How do I change the field value of multiple nodes? I'm working on a Drupal project where users can post classified ads. These are simply nodes created using a custom content type.

After 3 months, we want the user who created the node to receive a reminder email. We also need this email to be sent only once.

We're using Rules to send the emails.

This seems simple enough, but the implementation has been very difficult.

Right now, I'm stuck at limiting the number of times the email is sent. I have spent considerable time and effort online trying to find the answer. I still haven't found a straightforward explanation for this task. The closest I've seen is on this forum, which is why I'm asking for your help. It would be greatly appreciated.

= The setup =

There is a "Classified Ad" content type. It includes an "Email" field, and a (hidden) "Email sent?" field.

The user creates a "Classified Ad" node.

Views lists every ad that is more than 3 months old. The View has a VBO field. It also lists the "Email sent?" and "Sticky" values.

The "Send email" Rule is activated when the Cron runs. It has no conditions. It currently has three actions:

Load a list of entity objects from a VBO View. (This loads my list of 3 month old ads.)
Loop. (Loads the VBO list.)

-- Send HTML e-mail. (Sends email to the "Email" field value).

That works. So far so good.

My idea from here would be to add an action in the loop which would change the value of the "Email sent?" field from 0 to 1. I would then filter my View to hide all nodes that have this value.

= The issue =

I can't make Rules loop through my View and change the field value. I know others have had comparable problems and I've tried to apply the suggested answers but I didn't have any success.

I have also tried changing the Sticky value, but no success there either. I can change the first VBO item (at least for some tests), but I can't make Rules loop through all the items to update my nodes.

I have tried various approaches. The latest and (it seems) most promising is to use the Views Rules module. I installed it, created my "Rules" display for my VBO list, and added the Views loop to my Rule.

From there I tested all the combinations of Actions and Data Selectors I could think of to change the field value, but still no success. There were many tests.

Adding a "Set a data value" action inside my Views Rule Loop using "field-email-sent" as Data selector seems the most logical, but then Rules asks for a second Data selector, which makes no sense. When switching to direct input mode, I have to pick a "Node identifier", which makes even less sense. Attempts with other Actions or Data selectors have yielded similar results.

So either my approach is wrong, or one/more of my parameters are wrong. Either way, I need help.

How do I make this work?

You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag a user after such user was emailed for the first time. To actually flag such users, you should just improve the Rule you use to send those emails, by adding a rules action to flag that user with the flag you created.

Any time your existing rule is about to send another email, you can then verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no been flagged already (with the flag you created for this purpose)?".

If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.

PS: I'm assuming this is about D7 ...


File field fails to upload any files I've been having an issue with a file field that is not accepting any file uploads -- it ends up returning a 500 ISE on the specific field call (see image of the returned upload error). 1

The actual field itself is left over from a Database import of the site on an Acquia Cloud install. I know that it may be possible to re-create the field, but we stand the risk of losing existing records. Server configuration wise, it looks like the file directory is writable by httpd, so I don't see any issues there.

It doesn't help that the Acquia logs don't give anything useful. Any ideas?

Check the size of the files, maybe they are to big. Check the max. file sizes on your server and in Drupal!.

PHP configuration check:

check the following parameters:

post_max_size

upload_max_filesize

If these values are to small, you have to change them on your server in your PHP configuration (for example php.ini)


drush cc segmentation error when clearing theme-list I'm working on Vagrant/Virtual box and get a segmentation error when I drush cc theme list (8).

I'm new to Drupal and Vagrant and have no idea what this means. Would anyone be able to point me in the right direction?

Thanks

This turned out to be a problem with the Drush installation on my Vagrant box.


Ajax filtering a Drupal7 View I have a View where i would like to expose filters to permit the user to customize the view output. I know i can use exposed filters but, instead of a drop down (or checkbox/radiobutton of exposed filters) i want to put a list of DIV or LI that, when clicked, can update the view output through ajax. In which way is it possible using Views 3 and Drupal 7?

You can install Better Exposed filters in D7, edit the view and in the advanced fieldset change the exposed form style to "Better exposed filters", then in the settings for this you can choose how you want to display the filters, choose "Links". Also check the boxes for "Autosubmit" and "Hide submit button"


How do I set the default value of an exposed filter to a value that is not "-Any-"? I have a view with exposed filters, in Drupal 8. I need to set the default value of a filter to its title or custom text. I also need to unset/remove the - Any - option from the select list.

How can I achieve this?

Here is my code:

    function bootstrap_barrio_subtheme_form_alter(&$form, FormStateInterface
    $form_state, $form_id) {
        if ($form_state['view'] == 'office_locations_doctor_detail') {
            $form['field_doctor_reference_target_id_1']['#default_value'] =
            'Select Doctor';
        }
     }

Cleared the cache and reload the page but nothing changed.

Try this:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function bootstrap_barrio_subtheme_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ( $form_state->get('view')->id() == 'office_locations_doctor_detail'){
     // Set the default value as tid not the name of term.
     // Change 'Select Doctor' by the tid of it.
    $form['field_doctor_reference_target_id_1']['#default_value'] = '1';
    // Remove - Any - option.
    unset($form['field_doctor_reference_target_id_1']['#options']['All']);
  }
}


How to add class to embedded Paragraphs field-items? I have a Paragraph field embedded on a node type. The Paragraph field type allows for many different Paragraph Bundles to be inserted into the node.

My mark up currently displays as (Drupal 7 zen Theme):

<div class="paragraphs-items paragraphs-items-field-paragraphs paragraphs-items-field-paragraphs-full paragraphs-items-full">

How can I add a class after each field-paragraphs? I would want to do this so that each Bundle has it's own class.

I've tried the following in my themes template file but it adds a class around the entire field and not on each Bundle:

    function mytheme_preprocess_paragraphs_items(&$vars, $hook) {

  // This will remove all the current classes
  $vars['classes_array'] = "";

  // You can now add the classes you want in this array
  $vars['classes_array'][] = "myclass";
}

Drupal 7
You should be able to copy this function into your template.php file of your theme:
/**
 * Process variables for paragraphs-items.tpl.php
 */
function mytheme_preprocess_paragraphs_items(&$variables, $hook) {
  $variables['view_mode'] = $variables['element']['#view_mode'];
  $variables['field_name'] = $variables['element']['#field_name'];

  $variables['content'] = $variables['element']['#children'];

  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['element']['#field_name'] . '-' . $variables['view_mode']);
  $variables['classes_array'][] = drupal_html_class('paragraphs-items-' . $variables['view_mode']);

  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'];
  $variables['theme_hook_suggestions'][] = 'paragraphs_items__' . $variables['element']['#field_name'] . '__' . $variables['view_mode'];

  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

You should also be able to do this for individual item:
/**
 * Process variables for paragraphs-item.tpl.php
 */
function mytheme_preprocess_paragraphs_item(&$variables, $hook) {
  // your code here
  $variables['classes_array'][] = 'your-class';
  $variables['classes_array'][] = 'your-other-class';
}

After adding this function, clear the cache so it is registered. You can then check if either one are being called by adding a breakpoint or print 'called'; exit; if you do not have something like XDebug installed.
Note how the second function is paragraphs_item and not paragraphs_items. Both of these are defined as theme hooks in paragraphs.module.
You can even do this as well:
/**
 * Implements hook_preprocess_entity().
 * @param $variables
 */
function mytheme_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item' && $variables['elements']['#bundle'] == 'your_bundle') {
    $variables['classes_array'][] = 'your-class';
  }
}


Save language preference for future visit I would like to achieve this:When a user selects a language in a multilingual site,when he visits this site into future,the site remembers its language previous selection and shows this language for the user.
Is there a module for this or I need to write something with cookies?
thanks

Actually there are two modules, Language Cookie and Locale Cookie.  Both work about the same, but both have problems if you are using Varnish as a cache.  There was some work on Language Cookie done to fix this, but I haven't been able to get it working with Varnish yet.  If you're not working with Varnish, though, it works great.


Migrate site from dev environment to production server - 404 errors We completed development on our dev environment and I copied the files over from the dev server to the production server through FTP.

Then through back up and migrade module, I made a back up of the SQL database. I created a new database through Plesk with the same name, username and password. I then imported the SQL database into the new server through phpmyadmin. I go to the URL and get the Site Maintenance message (which is correct, I placed the site in maintenance mode before copying the files over) but cannot navigate to any sub pages. Generally I can add /user or /admin to the end of the url and get the login screen. However all I get are 404 errors.

It sounds like your .htaccess file is missing, or AllowOverride is disabled.  Clean URLs not working? Check your .htaccess file!


How to know which module is responsible for each database query? I enable the devel module and set it to Display query log.

Then on every page load I get a list of the generated sql queries. You can see an example of that list in the capture I uploaded. So far so good.

Is there any way to know which module is responsible for each database queries (in case that the query is generated by a module)?

If this is not possible. Is there any way to do an analysis of all enabled modules to see how them are affecting the general performance of the site?

For any modules you download from drupal.org, you can click on the function link within the where column and it will direct you to api.drupal.org and you can see the module there.

I couldn't find any settings that would enable showing where the call originated (file path) if the module wasn't an 'official' contrib.  A little digging and you can find the information within the devel.module.  Specifically, devel_query_table() receives $queries as its first argument.  $queries contains the rows that will be displayed and it does have the file path.

I created a quick patch to test this (Doing this does not imply that i think you should modify contrib modules in a production environment):

diff --git a/sites/all/modules/devel/devel.module b/sites/all/modules/devel/devel.module
index 0ebdef4..dd6aaa8 100644
--- a/sites/all/modules/devel/devel.module
+++ b/sites/all/modules/devel/devel.module
@@ -1482,7 +1482,7 @@ function _devel_print_object($obj, $prefix = NULL, $parents = NULL, $object = FA
*/
 function devel_query_table($queries, $counts) {
   $version = devel_get_core_version(VERSION);
 -  $header = array ('ms', '#', 'where', 'ops', 'query', 'target');
 +  $header = array ('ms', '#', 'what', 'ops', 'query', 'target', 'where');
    $i = 0;
   $api = variable_get('devel_api_url', 'api.drupal.org');
   foreach ($queries as $query) {
 @@ -1514,7 +1514,8 @@ function devel_query_table($queries, $counts) {
   'id' => "devel-query-$i",
   'data' => $placeholders . $args . $explain,
 );
 -    $cell[$i][] = $query['target'];
 +    $cell[$i][] = $query['target'];
 +    $cell[$i][] = '
' . check_plain($query['caller']['file']) . '
';
      $i++;
     unset($diff, $count, $ops);
 }

Here is the raw output on pastebin: http://pastebin.com/Ww5CkQsL

And a screenshot of the un-styled results:

This is a little rough looking as there are style sheets involved, but it gets the information.

Even better would be if the where column builder checked for the availability of the function on d.o but I'll digress, as I feel we may be entering, 'file an issue (feature request)' territory.


I cannot specify sender's address when sending email through rules Drupal ignores the "senders email" parameter when I send emails via rules.
I cannot even specify the "sender's email field" directly, putting directly the address like "sender@drupalsite.com" - the mail gets always sent from the default website address. (My goal is to get the email from a taxonomy term proper to a commerce billing - which I can access properly).
I tried both regular and HTML mail.
What can be the source of the problem?

Jeeeez, it was just the configuration of the mail server on my local development machine... Everything worked as it should on the drupal side.


How to assign ImageCache setting to an imagefield in content type For a self-created node type called 'Event' I added an image field.
Got all the modules going ImageCache, Imagefield, IamgeAPI, ….
under sitebuilding>ImageCache I made a setting called 'agenda-full-node-thumbnail' (agenda is dutch for calendar by the way)
I intended to assign this setting to the image field in Node type 'Event' and succeeded. But now I forgot how I did this.

The problem now is, since I put the site online, my pictures fail to reside in the directory /sites/default/files/imagecache/agenda-full-node-thumbnail and hence giving me a broken image link on my webpage.

Maybe I need to rename the path since I put it online, but can't figure out how I went about making this Imagecache setting and making it work for my Node type to begin with. And that's where I've been stuck for a couple of hours and it's driving me completely nuts.

in order to work, imagecache relies on a tmp folder that needs to sit on your server. While developing local the tmp directory is located under the local webserver directory obviuosly and that needs to be changed when you go online. Administer » Site configuration - then file system is where you change it do a directory that is compatible with a server on your host. Setting the permissions to 777 then allowed imagecache to store the necessary image files and solved my issue.


Creating account type where email not required to be unique I'm developing a platform for Drupal 8 where there are several account types: students, their parents, teachers.
The students are young and we want their accounts associated with their parents' emails for security reasons, and there are cases where the parent has two or more students on the system. Also, each parent and student will have logins to their own areas.
So I need to be able to create student accounts where the email address is not required to be unique. And for the student accounts I need the password management (forgot/reset) to be done by username, not email).
Is it possible? How can I achieve this?

This answer is untested and it should serve as a guidance. Use it at your risk.

mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'user' {
    unset($fields['mail']['constraints']['UserMailUnique']);
  }
}

If it doesn't work, try the following code.

$email_definition = &$fields['mail']['constraints'];
unset($email_definition['UserMailUnique']);

As DataDefinition::&offsetGet returns a reference, both should work.

Note that accessing the definition as an array is deprecated, but as long as https://www.drupal.org/node/2346329 is unresolved there's hardly anything else you could do.


How can I add password fields to the account creation page? My site has recently gone live, and I'm finding that a lot of users are getting confused while signing up for an account. I have "require email verification" enabled, so users are receiving their email with the one-time login link, but they don't seem be setting their passwords with this login. So they enter their details, save the profile and then, for whatever reason, log out and can't get back in as they never set a password.

I know they can request a password reset to get back in, but is there any way to add the password fields to the account creation page and still keep email verification?

Any help would be greatly appreciated,

Cheers,

Matt

Although it doesn't mention it on the module description page, this is one of the features of LoginToboggan, which also addresses a number of other common login confusions (ie: a user can log in with their email address or username, prompt for login instead of permission denied page).

From the documentation:

  Set password
  Ticking this will allow users to enter their desired password when they set up their user account.


Limit Taxonomy display in Term Reference based on criteria? I have Taxonomy called "Region" ex: (Region A / B / C)
Each user is linked to Taxonomy "Region" using Profile2 module (one person can be linked to multiple regions)
Content Type "Article" has a Term Reference field linked to same Taxonomy. (value = unlimited)

Requirement:
. In content type "Article", I am asking user to select the Region (as Taxonomy Select list) where this Article belong too - how do I limit the Taxonomy list based on the Region user have an access too?

ex: User1 is linked to Region A / User2 is linked to Region A & B; When User1  creates an Article, Term Reference Taxonomy to show "Region A" but when User2 - show both "Region A" and "Region B"

in SQL world, I would write something like this.

select t.name
from taxonomy t
where t.name in (select p.name from profile p where user_id = :%1);

How would you achieve this in Drupal without writing custom code?

p.s: My apologies - I am from database world and very new to Drupal; still learning Drupal lingo.

I achieve the behaviour described in the question with:

Entity Reference
Views

In my Entity Reference field I use these settings:

Target type: Taxonomy term
Entity selection > Mode: Views: Filter by an entity reference view
Entity selection > View used to select the entities: My custom view

In My custom view entity reference I have (most importantly):

A relationship: to the user referencing the taxonomy
A contextual filter: to grab only the terms the user "is linked to"

Related to this question - actually this is what brought me here, In some cases it easier to filter taxonomy terms using a get parameter. For example, I want my visitors to see only the cities of one country when adding a classified ad, I will have a view that produces this:

Morocco: q=node/add/ad?country_tid=1
India: q=node/add/ad?country_tid=2
Zambia: q=node/add/ad?country_tid=3

And on the entity reference view used on the ad content type I will add a contextual filter with a default value generated by this PHP code

return $_GET['country_tid'];

PS.
I tried hierarchical select, term reference tree and hook_form_alter. This solution is KISS.


Migration with unique index across multiple fields It is the first time I'm using the migrate module and I want to import some nodes from a JSON file and to specify a unique key that has two distinct fields. I.e so that the row is not imported or it's updated when the combination of those two fields values already exists in the database

id: import_json_entities
label: "JSON Entities"
migration_group: import_json_group

destination:
  plugin: entity:node

migration_dependencies: { }

dependencies:
  enforced:
    module:
      - my_module

source:
  plugin: url
  data_fetcher_plugin: file
  data_parser_plugin: json

  urls:
    - 'public://entitities.json'

  item_selector: Schema

  ids:
    - name
    - version

  fields:
    -
      name: name
      label: 'Name'
      selector: Name
    -
      name: version
      label: 'Version'
      selector: Version

process:
  type:
    plugin: default_value
    default_value: service

  title: name
  uid:
    plugin: default_value
    default_value: 1

  field_version: version

It works if I only leave "name" in the list of ids, but it does not import anything if I specify both "name" and "version" as id.

What I want is something similar with what you achieve in MySQL with:

ALTER TABLE `entities` ADD UNIQUE `unique_index`(`name`, `version`);

This is what I'm using in one of my imports:

source:
  ids:
    event_id:
      type: integer
    date_iso:
      type: string

I'm explicitly specifying the ID column type using type: integer or type: string.


How to use linkit package after uplaoding file with filedepot package? I am using File Depot to upload files.

What I want to do is to upload some images into the filedepot folders and then make a link to that files in my posts/pages/book pages/etc. Is it possible ?

What would be even better is to be able to find the files using LinkIt. Is that possible ?

this is an older thread, but maybe Linkit Upload is a nice solution for this problem.
With that module enabled you can upload files directly from the Linkit popup.


How can I make the coupon code field in commerce mandatory? Using D7 commerce coupon/discount modules. I need to make the coupon field mandatory. Every order needs a coupon code entered.

There is no standard "required" checkbox on the field and I tried using conditional fields module to no avail.

You must do this in a hook_form_FORM_ID_alter().

You wouldn't use hook_form_alter() unless you are checking on a dynamic form ID. In this case it's better to use hook_form_FORM_ID_alter().

The reason for this, is that hook_form_alter() is called on every form render and hook_form_FORM_ID_alter() is only called when that specific form is being rendered.

Add this code to your .module file to make the field required:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['commerce_coupon']['coupon_code'])) {
    $form['commerce_coupon']['coupon_code']['#required'] = TRUE;
  }
}


How do I use Views Global Filter with Geofield 2.x Exposed Proximity Filter? I am trying to set it up so that a views global filter  https://drupal.org/project/global_filter can set the distance and city for the proximity filter for Geofield? What are the steps to do this?

Add a filter that precedes that filter that is not exposed and creates the initial filter you want. Usually you can do this with most views handler filters, so it should work with the proximity filter.


How do you programmatically delete a field? I found this page: https://www.drupal.org/node/2012896 which lists this:

// Deleting field storage.
FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

but, of course, I get:  Fatal error: Class 'FieldStorageConfig' not found.

Any hints as to how this gets used?

Drupal 8 is using object-oriented programming (except for some procedural bootstrapping files and the *.module and *.theme files).

When trying to access static methods of a class without a namespace, the class is expected to reside within the same namespace of the file you use the class name with.

This is not true for classes provided by Drupal core or other modules, when you use them within your own module.

So you have to properly use namespaces. When checking the API docs for example for FieldStorageConfig and scroll a little down, you will find the correct namespace of this class. The same goes for the FieldConfig class.

So you could use both classes by altering your source code to:

// Deleting field storage.
\Drupal\field\Entity\FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
\Drupal\field\Entity\FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

However, it is best-practice to not prefix the class names by their full namespace, but use use directives at the top of your source code (after a possibly existing namespace declaration, if you are within the context of an own class).

This sums up to the following correct and working example:

use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

// Deleting field storage.
FieldStorageConfig::loadByName('entity_type', 'field_name')->delete();

// Deleting field.
FieldConfig::loadByName('entity_type', 'bundle', 'field_name')->delete();

PS.: When learning Drupal 8, it is always a good idea to check how other modules/core are doing it. You can search the code base for the class in question or use the API reference, which has a search function, and you may find plenty useful examples.


Drush hangs while executing any command I am experiencing a strange problem while running drush commands on newly installed server and newly installed drush(it's been installed with composer).
Exact the same configuration works fine on my local machine (composer, drush-dev, memcached with 11212 port), but for some reason it doesn't execute any command on my production server. I've already read this post, but it did'nt help, I am sure problem is not coming from my memecached config, I can open it from browser without any error (Memcache Storage: server 127.0.0.1:11212 (default cluster) - Connected - message from status report).

So, I properly installed composer (globally), successfully installed a drush-dev version, env PATH has been added to .bashrc file, I can only run drush command which outputs this help messages.. But if I run any other command in my drupal root driectory it just hangs with this debug output (for ex: drush status -vvvv -d).

Some addition info: 1. I digged into the drush files to find something and I found that drush calls _drush_bootstrap_drupal_login after _drush_bootstrap_drupal_full to login as uid=0, but somehow it can't login..
2. I am using Memcache Storage module as cache backend, It shows Successfull connection in admin report page, but somehow it doesn't see pecl memcache extension I think.. If I remove $conf['lock_inc'] = 'sites/all/modules/memcache_storage/includes/lock.inc'; from settings.php file drush does WORK, but the same configuration is working on my local machine.. Very strange..

How can I solve this?

I finally managed to work it, the issue was ralated to Memcache Storage module somehow, as it's lock_inc config is not compatable with pecl memcache extension, so the solution was a removing pecl memcache and install php's memcache module.

I think I need to post this to Memcache Storage Module's bug report..


"Show as expanded" selected but children menu items not displaying I am using a Bartik theme in drupal 7, and am trying to display a Page created using views under one of the Menu items. I've selected the "Show as expanded" for the parent item, however the child item is not appearing when I hover over the parent. Why would this be the case? How do I fix this?

I've displayed the same Menu in the sidebar, and there, it is displaying the child menu item. Also, I've tried disabling the css, and the drop down menu item is still not appearing...

Bartik theme is not designed by default to show parent items in Primary navigation section as expanded, even if you checked "Show as expanded" for each parent item in the main menu.

In order for you to make Bartik theme to render parent items and their children items; add the following code to template.php themes/bartik/template.php

function bartik_links__system_main_menu($variables) {
  $menu_name = variable_get('menu_main_links_source', 'main-menu');
  $menu_tree = menu_tree($menu_name);
  return drupal_render($menu_tree);
}

Note: make sure to clear Drupal cache once you apply the new changes.


How to update a field programmatically and keep the fields format and array structure? I'm trying to update a field with the format full_html. But when I'm updating the field, all the html tags will disappear and the old text is still there in the safe_value. So how can I update the the text in field and keep the existing structure and the html-tags?

I have tried this:

$node = $node_load($my_node_id);
$node->body['und'][0]['value'] = 'My new text.';

My field before editing

[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] =>
My old text.

                        [summary] =>
                        [format] => full_html
                        [safe_value] =>
My old text.

                        [safe_summary] =>
                    )

            )

    )

My field after editing

[body] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [value] => My new text. //All the html-tags are removed
                        [summary] =>
                        [format] => full_html
                        [safe_value] =>
My old text.
 //The old text is still there

                        [safe_summary] =>
                    )

            )

    )

Calling node_save() won't automatically re-load the node so you'll need to do it manually if you want to see the computed field values:

$node = node_load($my_node_id);
$node->body['und'][0]['value'] = 'My new text.';

node_save($node);

// Re-load the node from the db
$node = node_load($node->nid, NULL, TRUE);

// $node->body now has the values you would expect.

I just tried that and can confirm I get the same behaviour as you (the safe_value is not updated) if the call to node_load() is commented out.


Unique Classes on lists items I'm very new to Drupal 8 theming and I'm trying to replicate a random website to practice.

I have a problem recreating this part though:

I have a block with the latest news articles and a block with most popular.

I wonder if I could put unique classes on each item in the list (of latest news), that way I can make the widths different and make the floats work.

Is there anyway to do this? If I'm doing this wrong and there's a better way, feel free to tell me!

In order to replicate the desired behavior you can create several Views blocks and use the pager Display a specified number of items option. Then for each block change the amount and offset:

If you would do this with 3 different blocks and use offset/amounts of 0/1, 1/2 and 3/4 you should be able to stack them and have the desired result.

If you really really want to change the class per row, have a look at the great example Dynamically adding a CSS class to a view row with template.php where you can use a views preprocessor to set the right class per row.


How to create flexible number of columns in a Views table display? I have created a content type where each user is allowed to post exactly one comment on each node.

Now I want to create a table with UserID and all the node title as columns so that the table will look something like this:

Any suggestions?

To my knowledge you can't do this with (only) the Views module. But your question seems like a variation of something related to processing log messages. Digesting these messages is quite a challenge. That's why I've come up with my own "custom" report, as illustrated in this screenprint:

Within the "Report Execution Parameters" (collapsed in the screenprint above), I specify the search criteria of the log messages to be retrieved (like severity, User name, etc). And the red numbers are hyperlinks to get a drill down report of the specific messages for which I wanted more details (= to display the actual watchdog entries).

Some more details about the above table (to explain why it is similar to your question):

Think of the columns (with headers starting with "Msg Type:...") as your "Title XX". While each row (= different message) is like your User "1", "2", "3".
If there wouldn't have been any errors with (say) "Msg Type: Ajax" or  "Msg Type: page not found", then the corresponding column wouldn't have been created.
The red numbers (hyperlinks) are aggregated data, which in your case would correspond to commentXY (blank cells in your case would indicate that there is no such comment for user X and title Y).
Some columns (like "Msg Type: Error" or "Msg type: PHP") contain a value for multiple rows.

Refer to my answer to "How to gets analyts and generate visual reports from sessions?" for more details about creating reports (tabular displays) as in the above screenprint.

In case you wonder "How did you do that?" (without checking out my answer in the above link): There's a module for it ... it's called Forena ... And the clue in this specific case is to use Forena to create a "Crosstab table".

Disclosure: I'm a co-maintainer of the Forena module.


How to remove/hide 'to time' in time field I need to show only one time, no need of start and end time. Or I need to show only start time. Please anyone help me on this.

You can change in the field setting

Go to your content type, Now when we add a field of Date type. Then it will show a section for start and end date mentioned in the image

For already added field, you can not edit it i think because there is already content with end date. You can hide it if neccessary

Hope it will help!


What arguments should I pass to l() so that the generated link would open a new popup window? I have made my custom module in Drupal. I have a link that should open a popup window.

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

The link formatter function l() takes 3 arguments:

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

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

Use something like:

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

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

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

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

will give the javascript a target to use.


swiftmailer - html and email templates I need to create a HTML email, and someone suggested Swiftmailer. I installed that module, but it's not clear to me how to create HTML.

I enabled SwiftMailer as the sitewide default in the Mail System module, and I added a message like this:

$string = "This is a defined message: You have been send a message - \n" .$params['message'] . '\n click here<button type="button">Click me</button>';

But the HTML isn't picked up. The a tag is a link, but the button is not a button. I also can't apply inline styles.

Additionally, I will need to know how to create multiple email templates, which apply to different email types (I only saw online how to create one, swiftmailer.tpl.php)

Swiftmailer just sends emails ... it doesn't let you create HTML / plaintext content for emails.
For ease of setting this all up you likely want to use a module that supports the Mime Mail module and then at least use something like Previewable Email Templates (PET) module. Quote from the PET module page:

The Previewable Email Template (PET) module lets you create email templates, with token substitution, which can be previewed by the user before sending. The emails can be sent to one or many email addresses in a flexible way, and the recipients may or may not be Drupal account holders (users).
PET stores templates in a db table, not the variables table, so there is none of the memory usage which goes with the latter.
PET templates are in one place for easy management by site administrators. Emails can be sent one of three ways:

interactively, from a link.
programmatically, in response to any situation.
via a Rules action (D7 only).


hooks call order and hooks dependency I try to implement hook_menu() in a module and the code inside of this hook depends on another hook implemented in the same module Example:

function mymodule_menu() {
   $streamwrapper = file_stream_wrapper_get_instance_by_scheme('myscheme');
   if($streamwrapper !== false) {
      $directory = $streamwrapper->getDirectoryPath();
       .....
   }
}

and another hook function in the same (mymodule) module

function mymodule_stream_wrappers() {
  retunr array( 'myscheme' => array(...)
}

Apparently, hook_stream_wrappers() is called after hook_menu(), and file_stream_wrapper_get_instance_by_scheme() returns false during module installation process.

So, the whole idea works because Drupla will call hook_menu eventually and by that time stream wrapper will be in place and ready, but it seems too unreliable, IMHO.

Anyway, is it possible to control hooks order somehow? Or is there a better way to achieve desired result - retrieve stream wrapper in hook_menu after is has been known by the system?

Your problem is actually the opposite of what you're thinking. A call to file_stream_wrapper_get_instance_by_scheme triggers hook_stream_wrappers() if it hasn't been called already.

However, the problem is that the stream wrapper hook was already called before your module was enabled and the information from that is statically cached. So you need to clear the static cache to get your own stream wrapper:

drupal_static_reset('file_get_stream_wrappers');


How to 'drush sql-dump' all databases I have two databases I connect to with drupal. Does drush sql-dump back up all databases defined in settings.php?

If not how can I create dumps of both databases?

I've attempted using the --database=db_to_backup option but it throws an error:

sh: 1: Syntax error: "&&" unexpected
Database dump failed

Many thanks

If your database connection on settings.php looks like

$databases = array(
  'default' =>
  array(
    'default' =>
    array(
      'database' => 'mydatabase1',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'test' =>
  array(
    'default' =>
    array(
      'database' => 'mydatabase2',
      'username' => 'root',
      'password' => 'root',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

The following command will back up both the data bases;

drush sql-dump --database=default --result-file=default.sql; drush sql-dump --database=test --result-file=test.sql


Firefox can't download private PDFs I have an issue with FireFox where it can't download generated private file PDFs, yet Chrome has no such issue.

We populate PDF files with TCPDF and they get moved and copied into a few different directories. But ultimately, they're in directories in the private files directory behind the document root, with Drupal configured to look at this directory.

If I move any of these PDFs into the root of the site and access them directly with the URL, it works fine, but I wouldn't rule out the PDFs being corrupted in some small way. I've looked at the response headers when the file's downloading and all is in order, until I get this NS_ERROR_NET_PARTIAL_TRANSFER message and it fails.

I've run with xdebug enabled and stepped through hook functions of hook_file_download and the headers generated there all seem ok too.

Other private PDFs that aren't generated can be downloaded no problem.

I'm really running out of ideas of what it could be regarding FireFox and the private files system.

Hudri's comment ultimately led me to the answer, so huge thanks!

The real issue is the mismatch between the file's real size on the server and the size Drupal stores in the file_managed table, filesize column. Firefox will only download files that have matching values for the HTTP response's Content-Length header and the real length of the file sent to the browser. As to why the value's greater than the real one I'm still finding the answer to.


How to keep Display Suite CSS classes in code? I'm using DS in my D7 project along Features, so I've been able to keep all my new DS layouts, CCK, etc. in code, by generating a custom feature.

All good there... until I had to add some custom CSS classes to Display Suite:

Can't see how these values can be exported in code to persist in my project, rather than my DB. Nothing from the feature module either.

Is this actually possible? Thanks in advance :)

Seeing that you use Drupal 7, have you checked out the Features and Strongarm modules? Both modules allow you to export most configs as code.


Password request redirect to another page I click on forgot password page

it redirect me to http://example.com/user/password which is fine

now when i enter email id . it redirect me to

"http//example.com/user */. I want it to redirect another page

http://example.com/request-access

Any idea?

Thanks

You can add your own submit handler to the form :

function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_reset') {
    $form['#submit'][] = 'CUSTOM_form_submit';
  }
}

function CUSTOM_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'request-access';
}


How can I make the fields in my views "searchable?" So I have several views on my website with specific fields shown in table format. The search bar only searches through specific content, like pages, and basic pages. How can I modify the views or the search function to make it so that words typed into the search bar will search through the text entered for each field displayed in the views?

I would recommend checking out the Search API module. It's an extremely powerful extension to regular Drupal search, allowing you to use many advanced search backends and also integrates with Views to allow you to search on any field you wish.


Take over display of a content type node route I have a discussion content type. I would like the primary viewing experience (at "discussion/discussion-name") to be a cacheable form using a form mode.

Basically, I'm trying to create something like a web app experience where anyone who can view it, can edit it, so there is no point to separating view and edit, a more integrated experience is desired.

It feels like it should be easy, but I haven't found anything about how to override the routing for just one content type.

How can I override the route for a content type?

You'll need to alter the entity.node.canonical route to do this. You can do this via a RouteSubscriber::alterRoutes() in a custom module to have the route driven by your custom logic. In src/Routing/RouteSubscriber.php:
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

Then build the logic in your custom controller to redirect based on your node type, in src/Controller/NodeRedirectController.php:
namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Redirect to the edit path on the discussion type
    if ($node->bundle() === 'discussion') {
      return new RedirectResponse('/node/' . $node->id() . '/edit');
    }
    // Otherwise, fall back to the parent route controller.
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

Lastly, register your routeSubscriber service in mymodules.services.yml:
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Documentation is on drupal.org: Altering existing routes and adding new routes based on dynamic ones.


Views display product attributes with prices How do I create something like this with Views ?
This is my version in the making:

this is my view set-up:

You need to group your fields by the title. Specifically:

click on the settings button of the table format in your view and then select to group by the field that is the same in the 2 entries:

EDIT:

You can now hide your title field since it will appear in the group name:

and your final view (that you can theme according to your needs) will look like this:


theme_table drupal 7 issue - operator not supported for strings in theme.inc Although i have found the fix of this problem, but i thought of sharing with others.

Problem is if you mention $rows & theme_table like following:

$row[] = array('data' => drupal_render($form[$key]['alt_name']), 'class' => 'alt-ing-name-td');

$output = theme_table(array('header' => $header, 'rows' => $rows,'attributes' => array('id' => 'recipe-id')));

then you will get following error:

Fatal error: [] operator not supported for strings in theme.inc

To fix this problem you need to mention class & id values in array.
PFB, the corrections:

$row[] = array('data' => drupal_render($form[$key]['alt_name']), 'class' => array('alt-ing-name-td'));

$output = theme_table(array('header' => $header, 'rows' => $rows,'attributes' => array('id' => array('recipe-id'))));

Hope this will help.


What is the correct way to cache blocks by language? I have a multilingual site with custom blocks in the right-hand menu - the content of which is generated dynamically through the build() function of BlockBase and which changes depending on the interface language. I want to cache these once per language. Elsewhere I've used:

public function build() {
 $node = \Drupal::routeMatch()->getParameter('node');
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'node:' . $node->getId()
    ],
  ],
);

}

I've gone with this approach, which appears to work, although I'm not sure how to test that it isn't still processing templates on every call:

public function build() {
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId()
    ],
  ],
);

}

Is this the correct way to do it? I could find examples of the node: prefix in the docs, but nothing about language:

You should use the languages context, don't use tags here.

Like this: '#cache' => ['contexts' => ['languages:language_interface']],

You'll find more here: https://www.drupal.org/developing/api/8/cache/contexts


Remove all styling from views field view? I am using the views-field-view module to output the number of teachers I have in each school, so it's just a plain number. The parent view that this child view is embedded in is a table with some other information (see screenshot).

Is there a way for me to remove any and all formatting from the child view so that the final output looks like it's all coming from one view? As you can see in the screenshot, there is some misalignment with the numbers, and there is also a weird line above the numbers coming from the embedded view.

http://screencast.com/t/cFi0ctcZS

Thanks in advance!

Lukas

Yes, you have to override the templates of the child view to remove the markup you don't want.

You will might need to override (in order of how likely it is you need to override them in some way):

views-view.tpl.php
views-view-unformatted.tpl.php (if you are using the unformatted style. Otherwise whichever style template is relevant to your view)
views-view-fields.tpl.php

You need to find where the unwanted line is coming from in the markup/css and then find the template that markup is printed in, then override that template and remove the offending markup.

Alternatively you can likely style it out with css but I would favour the template override option.


drupal_add_js - working with inline but not file I have the following code which works:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}
?>

but the following doesn't:

<?php
function mymodulename_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'job_node_form') {
    drupal_add_js(drupal_get_path('module','conflict') . '/js/test.js');
  }
}
?>

The code in sites/all/modules/mymodulename/js/test.js is:

If(Drupal.jsEnabled) {
  $(document).ready(function() {
    alert("Hello!");
  });
}

And when I look in the page source when I'm in "job_node_form", I can see the js file loaded.

Edit:

I've found that:

$(document).ready(function()

is causing the issue. I've tried both $ and jQuery.

Is the inline code timed differently to the code in a js file? I'm wondering if the code in the js file runs before all DOM objects are loaded?

With Drupal instead of using $(document).ready, you can/should use Drupal.behaviors. Here is a boilerplate JavaScript wrapper you can use:

(function($, Drupal) {

  // Custom functions and variables can go here

  Drupal.behaviors.moduleName = {
    attach:function() {
      // Put your document's onload code here
    }
  };
}(jQuery, Drupal));

By the way, now that it's all done, to go back to the original topic, I wouldn't/don't use drupal_add_js() at all. Instead, you can do this:

<?php
if($form_id == 'job_node_form') {
  $form['#attached']['js'][] = array(
    'type' => 'file',
    'data' => drupal_get_path('module','conflict') . '/js/test.js',
  );
}
?>

This attaches the file directly to the form, allowing it to be overridden further down the line through the context of the form it belongs to.


Add next/prev link to image in drupal 7 I have a taxonomy with lots of nodes in it. Each node contains a large image. I want that image to be linked to the next node within the taxnomy. How can I do this in Drupal 7?

Please see the solution that should work !

Hook into node view using hook_node_view by writing a custom module.
Change the image field to a image with link using below technique

Get nid of current node using $node->nid;
Get taxonomy term id associated with node object using this technique.
Get all other nodes attached with same taxonomy term that you got in step 2 using taxonomy_select_nodes
From the list of node id's that you got in step 3 check the node id which is just greater than $node->nid and store it in variable $next_nid
Form a link using l function that should be markup for image field.

$overrided_image_field_value = l($image, 'node/' . $next_nid, array('html' => TRUE));

That should do the work !


Main menu not showing on cck type content items I have that annoying issue with my main menu not showing on nodes of one specific cck content type. The menu shows everywhere else and is set to do so in the block settings by using the Menu Block module.

I just don't get why it's behaving like this. Display of the node is done by using views & context / nothing special in the end. All fields which are visible are generated through views (in content type display settings, all are set 'hidden' - changing this, doesn't help).

Displaying the $page variable, the menu's aren't there, too. So which function should I have a closer look on for debugging?

The menu settings allow display everywhere (no restrictions), cache is disabled in the browser / doing drush cc often.

I'm accessing with user 1. (system is D7)

Issue was that the url patterns changed and I still had some old items - so for these the menu didn't display. Don't know why, but updating all content items of that type with the new url pattern solved the issue.


How to set up no result behavior of View field that uses "Views field view"? Im using "Views field view" module to display a secondary view inside a main view. The secondary view has a contextual filter. The problem is that when Im trying to set up no result condition it doesnt show up. I have tried this cases:

Secondary view no result: nothing

Main view no result (In settings of the field with sec. view): text

Output: nothing
Secondary view no result: 0

Main view no result (read "0" as no result option enabled): text

Output: nothing
Secondary view no result: text

Main view no result: nothing

Output: text

In the last case views display the text but if it is an html with arguments from the main view the tokens wont be converted.
If no result case is set to display 0 it will display nothing.

Views           7.x-3.0-rc3
Views Field View    7.x-1.x-dev
Drupal          7.9

How does Views know that The View Created By The Views Field View Module is not returning a result - on a row-by-row basis? I will hypothesize that Views is probably able to suppress the output of a field because very early on the process of creating/rendering the View, when the Views query is done, that field comes empty-handed from the database, and somewhere, internally, Views says: NO SHOW.

In my experience, I have never heard of a Views hook that allows a third-party module to short-wire this process and for example, arbitrarily command Views to render a field as it were populated, even if it is not, because a third-party module used that field as a contextual argument, created a view (or got data from somewhere else), and inserted that data into that otherwise empty field. This is what are you trying to do, and simply put, I am not sure if it is possible at all, at least in the way that you are trying to do it.

It would be possible however, for you to:

Create a primary view.
Create a custom preprocessor or template for that field. You would look for the proper name of the template by clicking your View's theme information link. A few caveats: For a preprocessor to be called, a matching template must exist first; Views won't recognize the preprossor (won't call it) if you declare it in a custom module, you will need to put it in your template.php; It isn't really necessary for you to create a preprocessor, however if you want to keep your templates clean (and any Drupalista worth his salt should want to) a preprocessor implementation is in order.
In your preprocessor, if that field is not empty, pass the results of that field to your secondary View's filter. This will require you to instantiate that View programatically.
If your secondary View returns any results, append those results to the current field.

So in essence, I think that what you want to do is 100% possible. I think your requirement will be possible (with Views) depending on A) How comfortable you are hacking with Drupal and it's theming layer, B) The performance requirements of your application.

If you are trying to do this for a high-performance site with a large number of visitors, I would be very wary of the solution that I am proposing, even with full Views caching turned on. So for performance and simplicity's sake, you can make your own database queries the ol' fashioned way. IMHO, your web server's CPU and whoever interacts with your site, clients and coders included, will appreciate it. Otherwise, if you still decide to go with my solution, here's a PROTIP:

Go to the Views advanced settings options.
Select show query.
Go back to your primary and secondary Views and test them. The query that is used to construct your Views will be revealed to you.
Copypasta this into your custom module for usage with db_query().
...
Profit!


How do I skip importing a duplicate item? I use unique field mapping, but instead of blocking the import on duplicates from CSV, it overwrites the data in Drupal and inserts the new value from the CSV file.

This is the default behavior with unique title field mapping:

"IF the title is duplicate THEN overwrite old item in Drupal with new item from spreadsheet"

But I'm looking for this behaviour:

"IF the title is duplicate THEN skip new item from spreadsheet, and keep old original item in Drupal intact"

I have field tamper, the item field AND the importer field all set to unique. It all works fine, but on duplicate feed imports, instead of preventing import of duplicate items, it overwrites the old field, and inserts the new duplicate...

My goal is for Drupal to PREVENT the duplicate field to be populated at all...the same way if you manually try to input a duplicate entry in manually imputing content, it shows an error and prevents you from submitting the form.

Is this even possible without custom code? Maybe with rules?

I have a hard time parsing your question. This is what I think you want:

If the source item has a title that already exists on the website, don't import this item.
If the source item has a title that does not exist on the website, import as a new item.

So if above are your only requirements, it would imply that you don't need to update existing content. In this case, the solution is:

On the processor settings, set "Update existing" to "Do not update existing".
On the mapping page, only set "Title" as unique.

From your story though, I sense that there might be more going on than just the above scenario, but I'm not exactly sure what it is.


Creating a view with multiple latest content types I am looking to create a view for my home page that displays the 3 last added items for 2 different content types (articles and news). Like 2 lists next to each other that also has the option to show more.

I already tried by creating a view with one of the 2 content types but I couldn't seem to manage to show both content types in the same view.

You can create two views, one for each content type, the configuration is the same, Filter Criteria should be Content Type (select in one articles and in the other news) you should sort by Authored on in DESC order, in the pager select Display a specified number of items (3) and More link (Yes).

Then you can add the two blocks to the page and add the styles with css.


Use external class in drupal 8 module with file name and class name I have created a module in drupal 8 .
I need to use a class which is in external file .

File name : drupal.php

Class name : class newman{...}

In drupal.php ( have many classes ):

<?php
namespace Drupal\mymodulename\lib;
class newman{
   public function new(){
       $dp = 'TEST';
       return $dp;
   }
}
?>

In my controller :

<?php
namespace Drupal\mymodulename\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\mymodulename\lib\drupal;

class mmController extends ControllerBase {
    public function man() {
          $this->man=new newman();
          $build['test'] = [
                            '#markup' => $man->new(),
                           ];
    }
}

Error: Class 'Drupal\mymodulename\Controller\newman' not found in Drupal...

How can I fix it ?

Your use statement is wrong. It should be:

use Drupal\mymodulename\lib\newman; - no Drupal on the end.

Aside from that, you should strive to inject dependencies in the constructor.

Also, there should not be a difference between the file name and classname. It makes it harder to debug and organize. The file should be named newman.php not drupal.php.

The error is referencing the fact that it cannot locate your class at the given namespace. It would help to brush up on PSR-4/autoloading in Drupal 8 as well as naming conventions and standards.


Imagecache action for image reflection I am using Drupal 7. I would like to display images with reflection effect.

For Drupal 6 there is module "Imagecache Effects" that offers this option.

For Drupal 7 there is "ImageCache Actions" module, but it does not offer reflection effect, but it provides Custom action effect for php code.

Can I add reflection with some custom php code?

If you're comfortable with modifying a little your theme, you can use a plugin like Reflection.js for jQuery.


How do i rewrite path field in views-view-fields.html.twig inside a href tag? i would like to rewrite the value of my view's path field in views-view-fields.html.twig template. I tried the following and the link is messed up.

{{ fields.title.content }}

my guess is it needs to be written with some type of filter combination and i looked everywhere and can only find examples on how to do this in a node.html.twig file but not in views templates. would somebody kindly advise on how to write this? Many thanks!

Probably because {{ fields.path.content }} actually is
/your/path
 and not just /your/path

So try with

If the above does not work

Try

Another possibility is that if you have Twig Debug turned on, this will screw up your template. Turning the twig debug off will fix it.


how to add to cart button in drupal 8 commerce? I am using zircon theme for my commerce site need to add cart and checkout pages to my site,how to create an add to cart button in drupal8 for product display which goes to cart page.

Wait until alpha3 is released, recreate your site, and use the core Add to Cart functionality on your product pages. Note: as we've been saying for some time, there is no alpha to alpha upgrade path, so you'll have to rebuild the site from scratch each time until we hit beta in late March.


Displaying fields in entity_reference data I'm using the entityreference module to provide my "Concert" content type with a "Program" field (machine name "field_program"), containing multiple "Song" nodes.  Each Song just has two fields: Title and Composer (machine names "title" and "field_composer").

What's the best way to control the display of a Program field within a Concert node?  I tried creating a "node--field_program.tpl.php" file, but that didn't seem to have an effect.  I also created a View that lists Song nodes in basically the way I'd want, but I don't know how to use that in the context of displaying a Concert node.

I'd recommend replacing program field with a custom View of Songs. That will allow you to pull any data that you'd need from the Song content type.

The least cumbersome (and I'd say flexible) way of doing involves two steps:

Create a View of Songs that will take a Node ID (NID as a contextual filter)
Override the field template for the Program field and instead of rendering the default template of the field - render a View crated in Step 1.

I'll detail each step, creating a View for this purpose can be somewhat complex, but that will give you great control over how you want to present the information.

STEP 1 - CREATE A VIEW

Create new View of "Content" of the type "Concert". Select Block instead of Page. Make it a view of "Unformatted List" of "Fields". In the number of items put 0 to display all items.
Add new "Contextual Filter" - "Content: NID". Provide default value: "content ID from URL"
Add new Relationship to "Entity Reference: field_program", which will give you a connection to each song selected in the filed Program for the particular node. Make relationship required.
Now remove all default fields that were placed in your View and add fields from the Songs content type (Title and Composer). Select the relationship that you added in previous step to each field (this is important, otherwise View won't work).
You can test your View by entering a Node Id from any existing Concert nodes into Views Preview placeholder for contextual filters. Without given contextual filter, preview will not show you any results (that's expected)

STEP 2 - OVERRIDE PROGRAM FIELD TEMPLATE

Copy field.tpl.php from modules/field/theme and place it into your current theme template folder.
Rename the file. Now here you need to decide if you wish to override the display of the field "Program" everywhere on your website or only when it is displayed in content type Concert.

field--field-name--content-type.tpl.php - Will target a specific field name within a specific content type.
field--field-name.tpl.php - Will target all fields of a specific machine name.

I'd recommend starting with the first choice - field--field-program--concert.tpl.php

Clear cache to let Drupal see your new template.

Now remove everything that was originally in that template, you can leave just the top comments for the sake of maintainability, etc. And add the code below - which will embed the view you create in the STEP 1.

<?php
print views_embed_view('machine_name_of_the_view', 'machine_name_of_the_block', $element['#object']->nid);
?>

$element['#object']->nid - is an argument that you can to your View. It is not absolutely necessary to place it here, because our View already has contextual filter that takes Content ID from Url by default. So additional argument just gives another chance to override that argument, or make sure that it will be passed appropriately.

That's it. Give it a whirl. Don't forget to test.


Exporting block settings in a Feature (Drupal 7) I am trying to learn about creating a reasonable workflow between a development site and a production site and I have decided to use the Features module to help accomplish this task.

On my front page I have a couple blocks that display newly added and top rated content.  I have used features to export these views but I do not see anyway inside of the Features module to export my block settings.  I set the new projects and highest rated blocks to show up in the content section of a page. I filter it to only show up on the front-page inside the view.

How to export these block settings inside my feature so I do not need to reconfigure them on each site?

You can export much more using Feature together with Strongarm and Features extra.

Strongarm gives site builders a way to override the default variable values that Drupal core and contributed modules ship with. It is not an end user tool, but a developer and site builder tool which provides an API and a limited UI.

Features extra supports: vocabularies; nodequeues (definitions); block settings; custom blocks (boxes).

Additionally UUID Features Integration provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module.


How to translate variable containing html with the i18n_variable module? I am trying to translate a variable with i18n_variable module. I am using the following code:

/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
  $variables['pm_email_notify_subject'] = array(
    'title' => t('My variable title'),
    'description' => t('The description', array(), $options),
    'default' => t('A good default value', array(), $options),
    'type' => 'string',
    'localize' => TRUE,
    'access' => 'administer checkout',
    'group' => 'my_variable_group',
  );
  return $variables;
}

This works as expected: I can choose the variable to be translated at /admin/config/regional/i18n/variable and when I do so, I can find its value via /admin/config/regional/translate.

But the problem is, that the variable contains HTML markup and although this works with the original content, the markup in the translated string gets converted to HTML entities. what am I missing?

A solution I used when I faced a similar problem in a different context is to preventively replace tag-markers by the corresponding entity in the content before it is processed.

Adapated to your case, it might look like this:

/**
 * Implements hook_variable_info().
 */
function MY_MODULE_variable_info($options) {
  $my_variable_content = preg_replace_all(
    '/<([^>]*)>/', '&lt;$1&gt;',
    'A good default value with some <tags> inside'
  );
  $variables['pm_email_notify_subject'] = array(
    'title' => t('My variable title'),
    'description' => t('The description', array(), $options),
    'default' => t($my_variable_content, array(), $options),
    'type' => 'string',
    'localize' => TRUE,
    'access' => 'administer checkout',
    'group' => 'my_variable_group',
  );
  return $variables;
}

This way, the finally rendered text keeps its "<" and ">" intacts.

But caution: it might be not appropriate to your case, so try it carefully.


Submitting new alter field I created a select/dropdown list and it works:
function hook_form_hook_ID_alter(&$form){
  $term_data = array(....) //array of key => values

  $form['elements']['location']['medical_name'] = array(
    '#type' => 'select',
    '#title' => t('Medical Area'),
    '#options' => $term_data,
    '#empty_option' => t('-None-'),
  );
}

but when I submit the webform, the field is not submitted. What I mean by submitted, when I go to results of the webform, there does not exist a medical_name field, thus the field is not registered. This is an alter function, so yes I am creating medical_name field on alter. I checked the formState->getValue and it is there. So I am wondering what may be the problem? I want to add the field programmatically.

This is not the solution I want, it is temporary:
In the UI, I created a select field with key medical_area
then with my alter function, it just override the webform and stored it there.
What I want:
Without having to create a select field in the UI, to be able to create a field through the alter function.


The website encountered an unexpected error. Please try again later( Olivero subtheme) Tried to make an Olivero subtheme. Followed drupal tutorials and after several unsuccessfull attempts ended in error "The website encountered an unexpected error. Please try again later" on both backend and frontend now I don't get the error anymore on the backend but I still can't access the frontend.
Error in drupal log looks like this
Drupal\Core\Asset\Exception\InvalidLibraryFileException: Invalid library definition in themes/mysubtheme/mysubtheme.libraries.yml: A colon cannot be used in an unquoted mapping value at line 1 (near "global-styling: version: 1.x "). in Drupal\Core\Asset\LibraryDiscoveryParser->parseLibraryInfo() (line 348 of /home/admin/web/mysite.com/public_html/core/lib/Drupal/Core/Asset/LibraryDiscoveryParser.php).

mysubtheme.info.yml looks like this
type: theme
base theme: olivero
description: My custom theme based on the core Olivero theme. It's meant for customization.
package: Custom
libraries:
  - mysubtheme/css
  - mysubtheme/js

regions:
  header: Header
  primary_menu: 'Primary menu'
  secondary_menu: 'Secondary menu'
  hero: 'Hero (full width)'
  highlighted: Highlighted
  breadcrumb: Breadcrumb
  social: Social Bar
  content_above: Content Above
  content: Content
  sidebar: 'Sidebar'
  content_below: 'Content Below (Flex Layout)'
  footer_top: 'Footer Top (Flex Layout)'
  footer_bottom: 'Footer Bottom'

core: '8.x'
core_version_requirement: ^8 || ^9

and mysubtheme.libraries.yml like this
 version: VERSION
 css:
   theme:
     css/custom.css: {}

global-scripts:
 version: VERSION
 dependencies:
   - core/jquery
   - core/drupal
   - core/drupalSettings
 js:
     js/custom.js: {}

Thank you for any help.

As @Leigh wrote in a comment one of the cause of my problem is that, sadly, OLivero doesn't support yet subtheming.


Add cardinality_unlimited taxonomy reference to custom entity Okay, so I'm getting an error that I think may be a Views bug, but I don't have enough knowledge about Views & SQL right now to be sure about that.

Here's the hook I'm using to install the new field into the poll entity, using drush entity-updates:

/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'poll') {
    $fields['cat'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Category'))
      ->setDescription(t('Category of poll'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => -10,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

Then, I make a view that would like to use this taxonomy term as a Contextual Filter.  I want to use the taxonomy term name rather than the ID, so I need to add a relationship.  I add relationship in the view and look for the Taxonomy Term relationship that has my description, "Category of poll" and select it.  The view complains about a SQL error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'poll__cat.cat' in 'on clause': SELECT poll_field_data.id AS id, taxonomy_term_field_data_poll__cat.tid AS taxonomy_term_field_data_poll__cat_tid FROM {poll_field_data} poll_field_data LEFT JOIN {poll__cat} poll__cat ON poll_field_data.id = poll__cat.entity_id AND poll__cat.deleted = :views_join_condition_0 LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_poll__cat ON poll__cat.cat = taxonomy_term_field_data_poll__cat.tid LIMIT 5 OFFSET 0; Array ( [:views_join_condition_0] => 0 )

The reason for the error in the above query is that the poll__cat.cat column does not exist, but it rather SHOULD be poll__cat.cat_target_id.

My question is: is this a views bug or a bug with the way I'm adding the field to the poll entity, and if it is a views bug:

How do I debug it? Where does views set the column name it's looking for?
Is there a hook I can use to change it,  and/or should I submit this odd case to the views project?

EDIT: I'm trying to use hook_views_query_alter and hook_views_pre_execute to try and modify the broken query to do what I want it to do, but it is incredibly frustrating, because all of the things are protected, and it is very inconvenient to access anything, considering the purpose of these hooks is to modify data.  I'm trying to look through the functions for ViewExecutable and the views Sql class, but I don't see anything that will help me change the column to what it should be!  Anyone who can help in any way, I will be so grateful.

Edit 2: It seems like this guy: Views doesn't like multiple entity references in my entity has had a similar problem.  I feel like this is a bug somewhere, or at the very least an issue with CARDINALITY_UNLIMITED being confusing to implement with entity references.

This is the best solution I have been able to come up with so far.  Answers are still welcome, because I still don't know:

Why this is happening, is it a views bug?
Could I have created the field in a way that using a hook to alter the query is not necessary?

What I ended up doing was using hook_views_pre_execute(Drupal\views\ViewExecutable $view) to get the query out of $view->build_info['query']->getTables() and then manually change the condition on my join table to use the correct column, which was not poll__cat.cat but rather poll__cat.cat_target_id.


Programmatically set the number of Multiple Value CCK fields in node edit form I have a filefield multi-value CCK field and I want to be able to set the number of values that can be added based on some condition when the user is editing the existing node. Is there a way to handle this through a form_alter? I do not want to set the number of values to "unlimited" for this case.

Use template.php and override the form functions and apply your logic there before rendering the form.
Example override function

/* Overiding the question creation form */

function yourthemename_question_node_form($form) {
//  dsm($form);
  // Modify title text
  unset($form['title']['#title']);
  // Set a default value for the title field
    // Set a default value for the title field
  $title_value =   $form['title']['#value'];
  if($title_value ==''){
  $form['title']['#value'] = t('Enter Title Here');
}
  else { }
  $form['title']['#attributes'] = array(
       'onblur' => "if (this.value == '') {this.value = '".$form['title']['#value']."';} this.style.color = '#333333';",
         'onfocus' => "if (this.value == '".$form['title']['#value']."') {this.value = '';} this.style.color = '#333333';" );
  $title = drupal_render($form['title']);
  $body = drupal_render($form['body_field']['body']);
  $form['body_field']['format']['#collapsed'] = FALSE;
  $form['body_field']['format']['#collapsible'] = FALSE;
  $form['body_field']['format']['#title'] = NULL;
  $body_filter = drupal_render($form['body_field']['format']);
  $tags = drupal_render($form['taxonomy']['tags']);
  $thematic_areas = drupal_render($form['taxonomy']['47']);
  $buttons = drupal_render($form['buttons']);
  $remaining_form = drupal_render($form);
    return '

'.$title.'
'.'
'.$body.'
'.$body_filter.'

'.$remaining_form.''.'	'.$thematic_areas.$tags.'
'.$buttons.'
'."

";
}


What is the alternative of hook_custom_theme in Drupal 8? I need to change the theme based in custom criteria.

Some nodes should be displayed with one particular theme and others with the admin theme.

In D7 I could simply use the pathauto module and set the node url to admin/[node-title]. It works in D7 because all url starting in admin will use the admin theme in D7.

An alternative way to do the same thing would be to use the hook_custom_theme() function in D7. I did not find any similar function in D8.

That is a service now. See \Drupal\user\Theme\AdminNegotiator for an example, which is registered as a tagged service:

theme.negotiator.admin_theme:
  class: Drupal\user\Theme\AdminNegotiator
  arguments: ['@current_user', '@config.factory', '@entity.manager', '@router.admin_context']
  tags:
    - { name: theme_negotiator, priority: -40 }


adding drop-down subject (html select) to contact form I would like to add a select field like a drop-down in the contact form to let user select the reason why they contact (contact, customer support, etc.)

Based on this (excellent) answer Adding check boxes to contact form, i’ve managed to create a field with check box :

source : Adding check boxes to contact form

How can i do that with a select ?

Solution :

You can choose in the "manage form display". The column "widget" allow to choose "Select list" (see screenshot)

There is a select form element that you can add to your buildForm or hook override, depending on how you are building your form:

$form['example_select'] = [
  '#type' => 'select',
  '#title' => $this->t('Select element'),
  '#options' => [
    '1' => $this->t('Contact'),
    '2' => $this->t('Other'),
    '3' => $this->t('Customer Support'),
  ],
];

This is from the Drupal documentation: https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Select.php/class/Select/8.2.x.


Link checker modules fails to detect a test broken link I downloaded, installed, enabled and configured the linkchecker module.  When I run it from the Drupal interface, it seems to be checking but I don't see in the report a test link (within ) that I have purposefully misspelled. This test link is to an external site.  Does it matter for the link checker module if my development site is not publicly accessible-- I think it is accessible only from campus.

Linkchecker version 6.x-2.7; drupal-6.26

Found Link checker works after  'run cron'

-- Found in video: https://www.youtube.com/watch?v=Hcl9iwIFZ2k
That a cron job has to be run after the configuring.
--  I had already set for automatic running of cron job.  For some reason it didn't work.
--  It worked after running cron job manually.
site-url/cron.php for D5 and D6

-- OR For Drupal 6.x, see in your site: Administer > Reports > Status report > Cron maintenance tasks > Run cron manually.

Steps for checking links:

Make sure link checker configuration is what you want
http://site-url/cron.php  in browser to run cron job (it yields blank page after the run)
See report for broken links and follow up specific links.

Here is another link for some relevant info on link checker module:
http://www.lullabot.com/blog/article/module-monday-link-checker


To pass the tid as an array value in callback funtion Am using drupal 7 site,am using a callback function to get the nodes list tagged to the particular tid,  the process is if i gave the tid value 25 it must return the nodes list which are tagged to this tid.As far this it is working fine.I wish to give the tid as multiple values ie as an array value, the thing am expecting is , if I give 25,17,28 (these are tid values) the result must be the nodes tagged to these tid's .Below is my function

'actions' => array(
        'selectNodes' => array(
          'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/taxonomy_resource'),
          'help'   => t('Returns all nodes with provided taxonomy id.'),
          'access arguments' => array('access content'),
          'callback' => 'taxonomy_service_select_nodes',
          'args'     => array(
            array(
              'name'         => 'tid',
              'type'         => 'string',
              'description'  => t('The vocabulary ids to retrieve, separated by comma.'),
              'source'       => array('data' => 'tid'),
              'optional'     => FALSE,
            ),
            array(
              'name'         => 'pager',
              'type'         => 'int',
              'description'  => t('Whether the nodes are to be used with a pager (the case on most Drupal pages) or not (in an XML feed, for example).'),
              'source'       => array('data' => 'pager'),
              'optional'     => TRUE,
              'default value'=> TRUE,
            ),
            array(
              'name'         => 'limit',
              'type'         => 'int',
              'description'  => t('Maximum number of nodes to find.'),
              'source'       => array('data' => 'limit'),
              'optional'     => TRUE,
              'default value'=> FALSE,
            ),
            array(
              'name'         => 'order',
              'type'         => 'int',
              'description'  => t('The order clause for the query that retrieve the nodes.'),
              'source'       => array('data' => 'order'),
              'optional'     => TRUE,
              'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
            ),
          ),
        ),
      }

can anyone please tell me how can I pass this tid value as array to the callback function used here?

I am sharing here some dummy data with you, it might help you.

{
    "tid": "25,17,28",
    "pager": 1,
    "limit": 5,
    "order": "desc"
}

   array(
                  'name'         => 'order',
                  'type'         => 'string', // it should be string because it can be either ASC or DESC
                  'description'  => t('The order clause for the query that retrieve the nodes.'),
                  'source'       => array('data' => 'order'),
                  'optional'     => TRUE,
                  'default value'=> array('t.sticky' => 'DESC', 't.created' => 'DESC'),
                ),

// Call back function

function taxonomy_service_select_nodes($tid, $pager, $limit, $order) {
  $tid_collection = array();
  $tid_collection = explode(',', $tid); // Here your tids are in array format and you can use in your code accordingly.
  echo $pager;
  echo $limit;
  echo $order;
}


Group Module: Join & Remove users from user account/profile 2? I added an entityreference to the user's Account so users can select what group they want to join (checkboxes). They check it and via a rule, it automatically adds them to that group. I did this for multiple Group Types.

Now i need it to remove user (unsubscribe) from group if "unchecked". Right now users keep on getting added if they select a new checkbox, but they are not removed from the previous group.

How can the we remove them from the now unchecked group and add them to the newly checked rule?

I found how to delete all group subscriptions on one rule. However, it removes all subscriptions, even those not found in this entityreference. How can we limit to add/remove users from only these group types?

Willing to pay for support on this issue.

Thank you.

I solved this. :)

I used the views_rules module to create a view that filtered a list of exactly what i needed (filtering the group type per user).

I then created a rule:

Before saving a user account
Condition if previous is equal to new saved (Negate). So it will only run if there are changes in the field in question.
Added View Loop i created. Add action > Delete entity mid from the view loop.

Done. This deletes or unsubscribes any unchecked boxes/groups.

Now to create any new memberships/subscriptions to selected groups...

I added condition...

-If field empty... do nothing

-Else

-Loop the field in question (gmem_created)

-Create new entity of type group membership

-Save a data value

Data: [gmem-created:group], Value: [account:field-yourgroup]

-Save a data value

Data: [gmem-created:user], Value: [account]

-Save entity

Entity: [gmem-created], Force saving immediately: true


form in a .tpl.php file This is the code in my template.php file.

function studiga_theme_theme($existing, $type, $theme, $path) {
    $items['add_property_form'] = array(
        'render element' => 'form',
        'template' => 'node--14',
        'path' => drupal_get_path('theme', 'studiga_theme') . '/templates/node',
    );

    return $items;
}

 function custom_add_property_form($form, &$form_state) {
    $form['first_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('First name')),
    );
    $form['last_name'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Last name')),
    );
    $form['address'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Address')),
    );
    $form['city'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('City')),
    );
    $form['state'] = array(
        '#type' => 'select',
        '#options' => array(
            'default' => 'State',
            '...' => '...',
        ),
    );
    $form['zip'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Zip')),
    );
    $form['email'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Email')),
    );
    $form['phone'] = array(
        '#type' => 'textfield',
        '#attributes' => array('placeholder' => t('Phone')),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );

    return $form;
}

This is the code in node--14.tpl.php.

                Contact Information

        <?php print render($form['submit']); ?>

But no fields are appearing - what am I doing wrong? You can't have a straight forward  in a tpl.php file can you?

Given your definition of studiga_theme_theme(), Drupal will never call custom_add_property_form() because there isn't any relation between the theme template you define, and that function. Eventually, you could implement the preprocess function for that theme template, and set there a variable that is passed to the template.

function studiga_theme_preprocess_add_property_form(&$variables) {
  $variables['form'] = /* define here the form */;
}

Now your theme template will get a $form variable.

Keep in mind that, except in a case, themes don't define forms; that is the task for a module. Eventually, themes can alter a form provided by a module, but (generally speaking) you will never see a theme that defines a form that is not for its own settings.


Newly created fields are not being displayed I have a content type "Article" with fields and data that was migrated from a Drupal 7 website.

In the admin/structure/types/manage/article/fields I added a new text field called "Test" with default value some of some HTML added.
Then, I went to manage form display and disabled that field from the form
Then I went to manage display of the appropriate view mode and enabled that field.
Flushed the cache

Reloading the article page doesn't display the newly added field. I believe it is because there is no value in it, but shouldn't adding a default value to the field pre-populate that field for all previous content belonging to that content type? Or am I missing something here?

Adding a default value doesn’t actually set any value in the field. To do that you must either edit the nodes you want the field on and click save, or write an update hook that sets the field value on all the nodes.

An update hook must be placed in a custom module’s .install file, in your case it would be something like:

function MY_MODULE_update_N() {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties('type' => 'article');
  foreach ($nodes as $node) {
    $node->set('field_name', $value);
    $node->save();
  }
}

As @4k4 mentioned if you have to update too many nodes as you have memory to, you can create batch updates using the &$sandbox, click here for more information


Is it possible to link images to different URLs? Using View's module it is possible to create a page to display some content horizontally. I have done this using carousel feature.
The content type that these contents belong to have an image_field and a body_field.
What I want from Drupal 8 is that when these images are clicked they should redirect visitors to a specific page (not to the node's / content's page).
Is it possible to do so or using html on body_field to place the images with a and img tags is the only way?
UPDATE:
At first I understood nothing from the answer below but a day later it just made sense like in the movie "Phenomenon"; I was struck by a mysterious light in the sky. Here is what I did:

Created a new link_field inside the content type that I am using on this View.

Went back to the content / node (under Content) where I wanted to add the link to the image and filled the link_field

Added this newly created link_field to the View and made it hidden by checking the box titled "Exclude from display".

Clicked on the image_field on View settings (under the FEILDS) and REWRITE RESULTS > check the box "Output this field as a custom link" (An empty area shows up to be filled here).

Went down and expanded the drop down list titled "REPLACEMENT PATTERNS" and found the link_field's name (The name you gave to your link field you have created it) and copied the string (something like {{ the_name_of_my_link_field }}).

Pasted this string into the empty area above then Saved, Saved, Saved to exit.

That's all!

You can do this using the Rewrite feature of Views.
These instructions assume that the view is set to show Fields (instead of Content or something else).  If you are not using fields, you can switch to fields under FORMAT in the Views UI.

Click the image field in your view and select the checkbox Exclude from display.
Add a new field to the view of type Custom text.
On the custom text configuration screen, check the Replacement patterns. This will include some twig tokens that you can use, including the image file. You can then use this token to add HTML to the Text field to get the link you want.  For example, {{ image }}.

Note that when using Views twig replacement tokens in a custom text field, order matters!  If your custom text field is above another field, it won't be able to get the tokens from the field(s) below.  In that case, you will need to click the flippy triangle to the right of Fields in the Views UI and choose rearrange, and then move the field that uses tokens below the field(s) that supply the tokens.
Another option is to open up the settings for your image field in Views and, under Rewrite results, click Output this field as a custom link and set the link options there.


Best way to migrate inline images in content fields to drupal 7 I am trying to create say "Articles" manually using scripts. Basically I am reading data from mysql table and creating nodes programmatically by looping the tables.

However in mysql content field which is the Body field of my Article content type has the data with inline embedded images and links.

 Some more dummy text.

What would be the best way to migrate images for such cases?

First off, there really can't be a best way without describing any requirements that can be objectively measured (e.g. speed, loc, number of steps, etc.). However, you can do a few things to do use those inline files in Drupal.

First thing is to sync (e.g. rsync) your content file dir under Drupal's publically managed file system. Depending on your organizational preference, this can be:

The default path (sites/default/files from your Drupal root).
A subdir in the default path (e.g. sites/default/files/assets)
Or a completely arbitrary dir; you can use any directory in Drupal root to be the public file system by configuring it in the admin/config/media/file-system admin page. In fact, you could make it the same directory as your previous CMS (assets/default).

If you decide to use a new directory (i.e. not assets/default) you'll need to either:

Create web server redirect rules (e.g. Apache .htaccess RewriteRule) from the old URLs to the new URLs.
Find old URL references in your imported content and replace them with the new URL references.

The first option is the better of the 2 since it accommodates other caches of your documents (e.g. cached web crawler versions of your content) that you can't update and it's less error prone (e.g. no breaking content because regex mismatches).

The last thing to mention is programmatically inserting records into Drupal's managed files system (its file_managed DB table). This isn't required for your imported articles to display, but if you ever want to manage the imported files through various Drupal file-management tools, it will be needed.

Since you're already using a PHP script to programmatically, you can add to the script a function to iterate over all sync'd files in the public directory and save them to Drupal.

//Assume $files is an array of file paths relative to the new public directory
//(e.g. 85/858dee4200c7f440cd6d4dba8814d56a8e81ab1f/original.jpg)
foreach ($files as $filepath) {
  $uri = "public://$filepath";
  $file = file_save((object) array(
    'filename' => basename($uri),
    'uri' => $uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($uri))
  );
}


Is it possible to add to different aliases to the same table in a dynamic query? I would like to use a example query for retrieving a full tree of the nested set model in a dynamic query.

SELECT node.name
FROM nested_category AS node,
        nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
        AND parent.name = 'ELECTRONICS'
ORDER BY node.lft;

The problem is that dynamic queries can't alias the same table. Is there a work around for this?

The best answer I have at this point is to simply execute the subquery first using fetchAssoc() to return an array.

$subquery = db_select('nested_category', 'parent');
$subquery->addField('parent', 'lft');
$subquery->addField('parent', 'rgt');
$subquery->condition('name', $name, '=');
$parent = $subquery->execute()->fetchAssoc();

$query = db_select('nested_category', 'node');
$query->addField('node', 'name');
$query->condition('node.lft',$parent, 'BETWEEN');
$results = $query->execute()->fetchAll();


Disabling some modules installed via a feature Is it possible to disable a module that was installed via a feature?

For example, I'm using a theme that came with a feature that installed a lot of modules, I realized that I don't need a bunch of the modules, but I can't disable them in the module page (the 'enabled' checkbox can't be toggled anymore).

Is it possible to just remove the feature but keep each individual modules configuration?

As far as I know, you can’t.

But, if you are 100% sure that these modules are not used by any component of your system you can do it in a hacky way. Only if you patch the feature’s .info dependencies and then revert it.

If it’s not very important to disable these modules (let’s say conflict with something?) do not do that!


Adding/ Editing list of people with photos I've created a content type called 'Cast'. Authorized users need to have ability to create a different list of cast members, add/edit their info, upload photo. Essentially, it's a team roster problem.

I'm having hard time figuring out how to solve this problem? What module is most suitable for this purpose?

You can do it using Drupal Core itself with out using any module. Just follow below steps to solve the problem.

Login as Super Admin
Go to admin/people/permissions/roles
Add a new role called "Cast Manager"
Give Edit any and Create new "Cast"  Content Type permission to "Cast Manager" role in admin/people/permissions/roles

That's it ! Now, users who have "Cast Manager" role can edit any cast content and manage them !


multiplying fields values Hi can someone help me with some field maths. I have taxonomy vocabulary called "plast" with several terms (large box, small box etc.) i have created field within the taxonomy called weight which is linked to each term. Now i have a nod where the user selects term from the taxonomy "plastic"and in the next field enters amount, what i want is to show i the next field "total weight" is weight from the taxonomy term multiplied by the amount.

thanks

Ok i think there must be an easer way using views so if  have taxonomy term "small box" which has a field "weight" linked to it with defaolt value 0.6  the folowing field in my nod is "amount" how do i get the result in views so i would see 0.6 multiplied by the "amount"

Thanks