Field level permissions in Drupal 7 What is the best way to create a piece of content with multiple fields... allowing users to edit the content as a whole yet blocking the ability to edit.

The setup I have is a piece of content that has 3 fields: Body, PDF, SWF... and a "Selector" (List Text) that's tied via dependancy. So the user chooses BODY, PDF or SWF and that's what available to edit and shown on the page when live.

What I want to do is add a PHP field... that's either:

greyed out (unable to edit) if your not admin...
doesn't show up in the Drop Down list... Can't select it if you can't see it
Shows up on the drop down, but the field doesn't show up in the editor without permissions.

I hope I'm making sense... I can provide an example if needed.

For Drupal 7, check out http://drupal.org/project/field_permissions.

  The Field Permissions module is a drop-in replacement for the Content
  Permissions module shipped with CCK.

So for Drupal 6, use the Content Permissions module shipped with CCK


How to set Form API's password_confirm in/visible depending on prior select list input? Neither visible nor invisible seems to work on password_confirm. Am I doing something wrong? What else can I try? This is my current code for a subadministrator form, where I'ld like to display the password_confirm only after a user is chosen:

$form['user_select'] = array(
  '#type' => 'select',
  '#options' => array('' => '- ' . t('None') . ' -') + _get_users_by_role('Subadministration'),
  '#required' => TRUE,
  '#description' => t('Chose account'),
);

$form['confirm_password'] = array(
  '#type' => 'password_confirm',
  '#required' => TRUE,
  '#description' => t('Type same password in both fields'),
  '#states' => array(
    'invisible' => array(
      ':input[name="user_select"]' => array('value' => ''),
    ),
  ),
);

A container around the password_confirm did the trick! Fieldset works too.

$form['user_select'] = array(
  '#type' => 'select',
  '#options' => array('' => '- ' . t('None') . ' -') + _get_users_by_role('Subadministration'),
  '#required' => TRUE,
  '#description' => t('Chose account'),
);

$form['pass_wrapper'] = array(
    '#type' => 'container',
    '#states' => array(
      'invisible' => array(
        ':input[name="user_select"]' => array('value' => ''),
      ),
    ),
  );

$form['pass_wrapper']['confirm_password'] = array(
  '#type' => 'password_confirm',
  '#required' => TRUE,
  '#description' => t('Type same password in both fields'),
);


How to enable the php option in Views contextual filters, provide a default value option? I have a text field called campaign and I want to set a contextual filter for this field, but I don't see a PHP option here. How can I turn this feature on? I don't see it anywhere.

You can php option in the filte using "Views Php" module

For installing this please follow such steps :
1. Download this module using https://www.drupal.org/project/views_php.
2. Install this module.
3. In views filter now you will get PHP option.


Drupal extra subdomains for some special nodes I have the following in mind and I'm not sure how to realize it nicely.

Drupal 7 serves many nodes from several different taxonomies
If I visit a taxonomy page e.g. example.com/category-one/taxonomy-term-one I get a list of all the corresponding nodes
If I click on one of the list nodes, I get to the page example.com/content-type/node-name
There are some special nodes in this list, when I click on them, I get to the following special page node-name.example.com. This page is exactly the content like example.com/content-type/node-name but in this case, only the subdomain URL is accessible and example.com/content-type/node-name doesn't exist to avoid content duplication.

The first 3 items are easy standard tasks: The Pathauto module handles all the taxonomy url alias tasks etc.

The 4th item is my problem. My idea so far: The subdomain node-name.example.com just references a special folder under the drupal root, which contains some logic to determine the name of the node according to the subdomain. With the given subdomain I get the node id and just load all the stuff from drupals db with a service implemented for this usecase.

Questions:

Ist it possible to give a drupal node an absolute url alias like node-name.example.com just like node-category/node-name?
Are there any problems going to be concerning drupals $baseurl/site configuration?
As I'm editing everything just over the example.com/node/node-id/edit there should be no problems with the editing functionality, no?
What remains to be done?

Did anybody had to fulfill a similar apporach and could share some thoughts regarding my approach?

Have you looked at the Domain Access module?

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

  By default, these sites share all tables in your Drupal installation.
  The Domain Prefix module (for Drupal 6) allows for selective, dynamic
  table prefixing for advanced users.

Basically you can assign a Node across any number of configured subdomains you've made drupal aware of.


I need a function to set a menu item's class to active based on if a keyword is in the URL Weird i know but as per the clients request i need to do the following:

if node being view is in a directory like this
/panelist/panelist-name

or this

/moderator/moderator-name

i need to set the a menu link in the main menu to active and also a sidebar menu item too.

now i know how to do the javascript part but i don't know to determine if /panelist/ or /moderator/ are in the URL, and also where i would put such code? i guess in template.php?

i tried doing in Rules but it didn't seem possible (still kind of new though!)

pseudo code would be
    if node being viewed contains 'panelist' or 'moderator' in URL
then
    echo out some javacript or
    set some menu  item class to 'active'

much thanks!

Something like this in your theme template can work:

function MYTHEME_preprocess_menu_link(&$variables) {
  if (menu_get_object()) {
    $parsed_path = explode('/', drupal_get_path_alias());
    $parsed_link = explode('/', drupal_get_path_alias($variables['element']['#href']));

    if (some_compare_func($parsed_path, $parsed_link)) {
      $variables['element']['#attributes']['class'][] ='active-trail';
    }
  }
}

You will have to implement some_compare_func yourself, or use a regular expression instead of exploding items, to do whatever matching needs to be done.

You can also check which menu the link belongs to (['#original_link']['menu_name'])

This is just a primer to get you going.


How to fix "Unable to save a field collection item without a valid reference to a host entity" error? I programmatically created a series of custom content entities which contain field collections. My site had an execution timeout error in the middle of entity creation and saving.

I can not delete some of these entities. Any attempt is met with:

  The website encountered an unexpected error. Please try again later.

  Drupal\Core\Entity\EntityStorageException: Unable to save a field
  collection item without a valid reference to a host entity in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->delete() (line 718 of
  core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

I need to be able to delete these host entities. They are still showing up in my entity list. I can edit and save them, I just cannot delete them.

How can I delete the host entities?

Sorry for the late reply but your question is a bit confusing and I would like to clarify the mentioned issue (message). Did you use ->setHostEntity($obj) at creation of the FieldCollection? I think that you created "ghost" fieldCollections. Have a look in DB if they was added there and you don't see the new FieldCollection at HostEntity in back end.

In my case, i was loading a FieldCollection Item which also did not have the HostEntity set and was struggling with the same Error Message (therefor the explanation). Later I figured out that the following procedure is correct - mention the saving of the HostEntity of the FieldCollection:

use Drupal\field_collection\Entity\FieldCollectionItem;

$fieldCollectionObj = FieldCollectionItem::load($fcId);
if($fieldCollectionObj->hasField('field_my_user_fc_field')) {
    $userObj = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $fieldCollectionObj->set('field_my_user_fc_field', 'my new value');
    $userObj->save();
}


How do I use and administrative form and save a message? I followed the instructions on Step by step guide to creating an admin form in Drupal 8.

I typed in a welcome text into the admin form and saved it, but after saving the form was empty again.

I am new to Drupal and php and don't know yet how to debug the code. I can not use Php-Storm because it is too expensive. Therefore I am using Visual Studio.

The website and database are running inside Docker. I mounted the folder for the modules, so I can write the module code from outside docker. I am working on a Ubuntu 18.04 machine.

This is the whole class:

namespace Drupal\welcome\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class MessagesForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'welcome.adminsettings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'welcome_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('hello_world.adminsettings');

    $form['welcome_message'] = [
      '#type'          => 'textarea',
      '#title'         => $this->t('Willkommens Nachricht'),
      '#description'   => $this->t('Willkommens Nachricht, die beim Anmelden erscheint.'),
      '#default_value' => $config->get('welcome_message'),
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('welcome.adminsettings')
      ->set('welcome_message', $form_state->getValue('welcome_message'))
      ->save();
  }
}

I just learned how to inpect variables with ksm() and found that the value is stored in the welcome_message variable.

Yes, I found the bug.

In buildForm is says:

hello_world.adminsettings

But it must be:

 welcome.adminsettings


Drupal node "ranking" based on views sorting I am creating a site where there are nodes (which are "causes") that users can donate to (i.e. buying a donation product using Drupal Commerce, which is sort of irrelevant, but just for the record).

I would like to display a "ranking" on each node based on how much money has been donated to that cause. It will be output something like "Rank: 50 out of 210".

My question is: What is the best way to do this?

I know how I could create a view and sort it by the criteria that I'm wanting, but then how to display on a node the index from the view... ? I don't know how to do that.

I've thought about figuring out a way to use Rules to assign a value to a field in the node whenever a donation is made... ? That might be a decent bet.

If anyone has any direction for me on this, I'd really appreciate it.

No need to make things that difficult; Views supports a field that display the sort index. It's labeled Global: View result counter.

It won't get you total results, but you can put that information in the header/footer with the Global: Result summary field.


Drupal7 | Time shows differently in Frontend and Backend The front end time shows as 3 hours behind the backend time of the same page.
The correct time is the one on the backend.
I set the time-zone correctly for the user and also
the time show correctly in the "Administration » Configuration » Regional and language » date and Time"

Here is the time that the page shows on the Backend (the correct time):

And here is the time showing on the front-end (3 hours behind)

And here is the code that I am using in the page template file:

`<?php print "Last Updated: " . format_date($node->changed, $type = 'medium'); ?>`

I am developing this Website locally on my machine (localhost).
Any Ideas to get the time correct on the front end?
Thanks.

Problem solved:

Just in case someone else got the same problem over this.
Here is what I was doing wrong (Thanks to Jay from Princeton University for pointing it out):

I set up the Date & Time for the administrator account under "/admin/people", but not the system-wide setting, which is at "/admin/config/regional/settings"

'Administration -> Regional & Language -> Date And Time' will show the date/time formats I have set up while respecting the user-chosen timezone (not the system-wide default time zone) so everything looks deceptively like it's how I want it until I log out.

So in short there is another time setting in .../admin/config/regional/settings
that I wasn't aware off.


AJAX form default values I'm using an AJAX form to match multiple values of a field to an other entity, to do so i've implemented the example we have in the ajax_example ( https://api.drupal.org/api/examples/ajax_example!ajax_example_graceful_degradation.inc/group/ajax_degradation_example/7 ), see ajax_example_add_more*

It is working great (except i would prefer being able to remove the field i want and not always the last one but we can't have everything).

When i submit the form, my chosen values are saved in database and the page is refreshed. The problem is that the form became empty, i might have multiple names for one fieldset and now i only have one empty textfield.

If we continue with the ajax_example, what i can do is this :

$myValues = variable_get('my_var', '');

And on this part add a default_value (let's assume that in my $myValues['name'] there is the list of the names)

$form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => $myValues['name'],
);

In the case where i add only one name, it will work. But if i have multiple name, it will only display the last one.

Do you know how can i do to recreate all the form as it is store in the db ?

Thanks by advance

[EDIT]

Thanks to sareed, i found the way to do so. I'll show the modification to ajax_example_add_more. In the example there is only one fieldset, in my work there is x fieldset so i will add $fieldsetName to know which one :

Change :

 if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }

By

     $myValues = variable_get('my_var', '');
     if (empty($form_state[$fieldsetName]['num_names'])) {

          if(isset($myValues[$fieldsetName])) {
            $form_state[$fieldsetName]['num_names'] =
              count($myValues[$fieldsetName]) > 0 ? count($myValues[$fieldsetName]) : 1;
          }
          else {
            $form_state[$fieldsetName]['num_names'] = 1;
          }
      }

AND

  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
  }

TO

  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => isset($myValues[$fieldsetName][$i]) ? $myValues[$fieldsetName][$i] : '',
  );

Loop through the myValues (only use the foreach if you are not already in a for loop) and use the appropriate array element:

foreach($myValues as $index => $name) {
  $form['names_fieldset']['name'][$index] = array( // Already using $i here. Are you in a for loop?
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => $name, // Or $myValues[$i]['name'] if you are already in a for loop (it looks like you might be).
  );
}

Depending on the structure of the array you may have to change this a little. If these don't work and you can't figure it out, add a print out of one of your smaller arrays using print_r to your question and we can help.


webform libraries dir location The webform status report states several libraries are needed.
After downloading the zip file.. and extracting it.  Where does '/libraries/' directory belong? ie: /modules/webform/libraries  Or ???

It's literally /libraries in your web root, not in a subfolder. This is from the Base-Level Directories section of the Directory Structure docs (which began life here):

  /libraries - All third party external libraries leveraged by Drupal, such as a WYSIWYG editor. This folder is not included by core, but used with many contributed modules.


Using token in Block title I want to use token to show user name in block title. But it is not working.
I tried like [user:name]

Thanks in advacne

The correct format is [current-user:name].


how can I use special Font awesome character in Twig link()? How can I use a special Font awesome character instead of the text parameter with `link($text, $url, $attributes)?

I tried the following code for the Contact us button, but it doesn't show the envelope symbol properly. Instead, it shows #xf0e0;.

{{ link('&#xf0e0;', 'base:contact', { 'class':['fa', 'fa-lg'] }) }}`

Is there any way to output that symbol without using the fa-envelope CSS class?

The point of the FontAwesome selectors is that you do not need to print out the Unicode equivalent for the character. FontAwesome usually works by adding a pseudo element before or after the HTML element using the class.

In this case, use the fa fa-envelope classes and optionally add in a class to hide the text with a text-indent or something.

{{ link('Contact Us', 'base:contact', { 'class':['fa', 'fa-envelope', 'fa-lg', 'contact-us-link'] }) }}


Redirect exclusion rule in .htaccess does not work I have a rule in my .htaccess to redirect all HTTP traffic to HTTPS,
and I'm trying to exclude some specific URL from redirect, so I added the negation exclusion rule:

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/my_url
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

But this doesn't work, http://example.com/my_url redirects to front page example.com. Is it interfering with some other rules? All are standard Drupal core .htaccess.

You're right, there's interference with other Drupal rewrite rules. If you have clean URLs enabled, you're rewriting each request as an argument to index.php. Add an additional check to exclude this other rule.

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/my_url
RewriteCond %{REQUEST_URI} !index.php
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


Change node author on node save with rules I have a very simple rule with Event "Before saving content" and Elements "Content is of type (page)" and would like the action to be something similar to "Change node author to UID X", which would be the UID I want.

I can't seem to be able to achieve that with the actions exposed. To test my rule I've been trying to display a message on the site when triggering the rule and it works just fine.

Any idea how to do that without having to write code?

This is on Drupal 7 (latest) with latest stable Rules version.

I think you can do this by adding a new action - "Fetch entity by ID", then selecting users and using that to update the node.


Getting form Array from a webform created with Webform module? Is it possible to easily get the form Array from a webform created with Webform module?

I want to be able to call a copy of the form elsewhere

thanks

First off you'll need to know the form_id. You can get this a million ways but the 2 I use frequently are using the devel module that has the dpm() function to display any variable you want to the screen. So in a hook_form_alter you can put dpm($form_id) and get it that way. Another way is to just view the source and find the opening form tag. The id is in there as well.

Once you have the form id you can use drupal_get_form($form_id) to get the form array.


How do I resolve an unnamed requirements problem during an update? I am attempting to update my Drupal 8.2 instance to Drupal 8.6.4.  I have faithfully followed the manual installations steps found here https://www.drupal.org/docs/8/update/update-core-manually.

I replace the core and vendor folders and replace all the files in the root with the 8.6.4 files.  I rename the 8.6.4 defaults.settings.php file to settings file, move my unique settings into that file and upload it to sites/default. I then visit update.php, but I get stuck at the requirements stage.

There is an error saying "Requirements Problem: Check the messages and try again."  There are, however, no messages.

I'm happy to keep troubleshooting this but I need to know where I'm going wrong.  How can I discover what the Requirements Problem(s) are?

Some Other Details

Both the database and the Drupal server are running in a AWS VPC.
The server is a linux machine: VERSION="16.04.5 LTS (Xenial Xerus)
Drush is not working or installed. The original sysadmin didn't install it as part of the Drupal installation and I haven't added it since.
Composer is installed but I've never used it to manage Drupal versions or dependencies.
Drupal is behind an nginx reverse-proxy.  I have the made allowances for Drupal in the nginx conf file as recommended here: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/.  Mostly just this rule  location ~ '\.php$|^/update.php' {...}
There are other non-Drupal tables in the same DB that Drupal uses.
Drupal tables are prefixed: drupal_
We use drupal in a headlessly.  A separate Node.js app interacts with Drupal via Drupal Rest routes and is also connected to the same DB as Drupal.

Issues I've already resolved

Missing sourcecode for hello_world module. Removed hello_world from Drupal table: drupal_key_value
$settings['update_free_access'] = TRUE;

Things I've tried:

checking the apache2 error logs. No errors thrown.
checking the apache2 access logs. Just shows access to update.php

Let me know if I should post any more information.  Also, if using drush or composer would help, I'm interested in getting those going on my site anyway, and would be happy to install them.  In summary, during a Drupal 8 upgrade, Drupal complains about Requirement Problems but never lists them. How can I discover what the Requirements Problem(s) are?

Since the database information was transferred into a new settings.php file instead of keeping the old one, it is possible that the the custom value for the path to the synch configuration directory is not found.

Reference: Upgrading Drupal

Look for the code:

$config_directories['sync'] = 'sites\default\files\your-config-folder

in the settings.php file & update it to match the address on your web server.

"This solution worked for me.
In order to find that config_gobblygook, I looked in docroot/sites/default/files and in there is a folder named config_ and then a whole bunch of letters and numbers. I copied that full name and then inserted it into line 247 of the settings.php file."

The same problem is described here with a similar solution.

Related:

Changing the storage location of the sync directory
How do I fix this Configuration Directory sync error?

Otherwise make sure the most recent nginx.conf file for Drupal is in use, as there have been changes to that to fix the update.php issue. See:

web /update.php sequence does not work with Drupal 8
Drupal 8 Nginx configuration on Homestead (update.php works ok)
Latest Version - NGINX


Date Repeat Node Generator Module I have a Drupal 6 site and am looking for a way to allow my content admins to set up repeat events. I have that set up, but all the repeats are not their own node. I want them to be their own node, so they will appear in my calendar block and in my views on their respective dates.

I've not been able to find a solution in Drupal 6. I found several modules and this one looks promising, but it doesn't seem to be working:
https://www.drupal.org/project/date_repeat_nodegen

The module's page on Drupal says:

  As part of the node editing form, you'll see a question prompting you
  to "Generate each date as a single node". Answering yes (the default)
  will ceate one node for each date in the repeating pattern you've
  specified, as determined by the Date Repeat API. Each node may be
  edited separately after creation and used in views. Answering no will
  create a single node using the repeating pattern, essentially
  disabling this feature for the node.

But once I activate the module and create a new event, I don't see this question in my form. :-(

Can anyone help me be either showing me a better way of doing this or by helping get this module working?

Thanks!

OK, I wanted to post that I figured this out. You have to go to the content type and enable "Repeat". For me it was in the vertical tabs of the Events content type. Once I did that and set it to the date field it worked. BUT the Date Repeat section in the Events content type edit form did NOT work. I just ignored this section altogether and once I create the single event and save, a tab appears above the content titled "Repeat." When I click on that, I see basically the same settings as I did when creating the node, but this time they actually work!!! –


Closing colorbox after submit I'm using colorbox module to load the login form, but after submit the form the page reloaded inside the "iframe" .

what i want to close the color box "iframe" and reloading the main page.

i searched for a long time but i can't find any solution.

Use
parent.jQuery.fn.colorbox.close();

for closing colorbox, when submitting form.

like,  add the onClick event inside the submit button code:

<input type='submit' value="Submit' onClick='parent.jQuery.fn.colorbox.close();'>


The installation directory "/root" is not writable - Error when install Drush i want to install drush on my server .

I want to install drush-toolbox project globaly on my linux server box so all users can use it

My server: Cpanel , Litespeed , Cagefs , Cloudlinux (centos 6)

my drupal version 7.5x

I try this article CLick here and after run this command:

curl -sS https://getcomposer.org/installer | php

I get this error :
The installation directory "/root" is not writable

I run this command : chmod 640 /root and chmod 644 /root  but give same error (not writable)

Please help me.Is any guidance for me?

The composer method for installing drush works, but is outdated. Use the drush documentation for the right instructions: http://docs.drush.org/en/master/install/

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('https://s3.amazonaws.com/files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init


Is there a better way of getting specific pieces of data from taxonomy_term_load()? I have a taxonomy that has several fields attached to it. If I do a taxonomy_term_load($tid) on a specific item, it returns a huge object with multiple levels of nested arrays. I know which "parent" item (i.e. field name) I want, so I can do something like this:

$track_tax = taxonomy_term_load($value);
var_dump($track_tax->field_track_icon);

But even this returns a lot of nested levels:

array(1) {
  ["und"]=>
  array(1) {
    [0]=>
    array(15) {
      ["fid"]=>
      string(3) "702"
      ["alt"]=>
      string(0) ""
      ["title"]=>
      string(0) ""
      ["width"]=>
      string(2) "36"
      ["height"]=>
      string(2) "36"
      ["uid"]=>
      string(1) "1"
      ["filename"]=>
      string(24) "strategies_at_retail.jpg"
      ["uri"]=>
      string(44) "public://track_icon/strategies_at_retail.jpg"
      ["filemime"]=>
      string(10) "image/jpeg"
      ["filesize"]=>
      string(4) "1129"
      ["status"]=>
      string(1) "1"
      ["timestamp"]=>
      string(10) "1338391429"
      ["type"]=>
      string(5) "image"
      ["rdf_mapping"]=>
      array(0) {
      }
      ["image_dimensions"]=>
      array(2) {
        ["width"]=>
        string(2) "36"
        ["height"]=>
        string(2) "36"
      }
    }
  }
}

I know I can get the uri by doing something like this:

$uri = $track_tax->field_track_icon["und"][0]["uri");

Is there a better way? Some other function that will return specific pieces? Or do I need to address it level by level?

The field_get_items() function is very useful for this sort of thing. It doesn't produce shorter code, but it's more structured and a lot easier to get your head round than the endless arrays of data:

// Get the items for a particular field
$field_items = field_get_items('taxonomy_term', $track_tax, 'field_track_icon');

// Get the first item (fields can have multiple items so field_get_items always returns an array)
$first_item = array_shift($field_items);

// Get the URI
$uri = $first_item['uri'];

Using that method has the added benefit of automatic language negotiation, so you can avoid having to get that from context or just relying on 'und'.

I should also say the use of this function isn't limited to taxonomy terms; you can use it to get field values for any type of entity.


Multisite- different localizations and domains but same codebase and user base I have an established site which caters to Australian market and now I want to launch a similar site for US market.

New site will have a different domain
New site will have different content

However, I want both sites to share code and users so that someone who has an account on Australian site should be able to log in to US site plus any changes in code should reflect on both sites.

Sorry I am bit a knoob and will appreciate some guidance.

You're going to have lots of fun with this one if you're a "knoob".

The module you want to look at is Domain Access. This will do pretty much exactly what you want to do. It's a slightly heavy configuration so if you are new, then you might struggle but you can probably get some assistance on #drupal-support on freenode.


How do I port my hook_alter module to D8? This is my D7 module (module name is ckeditor_show_blocks):

<?php

/**
 * Implements hook_ckeditor_editor_settings_alter().
 */
function ckeditor_show_blocks_ckeditor_settings_alter(&$settings) {
    $settings['startupOutlineBlocks'] = TRUE;
  }

All it does, it toggles Show Blocks by default on page load in the CKEditor when editing the page/node:

I'm trying to achieve same on D8. I did read some on hooks documentation, and it looked like same, so I didn't change anything, but the module won't apply when in editing mode, what I'm missing? Is hook format different? Does it have something to do with the fact that CKEditor is built-in feature in D8?

There is normal documentation on D7 on how to implement a simple hook module, but not so much about D8.

Considering that the Editor module in Drupal core is the equivalent of the Wysiwyg module for Drupal 7, and the core CkEditor module is the equivalent of the Drupal 7 module with the same name, I would say that the hook you are looking for is hook_editor_js_settings_alter() that, for a module whose machine name is ckeditor_show_blocks, it is implemented from the ckeditor_show_blocks_editor_js_settings_alter() function.

If you need to know the ID of the editor plugin used for a input format, you can get that from $settings['editor']['formats'][$format_id]['editor']; that is the case, for example, when you need to change settings if the used editor is the one implemented by the CkEditor module.

To make it clearer, the Editor module is the module that associate editors to the input formats used from a Drupal 8 site, while the CkEditor module in core contains an implementation of editor.


Fill in user reference from current user page while adding new content I have a view with appointments displayed at the user profile page (using pages for this) that is specific to that user.

While adding a node (appointment type) I can select the user(user reference) that the appointment is made with.

Now, I would like to add a link at the bottom of that view so I can add a new appointment and at the same time pass in the user id/name of the current viewed user, so I don't have to manually select the user again.

Any suggestions?

If you're using "Entity reference" module for the user reference field, you could use http://drupal.org/project/entityreference_prepopulate module which allows to set the entity id with an URL parameter.

For example, if the field name is "field_user_reference", and the entity you're creating is "appointment", you'll have to generate a simple link like:

  node/add/article?field_user_reference=UID

Instead, if you're using "References" module, you can install and enable http://drupal.org/project/userreference_url which does the same, although the syntax is a bit different:

  node/add/article?user_reference=UID

I hope this will help.


Import orders from xls/csv to drupal commerce I am trying to import orders from xls file to drupal commerce store.Is there any existing module for this, I found commerce_migrate and commerce_feeds module I am not sure if they can be helpful here could not find if any of the two module provides this functionality as not mentioned on project page.

I wrote a script to import orders. Here is the workflow I followed

imported all users using user_import module, the orders belongs to.
Created a custom database tables with columns needed to make an order.
Imported the excel/csv file to custom table after formating data.
Created a script to import orders and create customer profile linked to a order

Here is the script

/*
 * Helper function to facilate order import functinality.
 */

function mymodule_name_order_import_($email, $product_sku, $order_created_date, $quantity, $status, $billing_fields, $payment_method) {

  // Get product id.
  $product = commerce_product_load_by_sku($product_sku);
  $product_id = $product->product_id;

  $user = user_load_by_mail($email);
  $uid = $user->uid;

  if (!empty($uid)) {

    // Set order status.
    if ($status == "Pending") {
      $status = "pending";
    }if ($status == "Completed") {
      $status = "completed";
    }

    // Keeping order status to pending. -- Need to Change as per order. --
    $order = commerce_order_new($uid, $status);

// Save the order so its ID is assigned.
    commerce_order_save($order);

// Order created date in time stamp.
    $date = DateTime::createFromFormat('m/d/Y', $order_created_date);
    $order->created = $date->getTimestamp();

    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

//add products to order by ids array
    $product = commerce_product_load($product_id);

// Create a line item with quantity 1 and this product.
    $line_item = commerce_product_line_item_new($product, $quantity, $order->order_id);

// Save the line item to get its ID.
    commerce_line_item_save($line_item);

// Add the line item to the order using the wrapper.
    $order_wrapper->commerce_line_items[] = $line_item;

// Get Billing Profile.
    $profile_billing = mymodule_name_order_import_map_billing_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_billing[LANGUAGE_NONE][0]['profile_id'] = $profile_billing->profile_id;

// Get Shipping Profile.
    $profile_shipping = mymodule_name_order_import_map_shipping_fields($uid, $billing_fields);

// Map billing address to order.
    $order->commerce_customer_shipping[LANGUAGE_NONE][0]['profile_id'] = $profile_shipping->profile_id;

// Payment Method
    if ($product_sku == "25PDVDP") {
      $order->data['payment_method'] = "payment_commerce_2|commerce_payment_payment_commerce_2";
    }
    elseif ($product_sku != "25PDVDP") {
      if ($payment_method == "Credit Card") {
        $order->data['payment_method'] = "credit_cart|custom_import";
      }
      if ($payment_method == "PayPal") {
        $order->data['payment_method'] = "paypal|custom_import";
      }
      else {
        $order->data['payment_method'] = "na|custom_import";
      }
    }

// Save the order.
    commerce_order_save($order);
  }
  else {
    print "This user doesn't exists : " . $email;
  }
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make billing profile for.
 */
function mymodule_name_order_import_map_billing_fields($uid, $billing_fields) {
  $profile_billing = commerce_customer_profile_new('billing', $uid);
  $profile_billing->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_billing->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

//Business name(Required)
  $profile_billing->field_business_name[LANGUAGE_NONE][0]['value'] = $billing_fields['field_business_name'];

// Who runs your front desk?(Required)
  $profile_billing->field_who_runs_your_front_desk_[LANGUAGE_NONE][0]['value'] = $billing_fields['field_who_runs_your_front_desk_'];

// Email address for the front desk person(Required)
  $profile_billing->field_email_address_front_desk[LANGUAGE_NONE][0]['value'] = $billing_fields['field_email_address_front_desk'];

// Phone(Required)
  $profile_billing->field_phone[LANGUAGE_NONE][0]['value'] = $billing_fields['field_phone'];

// Save billing profile.
  commerce_customer_profile_save($profile_billing);

  return $profile_billing;
}

/**
 * Helper function to map billing fields.
 * @param $uid user id of user to make shipping profile for.
 */
function mymodule_name_order_import_map_shipping_fields($uid, $billing_fields) {
  $profile_shipping = commerce_customer_profile_new('shipping', $uid);
  $profile_shipping->commerce_customer_address = array(
    LANGUAGE_NONE => array(
      0 => addressfield_default_values()
    )
  );

// Full Name(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['name_line'] = $billing_fields['name_line'];

// Country(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['country'] = $billing_fields['country'];

// Address 1(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['thoroughfare'] = $billing_fields['thoroughfare'];

// Address 2
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['premise'] = $billing_fields['premise'];

// City(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['locality'] = $billing_fields['locality'];

// State(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['administrative_area'] = $billing_fields['administrative_area'];

// Postal Code(Required)
  $profile_shipping->commerce_customer_address[LANGUAGE_NONE][0]['postal_code'] = $billing_fields['postal_code'];

// You sould pass the entire $profile object as parameter.
  commerce_customer_profile_save($profile_shipping);

  return $profile_shipping;
}

function jh_order_import_run($jh_product_sku = '') {

  //$jh_product_sku = '25PDVDP';
  $result = db_select('jh_order_import', 'joi')->fields('joi')->condition('product_sku', $jh_product_sku, '=')->execute()->fetchAll();

  foreach ($result as $key => $value) {
    echo "<pre>";
    print_r($value);
    $country = array('United States' => 'US', 'Canada' => 'CA',
      'Australia' => 'AU', 'United Kingdom' => 'GB', 'South Africa' => 'ZA');
    $jh_bill = array('name_line' => $value->full_name, 'country' => $country[$value->country],
      'thoroughfare' => $value->billing_address_1,
      'premise' => $value->billing_address_2,
      'locality' => $value->billing_city,
      'administrative_area' => $value->billing_state,
      'postal_code' => $value->billing_postal_code,
      'field_business_name' => $value->billing_bussiness_name,
      'field_who_runs_your_front_desk_' => $value->billing_front_desk_name,
      'field_email_address_front_desk' => $value->billing_front_desk_email,
      'field_phone' => $value->billing_phone,
    );
    $payment_method = $value->payment_methods;
    mymodule_name_order_import_($value->email, $value->product_sku, $value->order_date, $value->quantity, $value->status, $jh_bill, $payment_method);
    print "imported " . $key;
  }
}

NOTE: the above script is use case specific, so it will need modifications per need, but might be helpful to start with. I am using drupal commerce API's to import orders, customer profiles that's all.


Avoid duplicates on a view based on results from another view I have a node type and two views:

One displaying the last 3 elements with a field marked as «important».
Another with 3 random elements, marked as important or not.

I don't want the views to repeat nodes.

Since the "lasts" views should always display the last 3 important elements, I thought about filtering the nodes on the random view, but I don't know how.

I managed to do it for a single node in another context. When viewing a node, choosing «Provide default value» with some PHP code combined with the option «Exclude», I can manage to hide that node from the views.

$node = menu_get_object();

if (isset($node->nid)) {
   return $node->nid;
}
else{
  return 0;
}

Suppose I can get the nodes shown on the "lasts" views programatically. Then what? This approach will only work to filter out a single node, not the three I'll get from that view.

Any ideas?

In the contextual filters, there's an option called «Allow multiple values» just above «Exclude». That option lets you return multiple values separated by commas (and) or mores (or).

So, I just use this code in the «Provide default value» field:

$my_view_name = 'videos';
$my_display_name = 'otros_importantes';

$my_view = views_get_view_result($my_view_name, $my_display_name);
if ( $my_view!=null ) {
  foreach($my_view as $view_row){
    $nodos[]=$view_row->nid;
  }
}

if(isset($nodos)){
  return implode(",",$nodos);
}
else{
  return 0;
}

And that's all, the nodes shown on that display are ignored.


How to skip empty and missing values from a migration I'm trying to skip fields that are not present in my source file or that are empty, but I keep getting "Migration failed with source plugin exception: Passed variable is not an array or object"

This is what I've tried in YML:

field_contact:
    -
      plugin: skip_on_empty
      method: process
      source: contact_array
    -
      plugin: sub_process
      source: contact_array
      process:
        target_id:
          plugin: migration_lookup
          migration: import_contact_json
          source: Name

and

field_point_of_contact:
    plugin: sub_process
    source: contact_array
    process:
      target_id:
        -
          plugin: skip_on_empty
          method: process
          source: name
        -
          plugin: migration_lookup
          migration: registry_import_pocs_json
          source: Name

Both of them have the same output (i.e. the error described above).

Can someone point me in the right direction, please?

It is difficult to help without seeing the structure of your source file (at least 1 sample record). But, here are some pointers:

At first glance, the error message says something about a source plugin exception. I believe the error might be stemming from the source plugin configuration.
The approach you are taking with skip on empty seems to be in the correct direction.
Depending on the data that the field contains, you might have to handle it differently. I usually add the following to debug exactly what is being received by a particular field process. Also, make sure that the value being sent to the migrate_lookup plugin is an array.

# ...
process:
  field_point_of_contact:
    - plugin: callback
      callable: print_r
      source: name
# ...

Have you tried removing the skip on empty part? I don't remember correctly, but migrate lookup might be skipping empty values by itself.
An array with empty strings is not considered empty. If your source provides values like [''], you might have to send the array through an array_filter() to remove empties.

I hope this helps. If it doesn't, you might want to share one row of fake data.


Views Slideshow missing JS files Views Slideshow on Drupal 8 gives me all kinds of 404 errors loading the js files. Missing files:

/libraries/jquery.cycle/jquery.cycle.all.js?v=3.0.3
/libraries/jquery.hoverIntent/jquery.hoverIntent.js?v=1.9
/libraries/json2/json2.js?v=2

Isn't the module supposed to take care of these dependencies?

Any tips on how to solve it?

Only downloading this module does not work. It has dependencies. You have not installed the required JS filed which required by module. Those all are dependencies and required by module to work properly. Here is the step wise procedure for installing Views slideshow properly for D8.

In the procedure steps, if you read 4th step it states that,

  Download the latest version of the jQuery Cycle plugin place it inside the jquery.cycle directory. The filename should be:
  jquery.cycle.all.js

This is just example, follow all the steps properly then only this module will work properly.


Using ftp wrapper in file_copy Can I use php ftp wrappers using file_copy or file_move. like this:

file_copy($file, 'ftp://user:pass@site.com/file.flv', FILE_EXISTS_RENAME);

Or is this limited to drupal default wrappers?

And if I can't, do I have to use drupal built-in ftp hanlder(FileTransferFTP Class) or I'm allowed to use my own php ftp functions(ftp_put)?

Which one's better?

I don't know what type of file are you trying to copy over the FTP server, but I did something like that once. This is what I did (it might give you an idea):

I created a content type where I added all the fields for the data I was collecting (like 10 fields)
Then I created an small module that will query the database and will create a CSV file from the data entered on the content type (I applied some logic to the data as well needed for my project)
I use the Drupal default file functions to name the file, placed on the define directory and avoid been overwritten by following exports.
Then on the same small module I created an small function that will read the directory content where the CSV file was and upload it to and FTP server.
When all this was done I use the "hook_cron" to create an small function that will do all that for me.

Note: in my project I created an small admin interfaced where I entered a couple of settings like the name and location of the local directory where the CSV files will be stored as well as the FTP credentials (the client wanted to have there as well) and the location on the FTP server as well.

Note 2: I know this module is good with moving media files: http://drupal.org/project/media_mover/

Thank you.


What is the best way to extend \Drupal\node\Entity\Node? When dealing with nodes on Drupal 8, we usually receive an instance from \Drupal\node\Entity\Node, that is great in many aspects, but i'm not sure on how to extend it so that I can use classes that represent something in my own domain, rather that generically using Node. I can make this here:

class Video extends \Drupal\node\Entity\Node {}

Ok. But to have Video::load() and that sort of things, i'm seeing that I need to probably also extend NodeStorage, because everything returns a Node class and type changing seems to be not so easy in PHP from what i'm seeing until now. I'm not sure if this is really the way to go.

I really like to work extending Node(I used to extend EntityDrupalWrapper on D7), as it becomes easier for newcomers to the project and to have stuff like $Video->getFileUrl()

Any ideas?

You shouldn't extend Node but rather \Drupal\Core\Entity\ContentEntityBase or \Drupal\Core\Config\Entity\ConfigEntityBase.


Where is the template for the promoted to front page items? I want to add some elements and icons into the promoted items template but I can't find where this template is located.

For example, right now my page is rendering:

Sample

    //blah blah blah

    //blah blah blah

Instead, I would like to add things like:

Maybe some other stuff

Sample

    //blah blah blah

    //blah blah blah

Or anything else I want in the future.

This is tipically done in node.tpl.php in your theme. Just keep in mind that this template works for any node, so you should introduce some logic to check if the node is promoted, e.g.

<?php if ($node->promoted) { ?>

Maybe some other stuff

<?php } ?>


In hook_node_insert drupal_goto with alias name not working In hook_node_insert() i have used drupal_goto(), to go to the newly created node with alias name of it, but id doesn't work.

I have already created url alias with patterns for that content type.

$alias = drupal_get_path_alias('node/'.$node->nid);
drupal_goto($alias);

If i give drupal_goto() with nid it works.

drupal_goto('node/'.$node->nid);

What is the issue with respect to alias name not working or how to get alias of newly created node and get it redirected to view page of it with alias name as url.

Any ideas or suggestions? Thanks in advance.

[Updated code]

This is the code which i am trying

function hook_node_insert($node)
{
    if($node->type == 'product')
    {

        $_SESSION['product_node_nid'] = $node->nid;
        $banner = $_SESSION['banner'];
        $theme = $_SESSION['theme'];
        $params = array();
        $params['node'] = $node;
        $site_email = variable_get('site_mail', '');
        if(($banner || $theme) || ($banner && $theme)) {
            drupal_goto('payment-approval');
        }
        else {
            //$alias = drupal_get_path_alias('node/'.$node->nid);
            module_load_include('inc', 'pathauto'); // include the inc file for Pathauto module
            pathauto_create_alias('node', 'insert', 'node/'.$node->nid, array('node' => $node), $node->type, $language->language); // Language is optional
            $alias = drupal_get_path_alias('node/'.$node->nid);
            //$alias = drupal_get_path_alias('node/'.$node->nid); print_r($alias); exit();
            drupal_goto($alias);
        }
    }
}

I checked the drupal_goto and found out that you must provide the path for parameter. You can't use alias for drupal_goto. So i think you can solve your problem like that:

While you create node. You will also create the alias for that node. The reference for create the alias for node here. In your code just normally redirect like that

drupal_goto('node/'.$node->nid);

After that you will install Global redirect module. This module will have responsibility to redirect your node/nid to your node's alias

[Updated]

Can you try to generate the alias by using the Pathauto. So can you put these code in hook_insert()

function yourmodule_node_insert($node){
  module_load_include('inc', 'pathauto');
  pathauto_cleanstring($node->title);
  $node->path = array('pathauto' => TRUE );
  drupal_goto('node/'.$node->nid);
}


How to Remove read more link from front page Possible Duplicate:
  Remove links 'read more' and 'Add new comment ' on the home

I user zen theme and i tried this question answer Remove the 'read more' and 'Add new comment' links on the home page but when i apply it i face server error message. also i study that drupal core doesn't have a setting to disable read more link.

So, How can i remove read more link from front page on zen them?

The problem is in the node rendering, not the page rendering. Its a lower/smaller level than the preprocess page. You can use node template overrides such as "node-fonts.tpl.php" where "fonts" is the name of the node type. You will copy "node.tpl.php" to make this then modify it to your liking. This template is found in "[SITE ROOT]/modules/node/". Copy this to your theme folder. When I do this I create a subfolder called "node" to help organize the theme overrides.

If you want an easier solution then I would use ConTemplate (otherwise known as Content Template). This will allow you to control this from the content type admin config (creates a template tab which has options for the teaser and the full node). This also provides details about the available variables and sample data from the last inserted node of the type you are looking at.


Display custom output if field doesn't have value in hook_field_formatter_view Display custom output of field in hook_field_formatter_view() if field is empty.

function hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  //My Snippet to display custom output
  // Here $items variable is empty.
  $element = array();
  switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (!isset($items[0])) {
      $output = generate_custom_output();
      $element [0] = array ('#markup' => $output );
    }
    break;
  }
  return $element;
}

my custom field is empty, no $item is available. Now I want to return custom output. But above code doesn't work.

Please suggest any solution.

I am able to do this as below in hook_field_formatter_view().

switch ($instance ['widget'] ['type']) {
  case 'my_widget' :
    if (empty ( $items )) {
      $output = generate_custom_output();
      $element[]['#markup'] = $output;
      $element ['#items'][] = array('value' => $output);
      $items[] = array('value' => $output);
    }
  break;
}

If anyone have better solution please provide.


How do I pass a value from the url to a custom field in the registration form? I know variations of this question have been asked but I haven't found any with this specific set of characteristics. Also, the only programming language I know is python. I don't know PHP at all.

I want to be able to pass the value from a url parameter into a custom hidden field in the registration form.

I've tried using theme functions, template files, and hook_form_alter() but I haven't been able to get any of these to work.

So far, I've been able to add the custom field but I can't seem to hide it, let alone be able to pass the value to it. I am able to add html to the form via the template file but that's about it.

I based my attempts on this site: themery

This is the code I tried to see if I could alter the label for email.

function acq_dmc1_form_user_register_form_alter(&$form, &$form_state) {

$form['mail']['#title'] = t('E-mailzzzzzz');
$form['field_recipientid']['#title'] = t('QualID'); //this is the custom field

}

...but it didn't work.

this is the form id:

<input type="hidden" name="form_id" value="user_register_form" />

this is the HTML that's rendered for the custom field:

<input class="text-full ckeditor-mod form-text" type="text" id="edit-field-recipientid-und-0-value"
name="field_recipientid[und][0][value]" value="[url:path]" size="90" maxlength="25">

EDIT: June 17, 2013
Someone gave me this code as a solution but I don't understand if it will work or how it will work:

function passval_user_presave(&$edit, $account, $category) {
    $fields = array(
    'RecipientID' => array('fieldname'=>'field_recipientid', "type"=>'complex'),
        'mail' => array('fieldname'=>'mail', "type"=>'simple'),
    );
    $urlargs = drupal_get_query_parameters();
    foreach($fields as $key=>$field) {
        if(isset($urlargs[$key])) {
            $value = ($urlargs[$key]);
            $value = intval($value);
            if($field['type'] == 'complex') {
            $edit[$field['fieldname']] = array('und'=>array(0=>array('value'=>$value, 'format'=>'', 'safe_value'=>$value)));
        }
        else {
            $edit[$field['fieldname']] = $value;
            }
        }
    }
}

You can create hidden form elements in drupal simply by setting the type to hidden. So in your case, it could be achieved like so:

$form['field_recipientid']['#type'] = 'hidden';

You can access URL arguments in drupal via the arg() function. So if you want to pass something to the user register page and set it in your field_recipientid, you could do it by sending the user to the registration page via "http://example.com/user/register/MLRP_8UByesUEfeeIA".

Then from your same form alter function, just call arg(2) to get the third item in the path and set the value like so:

if (isset(arg(2))) {
  $form['field_recipientid']['#value'] = arg(2);
}

Note for anyone else thinking of doing this on other form elements that aren't hidden (e.g. text fields), use #default_value. If you set #value on text fields, drupal forcable only accepts that value, and disregards any edits to the text field value, the user might have made.

For more information on drupal's form api, see the forms api reference page on the drupal api site.


'Order of importance' type field I'm using an Entityform to create a survey for a client, however one of the types of question they have is to rank a number of options in terms of importance to the user.

Similar to how the draggableviews module work would be the ideal, but I know that draggableviews changes the global setting for that list, rather than a per-user response.

Is there any way to achieve something like this?

Could you use "tabledrag", the code draggableviews uses to do dragging? It is basically javascript acting on an html table, with a weights column to remember the order.

Have a look at how the block module uses it (but bear in mind block is more complex because it has multiple regions to manage).

For tabledrag to work you need your questions in the form of a html table, which you then extend using the render array "#type" = "tabledrag". It is possible to configure tabledrag in Javascript, too.


Using Drush without typing drush every time This might be a dumb question and is probably more of a general question for using the command line, but how can I create a command setting where drush is set in the current terminal session. I already have the correct path set where I don't have to type the full path to drush every time, but I'd like to be able to open the terminal up with drush set in the session until I exit the terminal.

For instance instead of opening up terminal and having to type drush everytime:

$ drush dl ctools

$ drush en ctools

$ drush .... (everything else that you want to do)

I can open up the terminal where drush is already set, something like this where drush  becomes the user and I don't have to type it:

drush$ dl ctools, pathauto, ...
drush$ en ctools

This functionality was added in 2010 and removed in 2012. "By the book" way is to use bash with bash completion and optionally bash aliases. Or you can wrap it into a simple php / bash / c program that will automatically prepend drush -l $yoursitename to everything you write and execute the result, and use that as your small simple shell. But you would give up bash completion then.


How to configure date facet filter with year granularity, when click it should show months I am using Facet api with Search api.

I have enabled the facet for the node created date with Granularity set to "Year".

On the search page when I click on Year then it should show the months of that year and when click on month then it should display days of that month?

I didn't see any configurations for this in the facet configurations.

How will I achieve this functionality? Any contributed module?

I have found the solution.

Just select the Granularity to "Days" instead of "Year" in the facet configurations.


How to display image inside a form I want to show image insida a form I've try it with  tag inside form but it's doesnt render anything heres my code

$form['y']['image_div'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
        );

How do I render an image inside form.inc in drupal ?

$form['y']['image_div'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => theme('image', array(
    'path' => 'https://4.bp.blogspot.com/-tGbw82Gz8hA/WPR6WiOGPaI/AAAAAAAAEjk/JDPdpK3p-8wAUe2QTQbtWSdTZR_DBc-QACLcB/s640/Checkout.png',
  )),
);

And in your template file:

print drupal_render($form['y']['image_div']);

Result:


Show menu item to all users, prompt for credentials for anonymous I have an item in the navbar that links to a page view which can only be accessed by authenticated users.

I want the menu item visible for anonymous users, and also to have them redirected to login if they try to access it. This seems like a common use-case. I see a plethora of modules that accomplish this in Drupal 7, but I don't see any for Drupal 8.

How can I show the navbar for anonymous users that prompts users to login with Drupal 8?

As you know, Drupal excludes menu links that the user doesn't have permission to view.

One way around this is to build a menu specifically for anonymous users using the same titles as your other menu, but all pointing to the /user/login?destination=my/view/path path. Once the that menu is built, you can create a menu block from it that only displays for the anonymous user role.

After adjusting the original menu block such that it only displays for the authenticated user role, you will effectively have menu items that display for both roles and prompts a user to login when viewing anonymously. For good measure, you might want to set your Basic site settings such that 403 requests are redirected to /user/login in case the user navigates to the views page directly.


Add javascript to returned form after ajax validation I've built a form with the form API, and it's submitting via ajax via this type of thing:

  $form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#ajax' => array(
      'callback' => 'handyman_form_callback',
      'method' => 'replace',
      'wrapper' => 'form-wrap',
      'effect' => 'fade'
  )
);

The problem is, if the form is returned due to validation errors the javascript applied to the form no longer works. I've read lots about the attachBehaviors function but I'm not sure where I could put this to make it work, and not sure if this is even the correct thing to do.

Any help?

you can attach custom jQuery functions in your modules every time you load content just attaching functions to the Drupal.behaviors like this:

(function($) {

  Drupal.behaviors.your_module = {

    attach: function(context, settings){
      $('#element').bind('click', function(event){
            alert('hello!');
      });
    }

  }

}

In this way, every time Drupal loads content, no matter via ajax or a page refresh, it will automatically attach the desired behaviors. Don't forget to include the js in your pages.


Get node data from entity reference field I have an entity reference field to a content type blog. I referenced a specific blog, but when I render that field in twig using {{ content.field_blog }}. I want to get the autor name and time when that blog was created - not the blog's name by default. Field is in paragraph.
I would like to do this using twig, so without any preprocesses.

How can I do that?

You should be able to get the author like this:

{{ paragraph.field_blog.entity.Owner.name.value }}

and the creation:

{{ paragraph.field_blog.entity.createdtime|format_date('medium') }}


rank position based on field value I would like to display the rank position of a node based on a field value.

Let's say that in field_A there is the node's quantity of "points" and in field_B the node's category.

Then, I would like to display that the current node is 5th out of 15 in its category for example.

thanks for your help.

seems you need to create a "taxonomy view" (category) then create a listing and sort them by the "points" field value.


How do I check the content of variables passed to a template file? I enabled Twig debug and I tried to debug some custom fields. However, if I try this with debug() or kint(), my application always crashes. My PHP memory size is currently 512MB; I assume that should be enough.

I realise that node is a bit too much to debug, so I tried debugging a field as in node.field_video, but that didn't work out as well.

How do I check the content of variables passed to a template file?

You can follow document.

  To dump only the available variable keys use:

{{ dump(_context|keys) }}

In this case you can use:

{{ kint(node|keys) }}

Or you can follow topic

  Create a /modules/contrib/devel/kint/kint/config.php file and add /
  modify the line $_kintSettings['maxLevels'] = 3; (by @mdrummond on
  Slack)

The best way: install module twig_tweak and using twig function

{{drupal_dump(node)}} to dump variables.


"The form has become outdated. Copy any unsaved work..." when saving/deleting content I have a site where saving or deleting content frequently displays an error message "The form has become outdated. Copy any unsaved work and then reload this page"

It does not seem to matter what type of content.
It happens on new content, as well as editing existing content.
It doesn't matter how long the page is open before Save/Delete is clicked.
There is only one person editing at a time.

Can someone suggest a way to track down this bug as it's proving difficult to find.

Take a look at the answer provided by warwickshaw on D.O https://www.drupal.org/node/2241311#comment-8791165

  To fix the error message: 'The form has become outdated. ...' try
  moving the 'drupal_private_key' in to the Drupal 7 settings.php file.

  The Issue See
  https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_ge...
  drupal_get_private_key() is not a safe function.

  When variable_get() doesn't return a $key (some outage, maybe a
  memcached restarted) you suddenly and silently get assigned a new
  drupal_get_private_key.

  If you are using multiple server Drupal system where each server has
  it's own MySql database replicated from a Master DB, a Slave DB can
  end up with it's own key (which Master doesn't see) and when the slave
  gets it's key cached in memcached the fun begins.

  Mean while back in the D7 Admin, forms and menus that once worked
  start failing!

  The Fix The only safe place in D7 whether using a single or
  multi-server setup is to move 'drupal_private_key' value to the
  settings.php file.

  Add $conf['drupal_private_key'] = '...';

  To get the value execute on the Staging server (MySql master) drush ev
  'print drupal_get_private_key();' and assign the value above.

  You should have something like this (these are example values, don't
  use) $drupal_hash_salt =
  'j8lnCx-XF3gq_2NmnnHZ61Q3xlbKHFSzZ9EmUouPwKU';
  $conf['drupal_private_key'] =
  'Fnll-1ZETTb03CgO6PW4COWT7CjTBeRSAQzXqerq6FA';

  Check the hash_salt is behaving correctly (should match
  $drupal_hash_salt) drush ev 'print drupal_get_hash_salt();'

  Copy these setting to all other servers in the same Drupal cluster.

  On Stage update 'drupal_private_key' row with value used in the
  settings.php file. This will replicate and reset any MySql slaves out
  of sync. update variable set value = '[drupal_private_key]' where name
  = 'drupal_private_key';

  On Stage execute drush cc all

  Clear your browser cache.

  You are good to go!

  New D7 Projects When ever you create a new Drupal project make this
  the first task after installation.

  Other Symptoms of the Same Bug Multiple Save, Cancel buttons appears
  after clicking Save or Cancel in Page layouts.


With REQUEST_URI i get id node or alias path? I have a big doubt. In template.php I am using:

$_SERVER['REQUEST_URI']

what will the output like:  node/id-numberor /Alias_page ?

The right way to check on which page are you, is to use the current_path() function. Below is an example:

if (current_path() == 'your/system/path') {
  // Do whatever.
}

This is the best way because aliases can change, while system paths stay the same.

However, if you really need the aliased path, use the drupal_get_path_alias() function instead.


How to use form API to edit sub form that is added to user_register_form I need to alter a Redhen Contact form when it is attached to the user registration form.  More generically, I need to alter a sub form.  The form is added to user_register_form() via hook_form_FORM_ID_alter() in rendhen_contact.module:1029.  (I don't think this is specific to Redhen's implementation; I'm just providing this as a reference point.)

The first issue I encountered was that the hook implementation in redhen_contact.module hadn't occurred when my hook was called.  In a custom module, I used hook_module_implements_alter() to resolve that (see screenshot at bottom for kpr()).  With that I'm still unable to alter, for example, the #title attribute of field_agency_interest.  Even if I do $form['redhen_contact]['form']['field_agency_interest']['und']['#title'] or ...['und'][0]['title'] it doesn't change.

I tried using $form['#after_build'][] = 'module_callback_name' but I can't edit the sub form elements.

How can I alter a sub form added to a form?

You probably forgot to reference the $form variable ("&$form").
The alternative to #after_build would be #pre_render, which misses $form_state but should generally be preferred for changes that only affect the rendering of a form.


Field filter in Views, filter by TID, not name I have a content type, books, with a field Category, based on a taxonomy.
I have a View of books, and can filter by author, date, and also by field category.
Everything works right, but when I try to add several subcategories (nested taxonomy), I have the problem that I cannot let the filter exactly as it is, as I can have two family names exactly equal, namely "offers". For example:

 http://www.example.com/books/science/offers
 http://www.example.com/books/sports/offers

As I am using arg(3) for retrieving "offers", I have the same name for two different taxonomies with different tid's.

How can I alter the SQL in ´MYMODULE_views_pre_view´ so I can filter by tid instead of name? I can programmaticaly get the tid from the URL and inject it directly into the SQL, but don't know how to alter this SQL accordingly.

@no-sssweat' answer is what you want as long as views can figure out the right tid from the url.  In cases where it can't but you know how to, you can do an argument replacement in a custom module.  Here is some code I have that is doing that:

/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    $views_to_process = array(
        'view_name1' => array(
            'display_name1',
            'display_name2',
            'display_name3',
        ),
        'view_name2' => array(
            'display_name1',
        )
    );
    if (!in_array($view->name, array_keys($views_to_process))) { return; }
    if (!in_array($view->current_display, $views_to_process[$view->name])) { return; }
    if (!empty($args[0]) && !_MYMODULE_isInteger($args[0])) {
        $tid = _MYMODULE_get_tid_for_top_level_term($args[0], 'area');
        if ($tid) {
            $args[0] = $tid;
        }
    }

}

/**
 * Helper function to determine whether a value is an integer or not.
 *
 * Sourced from http://php.net/manual/en/function.is-int.php#82857
 */
function _MYMODULE_isInteger($input){
    return(ctype_digit(strval($input)));
}

The `$views_to_process is a tree of views and displays that this should be applied to and the first two ifs just ignore this hook if the display isn't in $views_to_process.  I then check to make sure there is an argument of some kind in place and that it isn't already an integer (helper function included for that), and then it loads a tid based on the current argument.  It then replaces that argument with the tid.  If you replaced _MYMODULE_get_tid_for_top_level_term with your helper function for loading up the tid, you can then use the tid as a contextual filter value.  I hope that helps!

note: I currently have a question open on that very view, and while I don't think this solution has anything to do with the issue I'm having, there is a chance.


Problem updating from Drupal Core 8.3.7 to 8.4.0 with composer I am having trouble updating from Drupal 8.3.7.

When running composer why-not drupal/core 8.4.0 I get the following results:

drupal/core 8.4.0 requires symfony/class-loader (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/class-loader (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/console (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/console (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/dependency-injection (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/dependency-injection (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/event-dispatcher (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/event-dispatcher (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/http-foundation (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/http-foundation (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/http-kernel (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/http-kernel (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/process (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/process (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/routing (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/routing (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/serializer (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/serializer (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/translation (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/translation (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/validator (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/validator (but v2.8.28 is installed)
drupal/core 8.4.0 requires symfony/yaml (~3.2.8)
andeersg/bouvet-d8-project dev-Stinis does not require symfony/yaml (but v2.8.28 is installed)

Trying to update one of the mentioned packages just results in composer telling me I can't because Drupal 8.3.7 needs a lower version. So I can't update the packages and I can't update Drupal. Am I stuck in a catch22?

Does anybody know what the problem might be? When I run composer update drupal/core --with-dependencies it says that everything is up to date even though it is still at 8.3.7.

I had the same issue and here is what worked for me

Requirement : PHP 7.1
Explanation :1. Doctrire, a dependancy of Drupal core, requires PHP 7.1. Doctrine uses the latest PHP 7.1 syntax to declare the methods' return type eg. function my_function() : void {...}. There is a core bug concerning this issue with status "Needs work". Even if this bug is patched, 8.4 requires PHP 7.
2. webflo breaks the chain of dependencies
3. Drupal 8.4 requires Drush 9.0

If you have PHP 7.1 on your server you can do the following:

edit the composer.json file: "drupal/core": "~8.4" and "drush/drush": "~9.0"
delete composer.lock
delete vendor
update webflo: composer require "webflo/drupal-finder ~1.0.0"
update the database: ../vendor/bin/drush updb -y
update the entities schemas: ../vendor/bin/drush entup -y

Applied on three different production servers (Linux + Apache) and on local environments (macOS + Apach, Ubuntu + Apache). Not tested with Vagrant.

The two entity updates are concerning "paragraph entity type" : (1) The Published field needs to be updated. (2) The Behavior settings field needs to be updated.


Views expose filter of start and end dates I want an expose filter of start date and end date. I want to show the events that have start or end date between these two dates. If end date is not given in filter then display all the events having start date greater than filter's start date.

Add the filter like that :

Start Date >= Filter's Stat Date

End Date <= Filter's End Date


How to prevent CKEditor from replacing spaces with  ? I'm using CKEditor 4.2 with D7 and the editor is replacing every space with an HTML non-breaking space. For instance, if I type: This is a paragraph and then either save or view source, I'll get the following:

This&nbsp;is&nbsp;a&nbsp;paragraph.

I don't have any HTML correctors/prettifiers running as filters and I'm banging my head against the wall trying to figure out what's causing this.

Oh, I also have Convert all applicable characters to HTML entities. unchecked, so that's not it.

Has anyone seen this before? Any solutions out there?

I solve this with a text filter

/**
 * Implements hook_filter_info().
 */
function MYMODULE_filter_info() {
  $filters = array();

  $filters['kill_nbsp'] = array(
    'title' => t('Kill Non-Breaking Spaces'),
    'description' => t('Remove non-breaking spaces.'),
    'process callback' => '_MYMODULE_filters_kill_nbsp',
    'tips callback' => '_MYMODULE_filters_kill_nbsp_tips',
  );

  return $filters;
}

/**
 * Filter callbacks.
 */
function _MYMODULE_filters_kill_nbsp($text, $filter) {
  return preg_replace('/&nbsp;/', ' ', $text);
}

/**
 * Filter tips.
 */
function _MYMODULE_filters_kill_nbsp_tips($filter, $format, $long = FALSE) {
  if (!$long) {
    // This string will be shown in the content add/edit form.
    return t('Don\'t use non-breaking spaces.  Ever.');
  }
  else {
    // And this one on the "Filter Tips" page.
    return t('Non-breaking spaces are evil and will be eradicated.');
  }
}

The code simply searches for non-breaking spaces and replaces them with normal spaces.

Stuff this in a custom module, and then assign the filter to the input formats that have WYSIWYG enabled.  This does assume that you never want actual non-breaking spaces in your output, which is good for my sites.


field_view_field geofield_map I'm doing the following

field_view_field('node', $node, 'field_geo',
    array(
      'label' => 'hidden',
      'settings' =>
        array(
            'format_type' => 'geofield_map_map'
        ),
    );

field_geo is a geofield.
geofield_map module is enabled (output is fine for this field in other instances where I am not calling field_view_field()

In looking through geofield_map.module, there is every indication in hook_field_formatter_info() that I should be using "geofield_map_map", but I don't get the map output. Anyone have any idea why?

Found the problem ... I was defining the output type in the settings array vs directly in the display array.

field_view_field('node', $node, 'field_geo',
    array(
      'label' => 'hidden',
      'type' => 'geofield_map_map'
    )
);

Hope this helps someone else.


How do I pass variables to JavaScript? In your MODULENAME.module file:
$testVariable = 'himanshu';
drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('module', 'MODULENAME') . '/MODULENAME.js');

In MODULENAME.js file:
(function($) {
  Drupal.behaviors.MODULENAME = {
    attach: function (context, settings) {
      alert(settings.MODULENAME.testvar);
    }
  };
})(jQuery);

this way you can pass your php variable in drupal javascript file and use the variable :)
How can I implement the above in Drupal 8?

Instead of drupal_add_js(array('MODULENAME' => array('testvar' => $testVariable)), array('type' => 'setting')); you use $build['#attached']['drupalSettings']['testvar'] = $testVariable;. Replace $build with the variable containing the form or the render array to which the settings are attached; in a form builder or hook_form_alter(), that would be $form.

The JavaScript code to attach to the page should then be defined as library, which is the only way to attach JavaScript and CSS to a page or a form.
It is explained in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module, so I will not repeat it here. I will just make notice that the library needs to declare at least two dependencies:

core/jquery, if the JavaScript code uses jQuery
core/drupalSettings, since the JavaScript code uses Drupal settings


How to use Rules to change the value of entity reference’s field? I have two content types (Inventory and Sales). In Sales, I referenced Inventory using the Entity reference module.

In Inventory, I have a stock_available (integer) field. In Sales, I also have the same field, so that I can automatically populate its value from Inventory using the Entity reference autofill module.

When I add a new Sales node, I want to adjust the value of stock_available  in the referenced Inventory, so that gradually it becomes zero in the referenced Inventory node.

I know how to set value/calculated value from other filed within same content type, by using the Rules module.

I have no idea how I can do same things to targeted entity reference node. I think it's possible by just rule configuration. Please let me know if something needs to change to get same output that I expected.

Step 1: Create a Rules Component

Create a Rules Component (of type "action set") like so:

Parameters are "node" and "stock decrease".
Rules Action = "set value/calculated value from other filed within same content type" (*).

Here is a prototype of such Rules Component:

{ "rules_decrease_stock" : {
    "LABEL" : "Decrease Stock",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "stock_decrease" : { "label" : "Stock decrease", "type" : "integer" }
    },
    "ACTION SET" : [
      { "drupal_message" : { "message" : "Something just got sold, so please decrease the stock for node with id [node-to-update:nid] with an amount of \r\n[stock-decrease:value] units. To actually do so, replace this (informational) Rules Action with setting the appropriate value for the appropriate field ..." } }
    ]
  }
}

The actual action only displays a Drupal message (to show the values of the variables passed to it). Replace that action with the actual update of your inventory node (*).

Step 2: Create a Rule

Create a rule with Rules Event something like "after updating a node of content type "Sales". Maybe also some Rules Condition like "stock_available" is updated (checked if the unsaved value differs from the saved value). And add these Rules Actions:

Update the stock_available in your Sales content type (*).
Perform the Rules Component (from step 1), whereas you pass these 2 parameters:

the node, which you can pass via the value (token) of the entity reference.
the stock decrease amount (which is identical).

(*): you indicated in your question you know how to do that ...


Two menus can't hide the other I have been reconfiguring my drupal site for faster loading so i restarted from strach, the problem is i can not get rid of the Menu tab which is above the Home tab, if you look at http://beta2.computersuppportservicescs.co.uk you will see what i mean, i have went into the theme setting and untick main menu and seocndary menu and flushed the cache but it is still there.

On http://beta.computersupportservicescs.co.uk you can see i did get rid of it but i think i edit one of the php files directly and commented out the section but i cant remember which one.

Finally worked it out again
Look for navigations.css
Edit it and look for menu-toggle
change it from display: none; to visibility: hidden; !important;
now it gone
I will update question with screenshots so others can see the problem better and know what this solution does


How to integrate some fields into a node more efficient? in my node.tpl.php i want to display a custom field (field_cta) which is part of my page.
It is working this way, but it looks so terrible...is there a drupal command to shorten all the array-walk-trough precedure?

if (isset($content['body']['#object']->field_cta['und'][0]['value'])){ print $content['body']['#object']->field_cta['und'][0]['value'];}

Thanks a lot!

if it's Drupal 7, I think this can works.

if(isset($content['fieldname'])):

echo render($content['fieldname']);

endif;


Importing and using overlay from jquery_plugin module I am trying (and failing) to use the jquery overlay plugin from the jquery_plugin module in Drupal 7.

I am using drupal_add_library() to add the plugin and drupal_add_js to add the code to generate the overlays.

The overlay trigger elements are area elements within a map.

Whenever I try and trigger the overlays, I get nothing - no errors or stacktraces or alerts, or messages in Firebug.

Here is the code - added directly into the page content.

drupal_add_library('jquery_plugin', 'overlay');
drupal_add_js('function($) {
    $(document).ready( function() {
        $(".overlayarea").overlay();
    });
}(jQuery); ','inline');

The map looks as the following:

<map name="globalmap">
    <area id="toronto" class="overlayarea" alt="Toronto" coords="94,195,6" shape="circle" rel="#tor_overlay" nohref />
    <area id="oxford" class="overlayarea" alt="Oxford" coords="576,147,6" shape="circle" rel="#oxf_overlay" nohref />
</map>

Actually this module seems to be abandoned. Using drupal_add_library() works only if the module used hook_library(). I wanted to check it in the repository of jquery_plugin, but these files aren't available. I don't know why.

If you want to use overlays, you can use directly the jQuery UI that is already included in Drupal 7.


How can you display document file sizes next to a media link button? I'm trying to display the file size of a file next to a media link button on a page.

I have two content types with a media entity reference field in each. Each field is restricted to only pull from a file media type. What I was trying to do was create a twig variable using a field preprocess and pop that variable inside each of my field templates. However, my preprocess below doesn't seem to be displaying the file size as I want. What am I doing wrong?

function theme_preprocess_field(&$variables, $hook) {

  $pdf_fields = [
    'field_1',
    'field_2'
  ];

  if (in_array($element['#field_name'], $pdf_fields) && $element['#entity_type'] == 'node') {

    if ($variables['items'][0]) {

      $field_name = $element['#field_name'];

      $node = $element['#object'];
      // Get first referenced media id.
      $media_id = $node->$field_name->target_id;
      // Get file object.
      $file = \Drupal\file\Entity\File::load($media_id);
      if ($file) {
        // Get file size.
        $file_size = format_size($file->getSize());
        // Set file size variable.
        $variables['file_size'] = $file_size;
      }
    }
  }
}

Twig field template

{% for item in items %}
  Download Paper(PDF | {{ file_size }})
{% endfor %}

function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileSize' => $variables['file']
        ->getSize(),
      'fileSizeFormatted' => format_size($variables['file']
        ->getSize()),
    ];
  }
}

{{ fileLinkDisplay.fileSize }}and {{ fileLinkDisplay.fileSizeFormatted }} will be available in your template.

PS: if it works then you can more filter to restrict to the content type and field you want applied for.

Additionally, there is a module that show the size https://www.drupal.org/project/field_formatter_file_size

  Field Formatter File Size is a field formatter to display the file
  size.


How do I add menu items within a .install file I'm trying to build an intall profile that implements a number if features. I am running into some issues because although features allows me to require menus, it seems there is no way to also include the links (most of the link are simple aliases to add content or edit views). Is there a way to add menu items from within the install profile?

You can follow the example from the profiles/standard/standard.install file and use code like this inside your implementation of hook_install():

// Create a Home link in the main menu.
$item = array(
  'link_title' => st('Home'),
  'link_path' => '<front>',
  'menu_name' => 'main-menu',
);
menu_link_save($item);


Solr search views cache issue I have views for solr search result and I have highlight processor enabled. There seems to be cache issue effecting search result. Search results are rendered array of entities. For example: If I search 'content'. I see my result highlighting word 'content' correctly but when I search for result 'extraction', in the page with both words 'content' and 'extraction', it highlights 'content'. I used

\Drupal::service('page_cache_kill_switch')->trigger();

in views pre_render but didn't work as expected. Views advanced setting already has caching set to none.

Can anyone help me disabling cache for this particular view?

Thank you.

When you go to /admin/config/search/search-api and then click to edit your index, there is a checkbox for "Index items immediately" under the "Index Options" section. That is the only way I've found to get Solr Views to output new content immediately after it's created.


Restrict a menu item only for a particular accessible after loggin and optionally for a role This is the menu I have.

  $items['start'] = array(
    'title' => 'Take A Test',
    'page callback' => 'qe_start',
    'access callback' => TRUE,
    'expanded' => TRUE,
  );

return $items;

What should be passed in this to make it accessible to a role/logged in user?

'access arguments'    => array('content'),

And how can I make this to a callback_menu?

If you actually just want to check if the user is logged in and don't want to set up permissions, you can set the access callback to 'user_is_logged_in':

$items['start'] = array(
  'title' => 'Take A Test',
  'page callback' => 'qe_start',
  'access callback' => 'user_is_logged_in',
  'expanded' => TRUE,
);


How can I refresh the adjustment tax after changing the line-item price? I create orders programmatically, and I have a tax problem: the order, after changing the line item price, always has the tax cost with the old product price.
How can I refresh the adjustment tax after changing the line-item price?

foreach ($entity_ids as $entity_id) {
    $abo = Node::load($entity_id);

    //utilisateur
    $user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
    $utilisateur = \Drupal\user\Entity\User::load($user);

    //profile
    $entity_manager = \Drupal::entityTypeManager();
    $profile = $entity_manager->getStorage('profile')->load($user);

    //abonnement
    $nid= $abo->id();

    //livraison
    $date_livraison = new DateTime();
    $date_livraison->modify('next friday');

    //ligne de commande
    $line_items = array();
    $abo_array= $abo->get('field_abo_produits')->getValue();

    foreach ($abo_array as $abo_item) {
        $ligne = $abo_item['target_id'];
        //load produit abonnement
        $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
        $quantite = $item->getQuantity();
        $produit = $item->getPurchasedEntity();

        $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
            'type' => 'default',
            'purchased_entity' => $produit,
            'quantity' => $quantite,
            //'unit_price' => $role_price,
        ]);

        $order_item->save();
        array_push($line_items,$order_item);
    }

    //creation de la commande
    $order = \Drupal\commerce_order\Entity\Order::create([
        'type' => 'default',
        'store_id' => 1,
        'checkout_flow' => 'boulangerie',
        'uid' => $user,
        'billing_profile' =>$profile,
        'field_abonnement' => $nid,
        'placed' => time(),
        'field_date_livraison' =>$date_livraison->format('Y-m-d'),
        'order_items' =>$line_items
    ]);

    $order->save();
    $order->set('order_number', $order->id());
    $order->save();
    $order->set('state', 'complete');
    $order->save();

    //prix custo
    foreach ($order->getItems() as $ligne_de_commande) {

        $produit = $ligne_de_commande->getPurchasedEntity();
        //prix
        if ($utilisateur->hasRole('biocoop')) {
            $role_price = $produit->get('field_prix_biocoop');
            $role = 'biocoop';
        }

        if ($utilisateur->hasRole('montagne')) {
            $role_price = $produit->get('field_prix_montagne');
            $role = 'montagne';
        }

        if ($utilisateur->hasRole('vente_directe')) {
            $role_price = $produit->get('field_prix_vd');
            $role = 'vente_directe';
        }

        $unit_price = new  \Drupal\commerce_price\Price($role_price->number, 'EUR');

        $ligne_de_commande->setUnitPrice($unit_price);
        $ligne_de_commande->save();

    }

    $order->save();
}

Order refresh is done via a service, this service is called every time an order is saved. Check the module documentation.


Mysterious "Page not found" on every page load for authenticated users I recently migrated my site to a new server, and restructured the urls, etc... so naturally there are quite a few 404's out there from other sites linking to old content. So far, so normal.

But among the page not founds, I'm getting something really bizarre: as far as I can tell, every single page load of the site by authenticated users is generating one particular "page not found" error for a file at location sites/default/files/stripes54-navywhite.jpg.

Every page load for every authenticated user.

Now this file does not exist. Nor are there any links on the site to it (the file name is familiar: we may have had a file at that location at some point in the past, on the old site).

I have searched page source, I have searched through the contents of all my site files, I have searched my complete db using phpmyadmin. There is no reference to this file anywhere, as far as I can tell.

So what could possibly be causing this? Where is this file mysteriously being referenced? Watchdog is giving me no help here.

My only clue at the moment is that this page not found seems to ONLY be triggered by authenticated users: not seeing any anonymous users triggering it.

Does anyone have any earthly idea what might be going on here? A big thanks to anyone who can help!

I'm even getting this error generated by admin pages, which use a separate admin theme. For example, when browsing my database log.

There is one entry in the file_managed table where origname is stripes54-navywhite.jpg. Unfortunately, this doesn't really shed much light on the problem.

After further investigation, this appears to be an issue with CloudFlare. Disabled it, and the problem went away... re-enabled it, and the problem returned, but with a different image url!

Yet further investigation shows Cloudflare's Website preloader to be the culprit. So nothing to do with Drupal.


How can I have the URL path (node slug) be different from the Title? It seems like this should be super simple, but I can't seem to figure it out...

I have layouts with headings and subheadings, (shown below) where the highlighted/top heading is the page/node's title.

So the issue I'm having, is that the system then makes the slug "stay-connected-with-campus" but I want it to be "parents" and "parents" is just redirecting to "stay-connected-with-campus"

Where or how can I control that?

My URL path Settings:

And there are no redirects set:

Thanks!

If you want control over the generated URL, then you need to enable the Path or Pathauto modules. Once these are enabled, Edit the piece of content for which you want to set a specific URL path, and go to "URL Path Settings" to do this.


Disable welcome message for specific roles but keep for others, user_mail_notify In Drupal 7...

I am trying to find a solution to disable the sending of the user mail register by admin for certain roles. I have scoured the internet and have come up with using a combo of mailcontrol and Rules or custom code in my module.

I'm using Rules to send the message. I didn't want to completely disable the welcome email message for the other roles.

How can I create this functionality of sending the system mail to some users but not others? (either programmatically or via Rules)

I have a custom module already, so I used the following hook but nothing happened. I still get the welcome message.

function myMod_fields_user_mail_notify($op, $account, $language = NULL) {

 $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);

if (in_array('Administrator', $user->roles)) {
  if ($op == 'register_admin_created') {
   //don't send system email we'll do this with another rule.
    variable_set('user_mail_register_admin_created_notify', false);
  }
  else if ($notify) {
  $params['account'] = $account;
  $language = $language ? $language : user_preferred_language($account);
  $mail = drupal_mail('user', $op, $account->mail, $language, $params);
}
return empty($mail) ? NULL : $mail['result'];
 }
}

I kind of stumbled on this after nobody answered my question. (I was desperate)

The solutions is to:

Edit your welcome email, under Account Settings.
Enable Mail Control and disable the welcome email. This content is saved  in the database, so don't worry about losing anything.
Create a new Rule to react on a new event: After saving a new user account
Add in your condition: User has Role && User is being Notified.
Under Actions: Send Account E-mail.
Under E-mail Type: Choose Welcome E-mail.
Save! Clear Cache! Get More Coffee!


Custom login page with redirect I've set up a custom login page witht the difference that that one should redirect the user to another page.

I use the default drupal login form so I dont really now how to fix the form alter for my custom form without it to change the default login form too.

What could I do to fix this?

My code:

function mymodule_cv_login() {
    // Print the user login form
    $form = drupal_get_form('user_login');

    $form['redirect'] = 'cv';

    return $form;
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $path = 'profil';
        $form['#action'] = url($_GET['q'], array('query' => array('destination' => $path)));
    }
}

You can check what page you are on by looking at $_GET['q'] (or using the arg() function) so you could base your alter on that.