Can I use plupload to load multiple image files into a single image field I have an image file field on my Drupal 7 site that allows users to add 4 images.  I would like to give my users the ability to load all 4 images at once.  I have discovered the plupload module and plup library which should be able to let me do this.  However, I have yet to discover an configuration (including the media module) which allows me to do this.  How can I make this functionality work?

Add this js in your custom js file.

(function ($) {
  Drupal.behaviors.autoUpload = {
    attach: function (context, settings) {
      $('form', context).delegate('input.form-file', 'change', function() {
        $(this).next('input[type="submit"]').mousedown();
      });
    }
  };
})(jQuery);

It will automatically upload all the images on click of upload button using above Jquery.

for more information,look at this link. at http://drupal.org/sandbox/clivelinsell/1587560 .


How to stop the book module defaulting to IE7 standards mode? I currently have a problem whereby when visiting a page created with the book module it forces IE into IE7 standards document mode.

I am running Drupal 7 with the Omega 3 base theme.  I have disabled the RDF module and added:

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

Which forces all other areas of the site to render correctly, just not in the book module pages.

Has anyone else come across this problem?

I suspect you may have visited the book page in IE, and selected compatibility mode once, and it is now being remembered.  Another possibility is that you have an internet zone rule (probably an intranet rule) that is forcing compatibility mode on.  Your IT department may be forcing this via a policy, too.

I have had some problems with just using the meta in the header of a page, and have been using this:

/**
 * Implements hook_html_head_alter().
 */
function MYTHEME_head_alter(&$head_elements) {
  // disable IE compatability mode
  // see http://msdn.microsoft.com/en-us/library/cc288325(v=vs.85).aspx

  $head_elements['x_ua_compatible'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'X-UA-Compatible',
      'content' => 'IE=Edge,chrome=1',
    ),
  );

  $head_elements['x_ua_compatible']['#attached']['drupal_add_http_header'][] =
    array('X-UA-Compatible', $head_elements['x_ua_compatible']['#attributes']['content']);
}

This adds the meta, so you can see it when you do a view source, and it also adds a proper HTTP header to disable it.

Just note that if this is being enforced via policy or IE settings, you may not be able to override it.


How can I submit a form into a node and save it in the database? I installed drupal 8 in local and i have created a content type named 'Formulaire' and also i've created a FormulaireForm and i want to submit this form into that node .how can i do this ?
and i also want to storage this values into the database.

Your FormulaireForm is made by webform? Under this case, you can use rules to create node automatically.


In which tables and columns data is stored for Story and Page? I am using Drupal 6.25 with Postgres 8.4. I want to create stories from backend. To which tables and columns should I insert values so that one story is shown on my drupal site?

This is Drupal way to insert a new node from code.

<?php
// add node properties
$newNode = (object) NULL;
$newNode->type = '{NODE_TYPE}';
$newNode->title = '{NODE_TITLE}'
$newNode->uid = {USER_ID};
$newNode->created = strtotime("now");
$newNode->changed = strtotime("now");
$newNode->status = 1;
$newNode->comment = 0;
$newNode->promote = 0;
$newNode->moderate = 0;
$newNode->sticky = 0;

// add CCK field data
$newNode->field_{YOUR_CUSTOM_FIELD_1}[0]['value'] = '{DATA_1}';
$newNode->field_{YOUR_CUSTOM_FIELD_2}[0]['value'] = '{DATA_2}';

// save node
node_save($newNode);
?>

Best of luck with Drupal.

You will need to refer Creating Drupal 7.x modules


Email not to admin, When user create an account I want to send an email to another email, rather than admin Email, When user create an account

Can Anybody tell me how to do that . I am using drupal 7

Thanks

Download, install & Enable Rules module.
Goto

Admin -> Configuration -> Rules

-> Click on Component tab -> Add Component

-> Select Action set -> In Component Plugin ->

Name: Send email to inactive user

Datatype: User,

Label:active_user,

Machine_name: active_user

Usage: Parameter

-> Add action -> data selector: active_user

-> Enter the subject & body & save

-> Go back & Add new rule

-> React on Event : After Saving a new new user a/c

-> Add Action  -> Select Schedule Component Evaluation

-> Value : Choose your component

-> Identifier : [account:uid]

-> Data selector : account

If you have any doubt then you may CLICK


How to add outer div to Profile2 profile including link set in #prefix I would like to add a wrapper div around Profile2 profiles when displayed on the user account page. I can wrap the title and profile fields by modifying user-profile-category.tpl.php in my theme. However, there's an anchor link to each profile added in profile2.module using hook_user_view: '#prefix' => 'type . '">',.

I can't find a template that will allow me to wrap that link along with its accompanying profile. How can I theme those items together?

The Profile2 modules implements a profile2_form_alter hook that you can implement in a module. Say you have a module called kelley_profile2, then the function you want to implement is

/**
 * Implements hook_form_profile2_form_alter().
 */
function kelley_profile2_form_profile2_form_alter(&$form, &$form_state) {
  // Check profiles key exists in $form_state.
  if (array_key_exists('profiles', $form_state)) {
    // Iterate through each profile type and add prefix.
    foreach ($form_state['profiles'] as $type => $profile) {
      $form['profile_' . $type]['#prefix'] = '';
    }
  }
}


Rule to check if a node has a translation? Just wondering if I can create a this rule:

1) check if a node (when viewed) has the translations for all enabled languages.

2) If the it doesn't, then create the translation (for all enabled languages)

Out of the box: no.

If you are willing to code, check the rules API. It lets you add your own conditions and actions.

If you don't need any of the rules functionality you can of course just implement hook_node_view.


verify operations through email I need to ensure that the user is the one who is acting on the website by sending hash code generated to his emial or sms message before complete an operation.

we have implemented account balance so we need to prevent others use his balance by verify the account owner.

Scenario wanted to achieve:

User add items to his cart
Send hash code to his email
verify the code
Complete to checkout

What is the best practice to achieve?

using commerce framework -- commerce account balance

You should force user registration before checkout and allow Drupal to handle this. There are a couple of things you can do to make it very tough for non-humans to get through:

Require user verification for registration. This is out of the box functionality with Drupal and is accessible in the system configuration area.
Consider using a module such as Captcha or Honeypot to expose traps for bots so that they cannot continue.

Don't work against Drupal's user and form system on this one. Let them do the work for you.


Date and links formatting in node template Drupal 8.x

I have 2 quick questions. I have the following node template node--briefing--teaser.html.twig

  {{ date }}
  {{ label }}

Now the questions are:

How can I format the date to the following d/m/Y
How can I get the URI of the read more field (links)

With a normal link field you can simply do content.my_link.0['#url'] to get this but that doesn't seem to be the case with the node links field.

Thanks in advance!

Answer for the date formating: {{ date.value|date('U')|format_date('custom', 'j/m/Y') }}

For the URI investigate the data structure with twig vardumper.


Send mail with attachment using the MIME Mail module I am not able to send mails with an attachement using the MIME Mail module.
There isn't munch documentation about this module, but some people claim they have successfully used the module, and sent a mail with an attachment.

I've enabled and successfully configured:

Mail System
Mime Mail
Swift Mailer

I think I configured the modules correctly.

No mail with attachement is delivered. I call drupal_mail() in a cron job with the following code.

drupal_mail('mymodule', 'notice', $user_email, $lang, $params, $admin_email);

It should invoke any hook_mail() implementations, which it does, but without the attachment.

function mymodule_mail($key, &$message, $params) {
  $data['user'] = $params['from'];
  $account = $data['user']->name;

  $file_content = file_get_contents('some/file/path');

  $attachments = array(
     'filecontent' => $file_content,
     'filename' => 'example-' . $account,
     'filemime' => 'application/pdf',
   );

  switch($key) {
    case 'notice':

      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from '. $account;
      $message['body'][] =
        '<p>'. $account .' has submitted an example.</p>';
      $message['params']['attachments'][] = $attachments;
      break;
  }
}

The solution I've found is to use hook_mail_alter to attach the file to the email after it's generated and before it's sent. The key to that is making an array of details about your attachment and adding that to $message['params']['attachments'].

hook_mail will send mail, but if you're using another program to send (Swift Mailer or PET), then I believe you'll need hook_mail_alter to alter the mail instead of sending it yourself.

I also suggest using the Form API (also this) to keep track of your file. That's not required, however, just provide the necessary info.

function myhook_mail_alter(&$message) {

  print "message id: {$message['id']}\n";

  // if this email is one of the ones I want to alter:
  if (!empty($message['id']) && (preg_match('/^message-id-set-by-formmail[\d]{1,2}/', $message['id']))) {

    // $message['params']['body'] is a single string, not an array
    $result = preg_match('/\[my dumb string with node id# (\d+)]/', $message['params']['body'], $matches);

    print "Message body: \n {$message['params']['body']} \n\n Matches:\n";
    print_r($matches);

    if (!empty($matches[1])) {
      $file_id = $matches[1];
      $my_pdf = file_load($file_id);
      $original_attachments = $message['params']['attachments'];
      // $original_attachments is an array of associative arrays, each bearing details about an attachment.
      // Add an associative array about this desired attachment.
      $my_attachment = array(
        'filecontent' => file_get_contents($my_pdf->uri),
        'filemime' => $my_pdf->filemime,
        'filename' => $my_pdf->filename,
        'filepath' => NULL,
      );
      $message['params']['attachments'][] = $my_attachment;
    }

  }
}


How to add Flag to a rendered View I've set up the default Flag (bookmark) and have added the proper links to my node.tpl.php pages so that the flags show up properly.  Is there any way to add the same link to a rendered view (page?) I tried using views-view.tpl.php and adding the following code:

<?php print flag_create_link('bookmarks', $node->nid); ?>

But that doesn't work because the rendered view is not a node, of course.  What I'm trying to do is allow users to bookmark a rendered page view just like they can do with any other node.

Just a single flag for the rendered page view that displays all
  articles (i.e., a way to bookmark the "read all news" page.)

ok then doing it the way you were doing it, is the way to go.

$node->nid alone won't return the nid, you need to to use menu_get_object() function

<?php

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;

print flag_create_link('bookmarks', $nid);

}

?>

Note 1: If you're using a page view, the above won't work since it cannot fetch an nid since page view's don't have node id's. In order to get it to work, you can create a block view, and then create a node where you insert your block view. Then since the node has a nid, it's able to fetch the node id.

Note 2: You can ignore all the comments below, as they were due to using a page view (see note1)


How to group drush command sets together in sequence? For example, when installing a drupal site, there are 3 sets of commands:

drush dl drupal-7.x

drush site-install standard --account-name=admin --account-pass=admin --db- url=mysql://YourMySQLUser:RandomPassword@localhost/YourMySQLDatabase

drush make example.make

Is there a way to group these 3 tasks and have drush do them one by one without having the user do it 3 times?

There are quite a few, I tend to use a shell script, but you can create your own drush command:
http://www.sitepoint.com/drupal-create-drush-command/

Here is an example of how I would do this with a shell script (mac / linux).

#!/bin/sh

# Default parameters to use.
version="7"
profile="standard"
user="admin"
pass="admin"
mysql_user="YourMySQLUser"
mysql_pass="RandomPassword"
mysql_host="localhost"
mysql_db="YourMySQLDatabase"
makefile="example.make"

# Collect parameters from the command line to override defaults.
for args in "$@"
do
  # Get the drupal install version.
  if [[ ${args:0:10} == '--version=' ]]
  then
    version=${args:10}
  fi

  # Get the installation profile
  if [[ ${args:0:10} == '--profile=' ]]
  then
    profile=${args:10}
  fi

  # User name to give the drupal admin user account.
  if [[ ${args:0:7} == '--user=' ]]
  then
    user=${args:7}
  fi

  # Password to give the drupal admin user account.
  if [[ ${args:0:7} == '--pass=' ]]
  then
    pass=${args:7}
  fi

  # Mysql username
  if [[ ${args:0:13} == '--mysql-user=' ]]
  then
    mysql_user=${args:13}
  fi

  # Mysql password
  if [[ ${args:0:13} == '--mysql-pass=' ]]
  then
    mysql_pass=${args:13}
  fi

  # Mysql host
  if [[ ${args:0:13} == '--mysql-host=' ]]
  then
    mysql_host=${args:13}
  fi

  # Mysql db
  if [[ ${args:0:11} == '--mysql-db=' ]]
  then
    mysql_db=${args:11}
  fi

  # Drush make file to use.§
  if [[ ${args:0:11} == '--makefile=' ]]
  then
    makefile=${args:11}
  fi

done

`drush dl drupal-$version.x`
`drush site-install $profile --account-name=$user --account-pass=$pass --db-url=mysql://$mysql_user:$mysql_pass@$mysql_host/$mysql_db`
`drush make $makefile`

Example usage:

~/path/to/script --profile=minimal --user=adminuser --makefile=meh.make


No release history available stops dependent modules download I am creating my first make file to retrieve a custom module 'CUSTOM_MODULE' from github and running into trouble getting the dependent modules to be installed.

Here is make file at the Drupal site to install the module:

api = 2
core = 7.x
projects[CUSTOM_MODULE][type] = "module"
projects[CUSTOM_MODULE][subdir] = contrib
projects[CUSTOM_MODULE][version] = 7.x-1.0
projects[CUSTOM_MODULE][download][type] = "git"
projects[CUSTOM_MODULE][download][url] = "http://github.com/to-git-repo.git"
projects[CUSTOM_MODULE][download][branch] = "master"

To Get the custom module

 drush make someMakeFile.build --no-core --contrib-destination=sites/all

This install the CUSTOM_MODULE in sites/all/modules/contrib, however. It doesn't install all the dependencies as specified in the CUSTOM module local make file:

api = 2
core = 7.x
projects[] = audiofield
projects[] = block
projects[] = blog
projects[] = comment
projects[] = context
projects[] = jw_player
projects[] = libraries
projects[] = strongarm
projects[] = taxonomy
projects[] = text
projects[] = uuid_features
projects[] = video
projects[] = video_presets
projects[] = views
projects[] = node

When run in debug mode(--debug)

    ...
Found makefile: designssquare_com_blog.make [40 sec, 6.69 MB]                                                                                [ok]
Downloading release history from http://updates.drupal.org/release-history/audiofield/7.x [40.01 sec, 6.73 MB]                                                                  [notice]
/Users/maxit/.drush/cache/download/http---updates.drupal.org-release-history-audiofield-7.x retrieved from cache. [40.01 sec, 6.74 MB]                                          [notice]
Downloading release history from http://updates.drupal.org/release-history/block/7.x [40.06 sec, 6.74 MB]                                                                       [notice]
/Users/maxit/.drush/cache/download/http---updates.drupal.org-release-history-block-7.x retrieved from cache. [40.06 sec, 6.75 MB]                                               [notice]
No release history available for block 7.x
Returned from hook drush_make_process [40.06 sec, 6.7 MB]                                                                                [debug]
Command dispatch complete
    ...

From the first line, it is processing the local CUSTOM_MODULE make file, however. It stops on second dependent module - 'block' and doesn't continue with the rest of the modules? While i would remove 'block' module as dependent (since it is part of core), my desired behavior would be it continue with the rest of the dependent module downloads, so the deployment completes with rest of the modules downloading.  How I would specify such a behavior? Thank You

p.s. Drupal 7.x, Drush Master, Mac

As per @jonhattan comment:

You need to specify projects to download in your makefile as block is not a project, but a module part of Drupal core. Same for comment or node. Simply remove them from the makefile.


How do I render my date field using my custom date format? I have a content type with two "date and time" fields, configured to display in "22 November 2012 5:19pm" format:

On the item itself, the start and end dates are both set to include times:

In my node.tpl.php, I output the two fields:
print drupal_render(field_view_field('node', $node, 'field_date'));
print drupal_render(field_view_field('node', $node, 'field_end_datetime'));

However, the two fields are displayed without the time:

Start Date and Time: 02 December 2012
End Date and Time: 02 December 2012

How do I output these two fields using my custom date format?

In the node template you should be able to output your dates with your selected format by doing:

print render($content['field_date']);
print render($content['field_end_datetime']);


Umlauts grouped in summary (U and Ü, A and Ä etc) I faced the problem with summary attachment which includes umlauts like: U and Ü, A and Ä; O and Ö etc. For example if two nodes starting with letters U and Ü

Umlauts
Ümlauts

only U letter will be displayed in summary. In case when some of nodes starting only with Ü, this letter Ü in correctly displayed in summary, problem appears when nodes have both U and Ü as capital letters.

Later I figured out that it's caused by GROUP BY query part

SELECT SUBSTRING(node.title, 1, 1) AS title_truncated, COUNT(node.nid) AS num_records
FROM node node
GROUP BY title_truncated
ORDER BY title_truncated ASC

Nodes with first U and Ü letters are treated were treated as U. How can I manage this problem?

If I had to take a guess at this it would be that your database is using utf8 and the default collation of utf8_general_ci. If I understand correctly, this collation does not handle diacritics very well, and would consider U and Ü the same. You may have better luck with utf8_unicode_ci. That said, most of my Unicode experience is with Elasticsearch, so I know less about MySQL collation (assuming that is your database). You may have more luck running this by a database-specific stackexchange.

Here is a reference on the two collation types: https://stackoverflow.com/questions/1036454/what-are-the-diffrences-between-utf8-general-ci-and-utf8-unicode-ci.


How to pass variable from block and access in it twig template I'm trying to make custom block but I have problem accessing variables in template.

My block code:

namespace Drupal\more_topics_rollout\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 *
 * @Block(
 *  id = "more_topics_rollout",
 *  admin_label = @Translation("More topics rollout"),
 *  category = @Translation("Blocks")
 * )
 */
class more_topics_rollout_block extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#title' => 'More topics'
        );
    }
}
?>

My module file:

function more_topics_rollout_theme($existing, $type, $theme, $path) {
    return array('more_topics_rollout' =>
        array(
            'variables' => array(
                'title' => null,
                'body' => null,
                'description' => null
            ),
            'template' => 'block--more-topics-rollout'
        )
    );
}

And when I'm trying to display title with {{ title }} it doesn't render. When I'm trying to access variables I know for sure don't exist like {{ dasdasda }} it doesn't throw any errors. Can someone explain this behavior to me?

Can someone explain this behavior to me?

The render array returned by the build method in the block plugin does not have a theme or type. This means that it will default to markup (iirc). The theme/template is not being used because the render array does not specify to use it.

You can find an example of implementing render arrays on drupal.org's documentation page, Render arrays. This explains the default element properties.

How to pass variable from block and access in it twig template?

The render array should have the #theme element property set to the theme definition key.

  public function build() {
    return [
      '#theme' => 'more_topics_rollout',
      '#title' => $this->t('More Topics'),
      '#body' => 'My body',
      '#description' => 'My description'
    ];
  }


jQuery hotkeys plugin I've found a nice plugin to bind hotkey combinations like Ctrl+A for submit buttons, but I don't understand how I can apply this to my form submit button.

Can anyone put me on the right direction?

It looks like what you'll want to do is add it in a separate js file in a module. Use hook_form_alter() or hook_form_FORM_ID_alter()and identify the form that you want the script run on. Then In hook_form_alter() use drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js'); to add the JavaScript file to that page.

Also in hook_form_alter(), you'll want to identify the button you want to add this to and add a prefix and suffix markup to it.

$form['button']['#prefix'] = array('
');
$form['button']['#suffix'] = array('
');

In the JavaScript file, where you see div.foo you'll want to enter the name of that div that you created on the button.

$('div.my-button-class').unbind('keydown', 'Ctrl+a', fn);

Also in hook_form_alter() you need to add a class to an input or button or whatever you are using.

$form['field']['#attributes'] = array('class' => array('my-other-class'));

For this, in the js file you need to replace:

$('input.my-other-class').bind('keyup', '$', function(){

EDIT: Note the input.class. If you're targeting a different type of element this will need to be changed accordingly. Same with div. class. I think you can also do IDs like input#my-input-id.


How to check if the AMP module (Accelerated Mobile Pages) is working? I'm testing the drupal AMP module (Accelerated Mobile Pages), well, I've installed it, pre-configured it (I've not created the subtheme..)but I've enabled it for one node (just for a test).

How can I test it ? Doing a google search on my browser ?

Thank you.

The first thing that needs to happen is to get it reindexed by Google so it knows about it.  I suggest configuring Google Search Console on your site https://support.google.com/webmasters/answer/4559176?hl=en  You can request it to be reindexed there. It was called Google Webmaster Tools before they rebranded it.
Its as easy to set up as Google Analytics.  It shows a display of what your site looks like on desktop, as Google sees it.

It does show you want it looks like ton AMP.


Allow views custom plugins on a particular filter criteria only I have started to create a custom views plugin to sort the fields in view according to the video views(not node views but youtube views) on my video content type.
This is how I've implemented hook_views_data():

$data = array();

$data['post_video_views']['table']['group'] = t('PROJECT_NAME');

$data['post_video_views']['table']['join'] = array(
  'node' => array(
    'left_field' => 'nid',
    'field' => 'nid',
  ),
);

$data['post_video_views']['popular'] = array(
  'title' => t('Popular videos'),
  'help' => t('Youtube views'),
  'field' => array(
    'handler' => 'views_handler_field',
  ),
  'sort' => array(
    'handler' => 'views_handler_sort',
  ),
);

This gives me an option to sort ascending and descending and also provides the fields to add. Everything working fine till this step.

Now, I want that this options should only appear when when I have the following filter criteria satisfied: Content: Type (= Video). How can this be done? I know this should be simple to do but just don't know where to do it.

P.S: I am using Views 3 with D 7.22.

You can use a hook_form_alter to add a conditional display of your filter based on the video selected option.

 /*
  *Implement hook_form_alter
  */

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
   //dsm($form) -> to get the form['#id']
   if ($form['#id'] == 'views-exposed-form-YOUR_VIEWS_NAME-DISPLAY') {
      $form['YOUR_FIELD_NAME']['#states'] = array(
       'visible' => array(
        ':input[name="THE_VIDEO_FIELD_NAME"]' => array('value' => 'THE_VIDEO_KEY'),
        ),
     );

   }
}

YOUR_FIELD_NAME is the field to display conditionally


update media object programatically If I have the id of an existing piece of media content, what can I do to update it (modify it)?

I know how to create a new piece of media , (with Media::create) , but not sure of the code to load and then updated an existing piece of Media.

thanks

Media is like any other entity based on ContentEntityBase in Drupal.

// top of your file
use Drupal\media_entity\Entity\Media;

// in a function
$media = Media::load($id);
// do stuff with $media
$media->save();

edit:

In a method of a class you would not want to use Media:: but instead use entityTypeManager service to load the entity:

$media = $this->entityTypeManager->getStorage('media')->load($id); where entityTypeManager is injected to your class.


How filter node inside view block by even nid (or odd nid) I have a view 2 blocks where I show some images and I'm trying to show the images with an even nid in the 1st block and the images with odd nid in the 2nd block

Do you guys have any idea if it's possible? and how?

@IsmaH answer is on the right track (use Regex for filtering nid). The problem in his answer is that this filter uses mySQL Regular Expressions - this is why his proposed regex is not working.

This worked for me:
^.*[13579]$

or this for even numbers: ^.*[02468]$

Notice: no slashes at the beginning and end of the expression.


Feeds with multiple Entity References per node? I have been racking my brains on how I can import a massive database I have collected into my Drupal website.

I have collected the below data for over 3000 players so manually uploading is not an option.

Can anyone help?

Player Content Type

Player,
Position(Term Reference)

Season Content Type

Season,
Appearance,
Substitute, Appearances, Tries, Yellow Cards, Red
   Cards, Club (Term Reference)

Each Player would have multiple seasons worth of data assigning to them, relating to previous seasons.

I cannot see a way in Feeds to implement this, I have tried with Entity Reference, but cannot see how I can add multiple Seasons to the same player through Feeds.

Here is some sample data.

Player - John Smith,
Position - Flanker

Season - 2013/2014,
Apps - 22,
Subs - 10,
Tries - 2,
YC - 3,
RC - 0,
Club - York RFC

Season - 2012/2013,
Apps - 12,
Subs - 1,
Tries - 0,
YC - 0,
RC - 0,
Club - Leeds RFC

I have some experience with Feeds, but not when using Entity References and the community does'nt really have anything that fits my bill.

If there is a better way to structure the data then I am open to suggestions as this is just the way I logically can work it out. I just ideally do not want to have multiple fields assigned to each player in one content type like 2013_apps, 2013_tries, 2012_apps, 2012_tries etc which would be the easy route...

Thanks

Craig

To my knowledge the solution you are looking for is not available directly through published modules.

You can find the beginning of the answering you are looking for at

http://clikfocus.com/blog/drupal-developer-tip-multiple-entity-references-using-feeds-importer

Create a custom target callback for your field importer. The targets array is keyed by the name of the target so it is necessary to differentiate your custom handler from the standard field handler for that entity reference field.

function my_module_feeds_processor_targets_alter() {

  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
    $info = field_info_field($name);

    if ($info['type'] == 'entityreference') {
      $targets[$name .':custom_handler'] = array (link is external)(
        'name'        => check_plain($instance['label'] .t(' (Import multiple values into multi-instance field')),
        'callback'    => 'my_module_set_target_entity_reference',
        'description' => t(''),
      );
    }
  }
}


Count number of nodes to be output I'm trying to figure out how many articles( nodes? ) will be displayed in a listing on our website, to use it to add classes to the elements that are rendered, so one can easily have different styling depending on the number of frontend elements. Right now there are six elements, so preprocess_node(&$variables) is called 6 times in template.php in my theme, but:  How can I obtain the number of nodes in the preprocess_page() - hook?

The nodes seems to be produced by a Promoted articles - type of listing.

No need to modify template files. Instead create a view of Article content type and then follow the below steps.

Into view Header part add field Global: Result summary
Now into above field configuration, inside Display text area add @total token.


How do I get a block and its content commited to a Git repo? Let's say I have created a block with some Full HTML (Facebook Feed) text inside. How can I commit the block and its text content into my Git repository, so my co-workers can pull it?

Turn it into a Feature. Bad thing is, it does not work on built-in custom blocks, so you need to use Boxes to get it work.

That way, you can export block as a module, and modules are text files, so GIT accepts them with it's full support.

Then, there is Features to Git module. It claims:

  Features to Git allows trusted users to write features directly to disk, commit
  them to git and push them to a remote. This makes it possible for site
  builders to be able to manage features in git without having to get their hands
  dirty on the command line.


Automatically group the sub menu items in drupal 7 My website contains project for following categories-

C language
Java language
Shell script

I have a custom content type "project", which has these fields as radio button. I have a menu item in main menu called project, which has above three categories as sub menu item. I want whenever I add any "C language" project, it should automatically attach as a sub menu item of "C language".

How to achieve it?

You could make links list attachment with views for each taxonomy term and then add them in theme_menu_link function if the link in variables matches. Note that requires customization in template.php


How to replace spaces with dashes when redirecting users through Rules? I have a rule that redirects users on login to a matching taxonomy term, ie. there is a taxonomy term that is identical to the user name and when a user logs in they are redirected to the url of that taxonomy term using tokens. The redirected url is as follows:

taxonomy/[account:name]

However, when there is a space in the user name then this causes problems, the URL of the taxonomy term has spaces automatically replaced with dashes, however the rule treats spaces as spaces and creates a url such as "mysite.com/taxonomy/first%20second"

Is there a way to replace the spaces with dashes?

Sometimes the solution to a problem, is to prevent the problem from happening.

So therefor I suggest you just do not allow spaces in your user names. To do so, use the Rules module (which you already have), and implement a rule that looks something like so:

{ "rules_disallow_spaces_in_user_names" : {
    "LABEL" : "Disallow spaces in user names",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_presave" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "account:name" ],
          "match" : "\\b \\b",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "User names are not allowed to contains spaces, please correct",
          "type" : "error"
        }
      }
    ]
  }
}

Some more details about this rule (which you should be able to import in your own site using the Rules UI):

Rules Event: "Before saving a user account".
Rules Condition: use a regex to check of the user name contains a space (adapt the regex if needed).
Rules Action: set an appropriate error message (adapt if needed).

The additional advantage of this approach is also that you don't need the PHP filter for it to work (as suggested in one of the comments).


drupal overlay text when you hover over the image views I have the content type with image, title and text fields.
I deduce views. I want to hover over the image appear the title and text field and a button with link.
Example http://demo.weebpal.com/#onepage portfolio section

how to do it?

This is only in part a Drupal question. The part that interests you most is the CSS styling.

As a tutorial, this could take several hours to explain, using the classes, wrappers, fields and so forth. I will jump over the styling, but I hope this will help as well.

As for the view itself, managed by Drupal, it is a little tricky. You need 2 containers in a wrapper. The first container should have the link set on the image and the second container should have the rest of the text and buttons.

Create a page or a block view listing all your nodes you need to include, printing fields.

Add the field image and set it to link to the node itself.

Add the text fields you need, one after the other, in the right order (title on top, text in the middle, button - linked to content - at the end and so forth).

Here comes the Drupal tricky part. Set everything as "exclude from display".

Now, as a last field, add a Global Text Area and print the 2 containers. Use tokens generated by Drupal and include them inside the containers.

For the first container, write down the wrapper code including the link over the image as a token generated by field no. 1.
For the second container, write the code for the wrapper and include inside every token for the hover visible content, in the proper order.

Then you need the right CSS, using position absolute, setting the view wrapper as relative and the second container as absolute.

Good luck.


Post content to Facebook Wall I'm using Drupal 7.

I've an Article content type, when it gets published it needs to be posted into my Facebook Wall. How can I implement this process? I've searched the drupal.stackexchange.com but I couldn't find the right way to do. Can you put me through?

Use the Drupal for Facebook module. It's not the easiest thing to setup in the world, you'll have to read the docs carefully. One of the features is publishing site content to a Facebook Wall.


Merge production site's content into staging through database tables I am working on a major upgrade on my website which includes several new modules being installed, various theme changes, updates on existing modules and a few modules that were uninstalled.

All the changes have been made in the staging site but, in the meantime, content is continuously being added in the production site. Since the staging site was a mirror of the production site (at that time), I was thinking that since the configuration changes that I made are a lot, I could just merge the database tables that are related to content in the staging site and make it my new production site (after some testing that everything works OK of course).

Notice that I have already checked the Deploy and Node Export modules but the first one is still in Alpha and the second does not support exporting revisions (which is a critical issue for my site).

My question is: what are the database tables that I should export from the production site in order to transfer all the content (nodes, revisions, profile2 entities, files) from the live to the staging database?

Keep in mind that no structural changes related to entities have been made to either database, so they should be identical.

From a preliminary search, the tables that seem to be relevant are: field_* , node_* , taxonomy_* , url_alias, profile, location*.

Is there something that I' missing here (other tables that I should copy or possibly a better way to do what I'm after)?

try the migrate or feeds modules. I recently used the migrate module with great success, though it does require you to write your own classes.


Injecting metadata into all nodes within one folder For my school I need to add metadata into the  tag of every node/page within the folder /course/

The metadata is the same for every page in this folder:

<meta class="swiftype" name="tags" data-type="string" content="course" />

This will allow me to use weighting for all our course pages in the Swiftype search app.

I've narrowed it down to the html.html.twig file in \core\modules\system\templates - where I believe I need to be adding something along the lines of:

if (preg_match('$^course/', $_SERVER['REQUEST_URI']])) { print_metatag }

But I won't be wanting to use print_metatag. Instead I should be using the fixed metadata referenced above.

Can anyone help me figure out what I need to use, and where, to apply this metadata to all those /course/ nodes/pages.

Many thanks!

You won't be able to use PHP like that in Twig, but your logic isn't far off. One of the reasons Drupal 8 switched to using Twig was to avoid having potentially unsafe PHP in template files – this sort of thing generally belongs in a module rather than in a template, especially as it's not related to the presentation of content.

Drupal doesn't have a concept of folders, but we can look at the path of the content (e.g. /courses/drupal-development or /contact-us or /news/2018/cool-thing-that-happened) and work out if it's 'under' courses or not that way.

Something like this should work, but is untested:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $current_path = \Drupal::service('path.current')->getPath();
  $exploded_path = explode('/', $current_path);

  // Add Swiftype metatag, see https://swiftype.com/documentation/site-search/crawler-configuration/meta-tags.
  if ($exploded_path[1] === 'courses') {
    $metatag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'tags',
        'data-type' => 'course',
        'class' => 'swiftype',
        'content' => 'course',
      ],
    ];

    $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
  }
}

Or to do it by content type:

/**
 * Implements hook_page_attachments().
 */
function YOUR_MODULE_NAME_page_attachments(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface) {
    if ($node->getType() === 'instance') {
      $metatag = [
        '#tag' => 'meta',
        '#attributes' => [
          'name' => 'tags',
          'data-type' => 'course',
          'class' => 'swiftype',
          'content' => 'course',
        ],
      ];

      $page['#attached']['html_head'][] = [$metatag, 'swiftype_course'];
    }
  }
}

If you need help setting up a module then take a look at https://befused.com/drupal/first-drupal8-module - but you can stop once you've created a your_module_name.module file – this is the file that the code above will go into.


How to attach node into panelized node? I've got content type which panelized using Full page override. So I would like to attach an existing node into newly created node and assign it into the region as normally you would do this at /node/%/panelizer/page_manager/content.

How this can be achieved programatically?

So far I've the following code:

<?php
# Usage: drush scr panelizer-test.drush.php

# Input variables.
$content_type = 'my_content_type';
$node_title = 'Content 1';
$did = 811; // Hardcoded display id from panels_display table (e.g. bootstrap_threecol_stacked).

# Load ctools includes.
ctools_include('plugins', 'panels');
ctools_include('common', 'panelizer');
ctools_include('context');

// Find the node in order to attach it to panelizer.
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', $content_type)
  ->propertyCondition('title', $node_title)
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();

if (!empty($entities['node'])) {
  // Load the node.
  $nid = current(array_keys($entities['node']));
  $node = node_load($nid);

  // Create an empty context object.
  $node_context = ctools_context_create('node', $node);
  $node_uuid = $node_context->data->uuid;
}

// Submit Panelizer content form (/node/%/panelizer/page_manager/content).
$new_pane = panels_new_pane('node', 'node');
$plugin = ctools_get_plugins('ctools', 'content_types', 'node');
$form_state = array(
  'contexts' => array( 'panelizer' => $node_context),
  'pane' => $new_pane,
  'plugin' => $plugin,
  'values' => array(
    'nid' => "$node_title [id: $nid]",
    'override_title' => TRUE,
    'override_title_text' => 'FOOBAR',
    'override_title_heading' => 'h2',
    'links' => FALSE,
    'build_mode' => 'teaser', // or: 'full'
    'op' => 'Finish',
  ),
  'op' => 'add',
  'subtype' => array('title' => 'Existing node'),
  'subtype_name' => 'node',
  'step' => 'form',
  'wrapper_callback' => 'ctools_wizard_wrapper',
  'conf' => array(
    'build_mode' => 'teaser',
    ),
  'no_redirect' => TRUE,
);
drupal_form_submit('ctools_node_content_type_edit_form', $form_state); // And save it.
if ($errors = form_get_errors()) print_r($errors);

// Submit Panelizer main form (/admin/structure/types/manage/%/panelizer/page_manager/content)
$display = panels_load_display($did);
$layout = ctools_get_plugins('panels', 'layouts', 'bootstrap_threecol_stacked');
$renderer = panels_get_renderer_handler('editor', $layout);
$form_state = array(
  'values' => array(
    'display_title[hide_title]' => '0',
    'display_title[title]' => '%node:title (foo-bar)',
    //'panel[pane][top]' => '12867,12868,12869,12870', // See: pids from panels_pane table
    //'panel[pane][left]' => '12860',
    'panel[pane][middle]' => "12861,12862,12863,new-$node_uuid", // We need to use new pane uuid, not node's uuid.
    //'panel[pane][right]' => '12865,12866',
    //'panel[pane][bottom]' => '',
    'op' => 'Save',
  ),
  'display' => $display,
  'renderer' => $renderer,
  'layout' => $layout,
  'no_redirect' => TRUE,
);
drupal_form_submit('panelizer_edit_content_form', $form_state); // And save it.
if ($errors = form_get_errors()) print_r($errors);

Here is a better approach by using the following function which uses modifies display in node it-self:

/**
 * Attach node into panelized node.
 *
 */
function example_attach_node_to_panelized_node($pnid, $nid, $region = 'middle') {
  $result = FALSE;
  $node = node_load($pnid);

  // Set default region based on layout.
  if (!$region) {
    switch ($node->panelizer['page_manager']->display->layout) {
      case 'landing_page':
        $region = 'primary';
        break;
      case 'sub_landing_page':
        $region = 'main';
        break;
      case 'bootstrap_threecol_stacked':
      case 'onecol':
        $region = 'middle';
        break;
    }
  }

  if (!$region) return; // Check if matching type.

  $panes = array();
  $my_block_pane_exists = FALSE;

  // Load the display.
  $display = $node->panelizer['page_manager']->display;
  $did = is_numeric($display->did) ? $display->did : example_resave_display($node);
  if ($display = panels_load_display($did)) {

    // Check if our pane is already there, if so, ignore the further processing.
    $panes = $display->content; // Get this display's panes.
    foreach ($panes as $pid => $pane) { // Loop through and add in our new pane.
      if ($pane->type == 'node' && $pane->subtype == 'node' && $pane->configuration['nid'] == $nid) {
        // If our node already exists we can skip this.
        $my_block_pane_exists = TRUE;
        return FALSE;
      }
    }

    // Attach our new panel.
    $uuid = ctools_uuid_generate();
    $new_pane = panels_new_pane('node', 'my_node', TRUE);
    $new_pane->uuid = $uuid;
    $new_pane->pid = "new-" . $uuid;
    $new_pane->panel = $region;
    $new_pane->shown = 1;
    $new_pane->configuration['nid'] = $nid;
    $new_pane->configuration['build_mode'] = 'teaser';
    $new_pane->configuration['link_node_title'] = FALSE;
    $new_pane->configuration['links'] = FALSE;
    $display->panels[$region][] = $new_pane->pid;
    $display->content[$new_pane->pid] = $new_pane;
    // Or: $display->add_pane($new_pane, $sourcePane->panel);

    if (!$my_block_pane_exists) {
      // Finished reordering pane's and save the panelized node.
      $node->panelizer['page_manager']->display = $display;
      $node->panelizer['page_manager']->display_is_modified = TRUE;
      $result = node_save($node);
      // Clear ctools caches.
      ctools_include('object-cache');
      ctools_object_cache_clear('panels_node_display_cache', $pnid);
    }
  }
  return $result;
}

In case the display is not initialized yet (it's in new state), you've to re-save the display in order to perform above operations.

/**
 * Re-save panelizer display.
 * See: https://www.drupal.org/node/2537006
 *
 * @param
 *   $nid (integer)
 *     panelized node id
 *
 */
function example_resave_display($node) {
  $node = is_numeric($node) ? node_load($node) : $node;
  $display = !empty($node->panelizer) ? $node->panelizer['page_manager']->display : FALSE;
  if ($display && !is_numeric($display->did)) {
    $new_display = panels_save_display($display);
    $node->panelizer['page_manager']->display = $new_display;
    $node->panelizer['page_manager']->display_is_modified = TRUE;
    node_save($node);
    ctools_include('object-cache');
    ctools_object_cache_clear('panels_node_display_cache', $node->nid);
  }
  return is_numeric($new_display->did) ? $new_display->did : FALSE;
}

Sample usage:

example_resave_display(800); // Use only in case the node is new.
example_attach_node_to_panelized_node(800, 123);
example_attach_node_to_panelized_node(800, 124);

See also: Updating Panelizer content programmatically which the above functions were based on it.


Improving UX with views exposed filters: automatically selecting certain options based on a profile value Background

On my site, users input their birthday, from which I use a computed field to calculate their age.  Then, based on that age, I use rules to add a taxonomy term to their profile to classify  them into one of the following age groups:

20s
30s
40s
50s
60s
70+

I have a view that allows members to search other members' profiles, and on this view I have an exposed filter for the taxonomy vocabulary age group.  The exposed filter widget is converted from a dropdown box to a list of checkboxes using the Better Exposed Filters module.

What I want to do

This works well, but I want to further improve the UX by automatically checking boxes based on the user's age when he or she visits the page.  Ideally, I want to automatically check the box for the user's own age group (e.g., a user in his/her 20s will automatically have the 20s box checked, while a user in his/her 40s will have the 40s box checked).

What I tried

I have no way how to implement this smartly.  One possibility that entered my mind is creating a panel with variants for each age group and then cloning a view once per age group and then using views rewriting functionality to rewrite the query strings for all of the views to check the appropriate boxes...  but this would lead to a huge amount of duplication and be very difficult to maintain.

As a huge fan of direct approach and writing own helper modules, I would make it happen mostly with jQuery.

Outputting user's age or age category in a hidden <div> is easy. You can append it to view's form with hook_form_alter, or simply output it as a block that will never really be seen.
Attach your JS library to views form (or again - simply load it and make it see if form is on page)
In behavior, read user's age from <div> created in 1. and based on that check checkboxes. Invoke click() on them for full emulation of user interaction (i.e. to reload what would get reloaded if it was user who selected it).


How to embed existing website in my Drupal 8 site? I have a site I created with Drupal 8, lets say http://falzon.xyz/.
Elsewhere, I have a site created with Jekyll, a bunch of static pages linked to each other visible http://www.elina-noe.eu/).
I'd like to "embed" the static site as a "subsite" of falzon.xyz, i.e. accessible as http://falzon.xyz/elina-noe/, by 'simply' putting all its files in a subfolder of the D8 site.
How can I do that?

Creating a subfolder inside your docroot folder such as docroot/elina-noe should suffice.

Put all the subsite files into this folder and if there is a index.html you can access your subsite just by visiting the subfolder http://falzon.xyz/elina-noe/


field_group #states does not working with using hook_field_group_build_pre_render_alter() I am trying to use #states on field_group at node add form.

From the search results I can find a couple of links which shows that hook_field_group_build_pre_render_alter() can make the magic but there is no luck for me.

I try to clear cache and dpm() some message inside the function. It seems the hook function has not been implemented at all.

These are the links I found.

Conditional fieldgroups/fieldsets in Drupal 7
hook_form_alter form state problems

After debugging I found that hook_field_group_build_pre_render_alter() is indeed working, but dpm() cannot work inside it at all.

For debugging, you can only use var_dump() or kpr() inside this hook function.


Load certain modules only if user is administrator I have a number of custom admin modules that deal with site statistics, site management, etc. These are quite heavy and I would like to reduce the site footprint for non-admin users.

Is there anyway to selectively load modules based on a users role? For example, if the user is an admin the load everything otherwise exclude modules admin1, admin2 and admin3.

Modules are either enabled or disabled in Drupal. They then may use access control to determine whether the user has access to them.

If these are custom modules, you may wish to write them so that either the heavy processing is skipped for non-admins, or that the data is cached to avoid calculations on every page load.


Search results showing nodes which are already under NODE_ACCESS_DENY In Drupal 7, I have some nodes that are restricted access for anonymous user. I implemented this using hook_node_access where if the user_is_anonymous and if the operation is View, I am giving NODE_ACCESS_DENY.

Now, how can I restrict these pages from showing in search results page for anonymous user?

You must flush the search cache after you have changed node access records.


New Relic: "Application Code (in /theme)" I have several Drupal sites with which I'm using New Relic to help monitor and debug performance issues.

I've been finding that when viewing the "Web Transactions" section under "Monitoring", that a large percentage of time is spent in "/theme". When I click in to view a trace, then view the Trace details, I often find that the majority of the time is listed in a rows named "Application Code (in /theme)".

The help link beside "Application Code (in /theme)" takes me to New Relic's PHP Custom Metrics Collection page. The documentation is clear enough, but what I don't understand is how to make this useful in Drupal. I'm guessing this is difficult for me because of Drupal's hook system, and (again guessing) that the "Application Code" that New Relic is referring to in this case are calls to theme() functions.

Is there something that I can do to get more useful information out of New Relic? First thing that comes to mind is "killing a kitten" and hacking core's theme() function to insert a New Relic Custom Metric, but I'd prefer not to do that (nor do I know for certain it will help!).

New Relic offers Drupal monitoring as part of their paid Standard plan to collect metrics for Modules, Hooks, and Views.

  The collection of Drupal-specific metrics can be
  controlled by the ini setting newrelic.framework.drupal.modules. It is
  enabled by default (in versions 3.0 and higher), and can be disabled
  with:

  newrelic.framework.drupal.modules = 0 Though this setting uses the
  word "modules", it controls the collection of all Drupal metrics:
  modules, views, and hooks.

  The PHP agent collects metrics for the following:

  Modules: Versions 2.5+. These metrics indicate time spent within each
  Drupal module. In versions 3.5+, time is calculated from the hook
  dispatch functions module_invoke and module_invoke_all. In previous
  versions, time was calculated from functions from a file with the
  ".module" extension where the file name and function prefix were a
  match.
  Hooks: Versions 3.5+. These metrics indicate time spent within
  each Drupal hook. Time is calculated from the hook dispatch functions
  module_invoke and module_invoke_all.
  Views: Versions 3.5+. These
  metrics indicate time spent within a view's view::execute method.

You are correct that New Relic: “Application Code (in /theme)” refers to the execution of the theme() function.  Given the throughput you referenced, this seems to be a minor issue, though there is definitely room for optimization if you're seeing ~7000ms response time.  I typically see around 400-500ms with similar throughput.


Change $form_state in AJAX callback I am creating a form which uses the form API '#ajax' attribute, and I need to make changes to $form_state when the AJAX-enabled button is pressed. Here's what I've got:

Inside my form builder function:

...
$form['some_fieldset']['add_more'] = array(
      '#type' => 'button',
      '#value' => t('Add more rows'),
      '#ajax' => array(
        'wrapper' => 'some-fieldset',
        'callback' => 'my_module_settings_ajax',
        'method' => 'replace',
        'effect' => 'fade',
      ),
    );

...

And here's the callback function:

function my_module_settings_ajax($form, $form_state) {
  // Make a change to $form_state
  if ($form_state['some_fieldset']['add_more']) {
    $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
  }

  return $form['some_fieldset'];
}

The change I've made to $form_state seem to be lost once the callback has finished. Is there any way to make a change to $form_state in this function, or there any other function I should use for this instead?

EDIT

As it turns out, the callback is the wrong place to do this logic. Instead, at the top of the form builder function, I added this:

// Respond to AJAX-triggger:
// Add new row
if ($form_state['triggering_element']['#name'] == 'add_more') {
  $form_state['values']['some_fieldset']['table'][] = array('first_field' => '',
                                                                'second_field' => '');
}

Of course, I had to give the button the name:

$form['some_fieldset']['add_more'] = array(
  '#type' => 'button',
  '#name' => 'add_more', // <-- Right here
  '#value' => t('Add more rows'),
  '#ajax' => array(
    'wrapper' => 'some-fieldset',
    'callback' => 'my_module_settings_ajax',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

And now it works!

You need to pass $form_state as reference; the AJAX function needs to be defined as in the following example:

function mymodule_settings_ajax($form, &$form_state) { /* … */ }


Articles listed in order base upon "Last-edit Date" instead of "Publishing Date" I have to solve a small bug in a Drupal 7.31 installation.

I have 3 rows in homepage, in which are listed 3 articles for each of them. Here a partial screenshot of Edit View for the first row, in wich Sort criteria is set to "Publishing Date".

In "Auto preview" pane, in the bottom area of this page, sorting seems corresponding to "Publishing Date" (node IDs are respectevely: "node-1901", "node-1861", "node-1904"), while when I load Homepage in browser, order is "node-1861", "node-1901", "node-1904".

It seems that in a case, order is made by "Last-edit Date" and not "Publishing Date".

How to make them coherent and, most important, how to display articles in Homepage in "Publishing Date" order ignoring "Last-edit Date"?

By your description, it seems to me that there's some code in your theme implementing a views hook or a theme hook, and doing a custom ordering before rendering the results (either altering the query, or altering the results after the query). The following hooks could do that:

hook_views_pre_execute()
hook_views_post_execute()
hook_views_pre_render()

plus the theme_preprocess_views_view()

I'd suggest having a look at the theme to see if any of those is implemented, and is getting in the way.


how to stop repeated content in view I am showing content from product content type of commerce module using view but view is showing some repeated content.how to solve this problem.

Did you check How do I remove duplicates when using the random sort? before?

If it does not help you check views_distinct module

  Relationships or other joins in Views often create "duplicate"
  results. For example, a node with a field that has multiple values may
  show up in the View once per value in the multi-value field. It's
  frustrating, and the "DISTINCT" SQL query option in the Views UI does
  not actually solve the problem because the result row is technically
  distinct. This module aims to give a simple GUI method to remove or
  aggregate these "duplicate" rows.


How to expose the node creation form in the front page? I created a new content type "project" and I want to create a view where every one can add a node (create a content) with my content type.

How to expose the form (to add a new project node) in the front (I do not just want to expose a link to add such node)?

In admin/people/permissions I granted the permission for ANONYMOUS USER to be able to create a new content.

To display content type form you can use formblock module as it description explains:

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

Enable the module
Go to Project admin/structure/types/manage/project
On the bottom left vertical tabs there'd be a Form Block, check Enable data entry from a block and save
Go to admin/structure/block and enable Project form block

I hope this'd help you.


Simplify Panels "Add content to" popup with fewer options for end users Echoing this unanswered question on D.O.

Is there a way to limit (and possibly reorganize) the Panels content types and panes presented to website editors?

Basically taking it from this:

To this:

I tried using some of the cTools API alter hooks, but no dice.  Any pointers?

Checkout https://drupal.org/project/Panopoly - they make a lot of customizations to this to improve the ui.

Some more details from the project page:

  Panopoly is powerful base distribution of Drupal powered by lots of Chaos Tools and Panels magic. The distribution is designed to be both a general foundation for site building and a base framework upon which to build other Drupal distributions


how to unpublish a comment rather than deleting it I like to use "threaded style" comments. However the problem with them is that when a users deletes their own comments all the "replies" to those comments are deleted as well.

Is there a way to "unpublish" those comments instead of deleting them?

To unpublish a comment, click on the link to edit it. In the page that appears, you will see an "Administration" section that is a a collapsed field set; select the "Non published" checkbox, and the comment will be unpublished.

If you unpublish a comment, the child comments will still be published; you need to unpublish each of them.


How to load page content by url programmatically in custom region How to load page content /node/add/page  programmatically in custom region? Example of custom region (https://jsfiddle.net/makbuk/1vetkgL2/).

I have found this How to get a node by its url alias? but it dosn't work for me.

$alias = "some/path/to/a/page";
$path = drupal_lookup_path("source", $alias);
$node = menu_get_object("node", 1, $path);

You can accomplish this with the Form Block module

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for including forms on panels.

Then in blocks (/admin/structure/block), assign the Form Block to your desired region.


How to make summary of body searchable? I've already looked at this answer and tried to change the search index view so that when I ran a search, I could type in a word appearing in a summary it would appear in my search results. I also ran cron to get the site reindexed but still, nothing appears when I type in a word that only appears in a summary.
How do I make the summaries in content searchable?

I did not figure out to do this, but a workaround was to actually make a separate field called summary and remove the default body and add a new body field without a summary.


Change input value on click when there is more than one paragraph There are two fields on my paragraph.

A number field
A text field

I want to change the value of the text field when I click on the number field.

Here's my script so far which is only good on the first paragraph because of field_my_content_paragraph_field[0]:

/**
 * @file
 * Javascript behaviors.
 */

(function ($, Drupal) {

  "use strict";

  /**
   * Handle paragraph fields on the node edit form.
   */
  Drupal.behaviors.myBehavior = {

    attach: function (context) {
      $('input[name="field_my_content_paragraph_field[0][subform][field_my_number_integer_field][0][value]"]', context).on('click', function () {
        var myNumberFieldValue = $('input[name="field_my_content_paragraph_field[0][subform][field_my_number_integer_field][0][value]"]').val();
        var myInputTextFieldValue = $('input[name="field_my_content_paragraph_field[0][subform][field_my_input_text_field][0][value]"]');

        switch (myNumberFieldValue) {
          case '1':
            myInputTextFieldValue.val('A');
            break;
          case '2':
            myInputTextFieldValue.val('B');
            break;
          case '3':
            myInputTextFieldValue.val('C');
            break;
        }
      });
    }
  };

})(jQuery, Drupal);

When there is a second paragraph on the node, the field names for the second paragraph are:

name="field_my_content_paragraph_field[1][subform][field_my_number_integer_field][0][value]"

name="field_my_content_paragraph_field[1][subform][field_my_input_text_field][0][value]"

How can I loop through the paragraphs, (or is it the DOM at this point?) so the text field value of the paragraph I'm in is changed on click?

I need to loop through the paragraphs with an .each() like so:

/**
 * @file
 * Javascript behaviors.
 */

(function ($, Drupal) {

  "use strict";

  /**
   * Handle paragraph fields on the node edit form.
   */
  Drupal.behaviors.myBehavior = {

    attach: function (context) {
      $("input[name$='[subform][field_my_number_integer_field][0][value]']").each(function (i) {

        $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]', context).on('click', function () {

          var myNumberFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_number_integer_field][0][value]"]').val();
          var myInputTextFieldValue = $('input[name="field_my_content_paragraph_field[' + i + '][subform][field_my_input_text_field][0][value]"]');

          switch (myNumberFieldValue) {
            case '1':
              myInputTextFieldValue.val('A');
              break;
            case '2':
              myInputTextFieldValue.val('B');
              break;
            case '3':
              myInputTextFieldValue.val('C');
              break;
          }
        });
      });
    }
  };

})(jQuery, Drupal);

Which solves the problem.


Theme a Panelized Content Type Not Working I'm trying to add a content type to an existing site. I've added it, panelized it, added fields, and everything seems to be working well. There is a second panelized content type in this site that is being themed from a file titled node--typename.tpl.php and is working correctly.

I attempted to name mine node--my-typename.tpl.php, cleared all caches, but nothing works.

I drush vset theme_debug 1 and checked for tpl suggestions but it doesn't really mention anything pertaining to theming the content type—just panelizer.

Is there a setting I'm missing here? I've combed through both content types and can't see a difference but one allows theming using node-- files and the other doesn't.

I figured out what I was doing wrong.

In my content type, under Panelizer > Full Page Override > Content I had to add "Rendered Node" to the main content area. This allowed me to use the node--my-typename.tpl.php file to theme this panelized content type.


Sortable, paged table retrieved using EntityFieldQuery How do you create a tabular, sortable and paged display in a custom module using EntityFieldQuery?  I've been looking all over for a working example and can't find one.  The entity has custom CCK fields, and using db_select it looks like I have to write joins and I'd rather avoid doing that if EntityFieldQuery brings in all the fields.

To add conditions for the content of the fields, you use EntityFieldQuery::fieldCondition(), while for enabling the pager you call EntityFieldQuery::pager() passing the number of rows shown in each page.
EntityFieldQuery::fieldOrderBy() could be handy, if you need to order the results by the value of a field.


How to send mail for every X months using rules? In my user profile there is date of orientation(date field) from date(current date) and end date.

When user fills the date field, it should generate an Mail for every X months.
                  example-according to screen shots i have two date field when user have given from date(current date or future date)based on that date for both date fields should trigger a mail every X months.

Requirements:

Rules, Rules UI and Rules Scheduler must be installed and enabled.

Step 1) Create a new component, I named it send mail every 2 months

Step 2) Add an action of Send Mail, fill out the form, see picture below.

Step 3) Add an action (again)

This time select Schedule Component Evaluation and select your component (send mail every 2 months)

  Note: this will re-schedule your e-mail to be sent 2 months after its
  sent for the 1st time

Step 4) For SCHEDULED VALIDATION DATE, erase everything and put +2 Months

For Identifier, put something like I did (see picture) so you know who the schedule is for.

For ACCOUNT, put account

Step 5) Create a new rule, for React on Event, select After saving a user account.

Step 6) Add an action, select Schedule Component Evaluation and select your component (send mail every 2 months)

Step 7) Click on the switch to data selection button

Step 8) Put your field in Scheduled Evaluation Date. My user date field is called From Date with a machine name of field_from_date Therefore, it's account:field-from-date

Click on Add Offset, put 2 and select Months. (This means it will send the e-mail 2 months from the from date.

For Identifier, put something like I did (see picture) so you know who the schedule is for.

ACCOUNT, put account


Module name and name of the directory the containing it Google and stack has come up dry so far, so I'll ask you: In Drupal 8, does my module folder need to match the name of my module?  Some basic testing indicates that they can differ with no harm done, but Drupal 8 is still a bit of a black-box to me and I don't want to find myself painted into a corner because of this.

Good conventions mentioned by Kevin aside, there's no technical reason for the names to match, no. What's important is the name of the .info.yml file, that's what defines the module machine name.

Drupal just interrogates the known module folder locations recursively looking for .info.yml files, so anything will get picked up regardless of folder name.


Different domains with same language Here is my situation

We have 2 websites: domain.es (use Spanish language) and domain.co.uk (English).
Customer asked us to register new domains: domain.mx (Mexico, so Spanish language) domain.com (English language).

We do not want let domain.mx see content from domain.es, but that what will happen, because our views (like all other stuff) are dependent on language.
We are considering to filter content by domain using https://www.drupal.org/project/domain however since we never used it before we are not sure if it will cover our needs.

I want to get your opinions guys, how would be best to manage content based on domain level but not a language. So domain.mx and domain.es are completely 2 independent websites and do not share values to each other.

Thanks!

If you want the .es and .mx content to be unique, you should treat them as different languages.

create a new mx-spanish language type.  even though it is "spanish" the system has no idea,  you can just load the unique content there.


Submit form and disable submission button I want to disable the submit button after it is clicked to prevent multiple submissions. I have:

$form['show'] = [
'#type' => 'submit',
    '#value' => $textforsubmitbutton,
    '#name' => 'submit',
    '#attributes' => array("onclick" => "javascript: this.disabled = true;"
    ),
];

but this disabled the button completely. Using "onsubmit" in place of "onclick" doesn't change anything on the button. So maybe I need something like:

    '#attributes' => array("onclick" => "javascript: this.submit; this.disabled = true;"
    ),

How do i fix this?

For those wanting to disable the form submit button on load, try this:

$form['actions']['submit']['#attributes']['disabled']  = 'disabled';


Commerce product entity not being saved by EMW from another entity form submit I'm using the module Commerce Stock Sources to manage different stock locations for my products.

When saving the Commerce stock sources form, on form submit, I want to update a field value on the Commerce product entity. The field is an Entity reference field.

The problem is that I can't get the field updated. No notice or error returning.

    //first I'm getting the values to be set; will have a simple array of IDs
    if (!empty($form_state['values']['plugins']['plugin_settings'])){
                $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
        }
    //next I'm loading the product entity; I have checked, the product is loading OK
    //and then the wrapper and the operations
    $product_entity = entity_load_single('commerce_product', $form_state['complete form']['#product']->product_id);
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

The field is not updated. I've checked to see if I can read values from product using entity_metadata_wrapper() and it works. When I try to update any field, it doesn't work.

I tried updating with field_attach_update(), but it doesn't work either.

        for($i=0; $i<count($selected_sources); $i++){
          $product_entity->field_product_location_store[LANGUAGE_NONE][$i]['target_id'] = $selected_sources[$i];
        }
        field_attach_update('commerce_product', $product_entity);
        entity_get_controller('commerce_product')->resetCache(array($product_entity->product_id));

Any thoughts?

It's seems that by using the product entity directly from $form_state['complete form']['#product']; the entity_metadata_wrapper() works as expected and it saves the values.

if (!empty($form_state['values']['plugins']['plugin_settings'])){
    $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
}
    //get directly the product, without entity_load_single()
    $product_entity = $form_state['complete form']['#product'];
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

Although the object loaded by entity_load_single() is identical with the object obtained by $product_entity = $form_state['complete form']['#product']; the entity_metadata_wrapper() works only for the second case, which seems more logical and is faster.


How to set role on the registration form programmatically I'm trying to create multiple registration forms with a role assigned to each.
It seems that my default value for the role is not keeped, but it works with other fields
Here is my code
$form = $this->entityFormBuilder->getForm($account, 'mycustomdisplay');
$form['account']['roles']['#default_value'][] = 'mycustomrole';

Thank you.

You need to do this in a form alter hook, not after the form has already been built.
function module_form_user_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($condition) {
    $form['account']['roles']['#default_value'][] = 'mycustomrole';
  }
}


How to create a custom frontpage using page--front.tpl.php and keep theme responsiveness I want my frontpage to be displayed with a full width image, some H2 header text and a navigation menu.

However using a page--front.tpl.php and applying custom css i am losing the natural responsiveness of my theme (at-subtheme), leaving me to apply mediaqueries.

What would be the apporiate way to set up a custom front page using my theme responsiveness?

There are different ways to set up a frontpage in drupal. I think the 2 most used ways are panels or context.

Panels allows you to create a page through drag and drop functinality. Almost every piece of content created in drupal (nodes, views, blocks, custom blocks, ...) can be added to a panel. In addition to that, if you use for example "omega" as a base theme, omega has a couple of default (responsive) build in templates you can use with the panels module.

Context allows you to expose content through conditions. So you can expose a block, view, node,... only on your frontpage. You will have to apply css to make your frontpage responsive though...

Both modules have there advantages and disadvantages, you should check them out and decide which is best for you. I'm certain there are other ways to create a frontpage, but this is how I usually get the job done.


node anchors on single front page website I'm building a single page website Omega subtheme on drupal 7. I've got a menu on top with 5 items which I want to link them with an other 5 nodes on the same page. Obviously we need anchors here.

Which way do you think is smarter to achieve this?

PS:No, I don't want to use Single Page Website module

We created the Single Page Site module, to incorporate one page websites into Drupal. This is an example of a website using it: http://starfisk.com
Some more details about this module (from its project page), which is available for both D7 and D8:

This module provides functionality to create a single page website.
It allows you to automatically create a single page from a menu. The module will render all the content from the links, that are configured in the menu, on one page. It will then override the menu links so that they refer to an anchor instead of a new page.


How can I tell if a config entity hasn’t been saved yet? How can I tell if a config entity hasn’t been saved yet?

isNew();

this core test confirms it:

// Config is no longer new once saved.
$this->config->save();
$this->assertFalse($this->config->isNew());

(from core/tests/Drupal/Tests/Core/Config/ConfigTest.php)


What does the AdvAgg bundler do? I read the description, but I didn't understand what this component does.
The description says:

If not checked, the bundler will not split up aggregates.

I know the purpose of aggregation is joining files and I take this splitting isn't de-aggregation. What is it?
The description for the CSS bundling option says:

If file count is selected then each bundle will try to have a similar number of original files aggregated inside of it.
If file size is selected then each bundle will try to have a similar file size.

I would like to understand what that means too.

The short answer is to take advantage of the browser cache. It can also be used to take advantage of the number of parallel connections that the browser can make.

Example:
Front page has a.css and b.css; node 1 has a.css, b.css and c.css. If using one aggregate then the user going from the front page to node 1 would have to download all of the CSS again. By splitting up the aggregate in a smart manner the user will only need to download c.css


Do these options affect other modules and possibly core? I have a question about downloading an unstable version of a module using composer. I run composer require 'drupal/page_manager:^4.0' but I get this error message.

  The requested package drupal/page_manager ~4.0 is satisfiable by drupal/page_manager[4.x-dev, 4.0.0-beta3, 4.0.0-beta2, 4.0.0-beta1] but these conflict with your requirements or minimum-stability.

I looked at the repository, and they don't seem to have a stable version. So I read that in my composer.json file I should put the following lines.

"prefer-stable" : true,
"minimum-stability": dev,

If I set these options to composer, will this affect other modules and possibly Drupal core? when I update core, could it download a development snapshot higher than the current version? If so, how do I downloading the development snapshot only for a module without affecting other modules/core?

This is just fine, this thread describes that it is there by default.

So it is fine to set minimum-stability to dev.

The reason why you can set the minimum-stability, is because that prefer-stable, prefers stable packages over unstable.


Drupal 7 Module to Set image src to a URL I am trying to do something pretty basic but I just cannot find the right module.

All I want to do is have a field type or widget that I can use in a content type that will set the image tag's src property to a URL without actually adding the file to Drupal.  The images for our site are located in a database and are accessible via a URL.

I tried the Media module but that adds the file to the Drupal images folder.

There's got to be a module for this.  Anyone know the right one?

Thanks.

I think you're looking for Remote File Source.

  Remote File Source allows you to add a file from a remote server to a filefield without transferring it locally.


View search by multiple values, how? Now I have built a search view and expose one parameter for user to filter search results.

The parameter is input via a textfield, i.e.:

 +------------------+
 | car              | [search]
 +------------------+

Is it possible to modify the above search view by:

change the textfield to textarea
such that user can input multiple values (one at each row)
the filter will match any of the values entered
and present results

i.e.:

 +------------------+
 | car              | [search]
 | magazine         |
 | 2012             |
 |                  |
 |                  |
 |                  |
 +------------------+

If you are trying to search through a view's node title field, node body field, or some other string field specifically, you may be able to customize the filter how you would like:

Add filter Node: Title or Node: Body
Set the Operator to Contains any word
Click Expose
Click Update

This will display a filter to the user that can filter the view by the corresponding field values that contain any of the entered words, separated by spaces. This does not format the textfield into a textarea, but works functionally as you had asked.


Get the vocabulary ID by term or node I am going to check whether a term belongs to a designated vocabulary.

Which function is used to get vocabulary by term or node?

In Drupal 6, if you know the taxonomy term ID, you can get the vocabulary ID by using the following code:

$term = taxonomy_get_term($tid);
$vid = $term->vid;

If you have a node ID, then you can use the following code to get the vocabulary ID of all the taxonomy terms associated with the node using the following code:

$node = node_load($nid);
$vids = array();

if (!empty($node->taxonomy)) {
  foreach ($node->taxonomy as $tid => $term) {
    $vids[] = $term->vid;
  }
}

In Drupal 7, the code would be the following:

$term = taxonomy_term_load($tid);
$vid = $term->vid;

In Drupal 7, the node property $node->taxonomy doesn't exist anymore. Instead, there is $node->field_<vocabulary_name>, which is an array with two different structures.

tags

other taxonomy terms

Using field_get_items(), you would get the taxonomy terms in the language they would be displayed, or in the language whose code is passed as argument to the function.

$items = field_get_items('node', $node, $field_name);

$node contains the node object, and $field_name the name of the taxonomy term field.

$items contains a simplified array, compared to the array contained in $node->field_<vocabulary_name>.


How to render element array piece by piece I have template form.html.twig Drupal commerce is using it to render cart form. I made override of that template, to be able to change it only for cart form, without affecting other forms. That part works well.

Form template looks like this:

<form class{{ attributes }}>
  {{ children }}
</form>

Where "children" is markup. But (even not documented in template it self) there is also "element" array. So I can print the it instead of children and get the same results:

<form class{{ attributes }}>
  {{ element }}
</form>

This also works well.
Now, I need to print it piece by piece. If I put loop like this:

  {% for single in element %}
    {{ single }}
  {% endfor %}

I get some form elements doubled, so obviously some elements must be excluded. But which ones?

Here is the list of all element keys inside this "element" array:

#action
#prefix
#suffix
#pre_render
#cache
#attached
#substitutions
#form_id
#type
#build_id
#token
#id
#attributes
#method
#theme_wrappers
#defaults_loaded
#tree
#parents
#validate
#submit
#theme
#processed
#required
#title_display
#description_display
#errors
#array_parents
#printed
show_view_elements
output
footer
edit_quantity
remove_button
form_build_id
form_token
form_id
actions
#sorted
#children
#render_children

How can I find out what elements  should I print and what to exclude to get the same result (valid form) as when printing top element:

{{ element }}

Update: purpose of this is to render cart page a bit differently. Now, inside the form element I have first table with purchased items, then, bellow table goes div with sub-total and total prices and then div with "Update" and "Checkout" buttons.
What I want is to display those 3 elements in 2 columns. In left one there should be only table with items and in right prices, buttons and some additional info.

BTW, I'm already displaying another form that way. It's template file looks like this:

<form{{ attributes }}>
  {{ title_prefix }}

  {{ element.pages }}
  {{ element.elements }}
  {{ element.form_build_id }}
  {{ element.form_token }}
  {{ element.form_id }}
  {{ element.footer }}
  {{ element.actions }}
  {{ element.children }}
  {{ element.progress }}

  {{ title_suffix }}

</form>

There I print progress bar bellow the other form elements.
But I have problem achieving the same with cart form.

Succeeded it "my way". Template now looks like this:

<form class{{ attributes }}>

{{ element.output }}
{{ element.footer }}
{{ element.form_build_id }}
{{ element.form_token }}
{{ element.form_id }}
{{ element.actions }}

</form>

element.output prints the table
element.footer prints the prices
element.actions prints the buttons
and other fields are printing necessary hidden fields

I know that @4k4 is right and I even tried solution he proposed before, but for some reason it didn't work for me (probably my mistake) and I didn't have more time to spend on this and this solution works well.

Posted this, because it's answer to this question and IMHO this should be "legal" way to print form, achieved only from twig without forcing on creating theme function and other stuff.

Please be gentle with minuses.


How to call custom javascript function defined in js file from .module file I have some custom menu defined for which in the page callback function I want to execute some javascript function defined in some js file which is included in .info file.

The alert and console.log works as file is included on the page and loading successfully in browser, but custom js function not working. It says function is not defined.

.info file:

scripts[] = js/code_init.js

Here is my code in .module file:

function mymod_process_file(){

     $count = 2;
     for($i = 1; $i <= $count; $i++) {
     $file_path = "/abcd.html";

     echo "counter:$i";
     echo "<script language='javascript' type='text/javascript'>";
     echo "myFunction('".$file_path."', 'index_".$i."');";
     echo "</script>";
     }
     return 1;
}

I have faced same kind of issue few days ago and I have resolved it by adding type as module to the script tag. All script with type=module have differ attribute. It download such js parallel with loading of other page and then run them in order but after the parsing is done.

This might help you:

<script language='javascript' type='module'>


Are there filters in drupal? I'm a wordpress user and I was wondering if Drupal has the ability to let coders modify the output, or return value of a function trough filters.

(in WP you can do this with add_action / add_filter)

Yes, there are a few methods.

One uses what Drupal considers filters.  I a not sure what the best starting point for these is, but the API reference for hook_filter_info should be a decent read.

Another is via preprocess and process functions.  Again, I am not sure what the best online starting point for these is, but take a look at the API reference and search for "process" and "preprocess".

The concept of Drupal 7 render trees along with field templates / template functions can also be thought of as a way to process content for display.

My copy is at work, but I think both filters and preprocess/process hooks are discussed in Drupal 7 Module Development.  I can't remember if render trees and field templates are in that book or their theming book.


How to rereference taxonomy? My goal was to create a taxonomy reference field in Drupal 8.2.

Consider these to field definitions on an entity.

    // #1
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setTargetEntityTypeId('taxonomy_term')

    // #2
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSetting('target_type', 'taxonomy_term')

Here is how #1 is documented:

  /**
   * Sets the ID of the type of the entity this field is attached to.
   *
   * @param string $entity_type_id
   *   The name of the target entity type to set.
   *
   * @return $this
   */
  public function setTargetEntityTypeId($entity_type_id) {

Looking at the description both should produce the same result - set target entity type.

The #1 creates me an input with autocomplete from page names and page types.

The #2 creates n input with autocomplete from taxonomy terms.

Why does this happen and what is #1 is meant to do?

As I answered at  Limit Taxonomy Term references to special vocabulary  if you want to create a custom entity_reference field on custom entity type try something like

$fields['book_cat'] = BaseFieldDefinition::create('entity_reference')
   ->setLabel(t('LABEL'))
   ->setDescription(t('DESCRIPTION'))
   ->setSetting('target_type','taxonomy_term' )
   ->setSetting('handler','default' )
   ->setSetting('handler_settings',['target_bundles'=>['VOCAB_MACHINE_NAME'=>'VOCAB_MACHINE_NAME']] )
   ->setTranslatable(TRUE)
   ->setDisplayOptions('form', array(
       'type' => 'options_select',
       'weight' => -1,
       'settings' => array(
           'size' => '60',
           'placeholder' => '',
       ),
   ))
   ->setDisplayConfigurable('form', TRUE)
   ->setDisplayConfigurable('view', TRUE);

AND  about  setTargetEntityTypeId :(Doc)

  Sets the ID of the type of the entity this field is attached to.

and used when you want attach  field(s)  not  for referencing.


How NOT to redirect using the Rules module? I have a comment form in a panel. The path to the panel is user/[uid].

When I post a comment I am taken to another page where all the comments are shown (user/[uid]/comments.) I do not want this, I want to stay on the same user/[uid] page.

Does anyone know how to do this using the Rules module?

A possible "remedy" for this is to use the Rules module (indeed ...). To do so, have a look at my answer to "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?".

Use the rule included there (within "Option 1"), and apply these changes to it:

Adapt the regular expression within the "Rules Condition", to make it match your (user/[uid]/comments.).
Adapt the "no_access" url to your user/[uid].
Probably you don't want to display any message, so just remove that "Rules Action".


How to add more than one tags for content? For example, I want to create two tag, one is "new", the other is "test"，Now tags is "new test"
Screenshot:

You already seem to have 1 field for this content type that is a term reference, whereas the corresponding taxonomy has at least 2 terms (i.e. "test" en "new").

Solution 1:

Allow "multiple" or "unlimited" values for the term reference you're already using, which is an option with the field settings of your existing term reference. Which you'll find at /admin/structure/types/manage/mycontenttype/fields/field_term_ref, assuming field_term_ref is the machine name of your term reference, and mycontenttype is the machine name of your content type.

Solution 2:

Create an additional term reference field for this content type, and add one of those 2 terms to the new field, and delete it from the term reference field you already have.

Note: Which solution to choose depends a bit on your use case:

If the terms are somehow "related", then solution 1 is what you should use. E.g.: Target audience with terms like visitors, members, editors, administrators.
If the terms are not at all "related", then go for solution 2. E.g. Topic and Target audience.


On logout as admin, PHP code from node pages is executed. When I log out from site as Admin, PHP code in the node pages is being executed.
For testing, I had put node access rebuild function in one of pages and the site went slow after that. When I checked in the xdebug profiler scripts, I came across this eval() call.
Is it the default functionality or is it some of my code that has affected this?

If the page you are referring is a node page, then the node could be using the PHP input format, and in that case the node body would be passed to eval() through drupal_eval().
If the page is a view page, the Views module allows the administrator users to enter PHP code that is executed, through drupal_eval(), in specific circumstances.

In both the cases, a block visible in the page could be using PHP code to set it block visibility.

There could be other modules that call drupal_eval(). Those modules pass to drupal_eval() code that users with the right permission enter in the module's settings; if you have one of those modules, you should remember ending PHP code in a text area.


How do I print a specific meta tag attribute value in html.tpl.php? I am trying to create WebSite schema condition output in html.tpl.php in Drupal 7, so installed schema.org module, but it doesn't come with all the fields that my project required, for example, description. How do I get the description value from "admin/config/search/metatags/config/global%3Afrontpage"?
What I have so far.
<?php if(drupal_is_front_page()) {
$logoSchema = theme_get_setting('logo');
$urlSchema = $GLOBALS['base_url'];
echo '
<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "url": "'. $urlSchema .'",
  "name": "Company Name, Inc.",
  "image": "'. $logoSchema .'",
  "description": "**NEED HELP GETTING THE VALUE**",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "'. $urlSchema .'/search/{search_term_string}",
    "query-input": "required name=search_term_string"
  }
}
</script>';
} ?>
</head>

create a preprocess_html function in template.php
function porto_sub_preprocess_html(&$vars){
  if (drupal_is_front_page()) {
    if (isset($vars['page']) && isset($vars['page']['content']) && isset($vars['page']['content']['metatags'])) {
      $meta_tags = $vars['page']['content']['metatags'];
      if (isset($meta_tags['global:frontpage']) && isset($meta_tags['global:frontpage']['description'])) {
        $meta_desc_list = $meta_tags['global:frontpage']['description'];
        if (isset($meta_desc_list['#attached']) && isset($meta_desc_list['#attached']['drupal_add_html_head'])) {
          if (isset($meta_desc_list['#attached']['drupal_add_html_head'][0]) && isset($meta_desc_list['#attached']['drupal_add_html_head'][0][0])) {
            if ($meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value']) {
              $vars['front_page_meta_desc'] = $meta_desc_list['#attached']['drupal_add_html_head'][0][0]['#value'];
            }
          }
        }
      }
    }
  }
  drupal_add_http_header('Cache-Tag','mktg',true);

2. This defined meta tag is accessible from html.tpl.php
 if (!isset($front_page_meta_desc)) {
       $front_page_meta_desc = '';
     }

In the schema JSONLD, you need to call the variable.
"description": "' . $front_page_meta_desc . '",


Saving a value from Javascript on Drupal form submit I have a jQuery map that I've built that allows users to select states and counties. This is all done in Javascript. I would like to, on form submit, take this data and submit it to the user's profile2.

Should I create an empty form element and fill it somehow? It seems like there wouldn't be a way to pass any information to a form that happened after page creation.

Is this map that you created already in place? Were/are you utilizing it on the user's edit info page or somewhere else on the site?

You may want to consider instead using something like Geofield: https://www.drupal.org/project/geofield

This would allow user map input (on an OpenLayers map) via a new field that you can attach to the User entity (or any fieldable entity) and would collect the data into a "Drupal" way, freeing you up to focus on how to display the information, as opposed to doing a custom POST action using JS to your Drupal site, which could be time-consuming.

If you are looking to do this in JavaScript, you may want to consider the Services module, which would allow you to access your site's CRUD actions, therefore editing the information on a User's profile, but this means that you'd have to have to include a field to collect this information on the User entity anyways, at which point having a Geofield may be useful to you.


How do I set up HTTPS on a multi-site? I made a couple websites on a drupal multisite setup.. and I want to start using https. And.. I'm just lost. Can anyone help me get started?

So, here's the details of how I have things set up..

So I have like a drupal 7 install on ubuntu, with 3 sites.. all in the var/www/html/sites folder, so for example, the folders are named

site1.example.com
site2.example.com
site3.example.com

and the sites.php file directs the requests so like

$sites = array(
    'domain1.com' => 'site1.example.com',
    'domain2.com' => 'site2.example.com',
    etc
);

and as far as dns is concerned, each domain just points at the IP of the ubuntu server and drupal handles the rest.

All that is so far so good. Got several working sites.. each domain goes to the right site.. etc. But they use http. How.. do I go about.. getting a certificate that handles the 3 sites so that they can use https?  I've not set this up before.. I've been trying to read through whatever I can find.. but I'm confused! Sorry, not sure what to do, I'm just .. lost!

Are you using a module to handle the multisite configuration? A place where you can associate each site to a domain, theme and other configuration settings. Also you should be able to add https protocol to the desired domain.

If you don't use any module, check settings.php of each site looking for $base_url where you can change it from http to https.