Migrating data from a CSV source: Where should the source go? I'm trying to do a migration of an old (and full of nodes and comments) D7 site, to a Drupal 8 brand new one.

In order to import only the contents, I'm trying to do the migration from a csv file (with the stuff that I've exported using views).

My question is, how to set the source? Full path?
I'm using a test csv file and I put it at the root folder, at the same place where the index.php file is.

I tried this:

source:
  plugin: csv
  path: 'http://www.example.com/myfile.csv'
...

And this:

source:
  plugin: csv
  path: '/myfile.csv'
...

(with and without the slash)

I keep receiving this error when I try to run the migration script:

An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /batch?id=20&op=do_nojs&op=do
StatusText: Internal Server Error
ResponseText: The website encountered an unexpected error. Please try again later.

What should I do?

Please add the file as :

source:
  plugin: csv
  path: 'public://csv/test.csv'

And under sites/default make a folder named as csv and place the file inside that. It will work.


Multiple registration phases I'm having trouble figuring out how to have a registration in different phases. This is what I would like to do:

A user registers with a name and an email or register with facebook.
He will receive an email to set his password.
The user can now bookmark nodes. But when he would like to create a node of content type Proposal he needs to complete a full registration (I'm using Multi-step registration module). An email will be send to the administrator who needs to check the data and give the user a new role.

For now I have the second step. A user register with a complete form. But how can I add the facebook register or name/email register before it?

Seems to me that you should consider the Profile2 module for getting this to work.

Excerpt from issue # 1796856 :

  Multi-Step Registration module works out of the box with Profile2 and all we need to do is assign the profile type to a particular step.

That same issue also contains some extra details about getting around possible access errors.

Refer to the Community documentation of Profile2 for more details about this module.


ApacheSolr - No Documents or Data in Index For reasons unknown to me, Apache Solr isn't indexing any of the Articles that I create.

I have about 10 articles, just for testing, and Solr tells me that no documents have been indexed, nor have any documents been sent to the server for indexing.

I've tried reinstalling everything and deleting the Solr & Search Index to no avail.

What am I doing wrong?

Fixed the problem by reinstalling Solr. I might have missed something along the way the first time.

As for the original issue, I have no idea, but I'm considering this solved.


How do you pass more than one node to a route? I am working on converting a drupal 7 site to drupal 8 for some practice with 8. In my drupal 7 site, I have a custom hook_menu declaration with the following:

function solution_menu() {
  $items = array();
  $items['solution/%node/%node/%node'] = array(
    'title' => '',
    'page callback' => 'solution_build_solution',
    'page arguments' => array(1,2,3),
    'access callback' => 1,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function solution_build_solution($solution_node, $species_node, $problem_node) {
   //build solution
}

I am trying to accomplish the same thing in drupal 8 with a route. However, if I try something like the following i get an error:

wlh_decision.solution:
  path: '/solution/{node}/{node}/{node}'
  defaults:
    _content: '\Drupal\wlh_decision\Controller\SolutionController::displaySolution'
    _title: 'Solution:'
    _title_callback: '\Drupal\wlh_decision\Controller\SolutionController::solutionTitle'
  requirements:
    _permission: 'access content'

The error i get is:

LogicException: Route pattern "/solution/{node}/{node}/{node}" cannot reference variable name "node" more than once. in Symfony\Component\Routing\RouteCompiler::compilePattern() (line 106 of /Users/brianwilliams/Sites/MAMP/drupal8/core/vendor/symfony/routing/Symfony/Component/Routing/RouteCompiler.php).

but if i change it to use names other than node, I don't get the autoloading.

Anybody know how I am able to handle this?

You can specify the upcast type for parameters manually:

wlh_decision.solution:
  path: '/solution/{solution_node}/{species_node}/{problem_node}'
  defaults:
    _content: '\Drupal\wlh_decision\Controller\SolutionController::displaySolution'
    _title: 'Solution:'
    _title_callback: '\Drupal\wlh_decision\Controller\SolutionController::solutionTitle'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      solution_node:
        type: entity:node
      species_node:
        type: entity:node
      problem_node:
        type: entity:node

See Using parameters in routes for a slightly more in-depth explanation.


Re-creating Blocks Page for Content Authoring? I'm using Drupal 7.14, and the biggest complaint I get from people new to Drupal is visualizing where the content goes once its created.

It got me thinking of some clever/native ways to do this with the base installation. I looked into the Overlay module that the administrators have access to, then Blocks page, then Context page, and none seem to provide an easy to use interface for doing what I want. I remember the Themer module in Drupal 6 highlighted the regions in the Blocks page when you're moving components around, and my question begs whether or not this can easily be re-created somehow?

Now I'm familiar that Drupal 8 + Sparks helps with content authoring a bit, I've seen the demo's where users can edit content on the page/layout, but it still doesn't allow for adding new ccks, nodes to a specific region on a page.

I'm not sure this is an appropriate D.SE question, but has anyone heard of a module, or can think of a way to provide a GUI for users to attach their newly created content to the specific region in a theme, most preferably when they are creating the content?

The nodeblock and node-level-blocks modules may be a good starting point.


Contextual Filters with multiple arguments Why isn't this view filtering correctly? I have four contextual filters applied to one view:

http://i.imgur.com/3wN6Q.png

The view is filtering a list of projects by four properties, Region, Client, Type, and State.  When the view-page is loaded, all 4 arguments will be supplied.  The problem I'm having is:

The first two arguments, Region and State, filter correctly.  The last two: Type and State do not affect the filter.

http://i.imgur.com/9fVfG.png

The Type field isn't being factored into the query at all. You can see content with both Roadway and Airport values for the type field show up, but none for Asian or Military which are correctly filtered out values for the first two arguments (Region and Client).

I have tried remaking the filters, re-arranging the filters to make type first, re-entering some of the test content to make sure it wasn't corrupted.. no luck yet.

Okay- I figured out what was going on.  I'm going to answer my own question in case anyone runs into the same problem I had.

Previously I had specified some PHP Validation code to the Type and State filters.  Thinking they might be causing the problem I turned off the validation for both of them, but the problem persisted and that's why I posted my question above.  To solve this you need to overwrite the previous validation you set by setting it to something like Basic validation, thus clearing out the old code.  Now it works like it should but it seems like there is a bug in Views though that doesn't properly unset validation code.  Good luck!


How can create custom twig template for particular page I want to create custom template for particular pages. Single template for multiple page in drupal 8.

Twig Debugging
It’s great that we have the ability to override our template files,
but we are still left with the question of how we are to know which
template file needs to be overridden in any particular case. After
all, template files are nested one inside the other—which one contains
the markup that we want to change?
This brings us to the killer feature of Drupal 8 theming—Twig
debugging. Getting started is very easy. Inside of the sites/default
folder is a file named service.yml. Inside that file you will find a
setting for Twig debug. This setting will be set to false by default.
Simply change it to true as shown in the image below:

As usual, clear your cache after making this change. When we return to
our page and inspect the markup we will find debugging information
added in the form of code comments. Here’s an example of what our home
page markup will look like when inspected in DevTools:

You can see the debug info provides the path to the new template file
we have created. This information is repeated for other template files
found on the page, providing a fast and easy way of finding the file
you need to override or edit.
Important: Do not edit template files in core! Copy the file to your
theme and edit that version instead.
Also included are file name suggestions for overriding the currently
active templates. If you’ve ever had to track down the correct
template file to override in Drupal 7, then you know what a huge
improvement this is.
Author: John Hannah
Source and more great twig info: Drupal 8 Theming Fundamentals, Part 2

Note: In the 2nd pic, the x shows you the current twig template that is being used. In this example it's page--front.html.twig
To answer your Q, enable twig debug and go to your page and with your browser inspect element. The debug will suggest you all the template names you can use for that page.
PS: Don't forget to turn off twig debug before your site goes live.


My website's http header has weird information So I have a Drupal website. Today I checked the http headers on its homepage and found the following value:

EXPIRES Sun, 19 Nov 1978 05:00:00 GMT

I did some google research and found it's the Drupal's founder's date or something. How does it effect my site if any and how do I change this or remove it if needed? Does it effect SEO ranking as well?

Thanks!

It means you have no additional caching mechanism and the default Drupal caching will be used, several of my sites also return this header without any problem.

On other sites I use different mechanisms to control the caches, Memcache or Redis in addition with Authcache gives you quite a lot of additional control over the caches, but you'll need access to additional resources on the server.

Another aspect I've heard about is Varnish but I have no knowledge of using this myself.


problem with .htaccess file I am getting the following error after uploading files in server:

  The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.

For development purposes, I am using the following server URL: http://dev.example.mhd.co.us.

I am not able to access site when it has its .htaccess file; when I remove the .htacess file, it works fine. I am using the default file that comes with Drupal. I need to enable the clean URLs on the site.; mod_rewrite is enabled.

Is there anything else I need to configure?
Do you have any idea about why I have problems?

That usually means something in your .htaccess is causing Apache to fail. Could for example be a missing module or a configuration that denies access to something.

Try to look at the error log of the Apache server, if you have access to it. If not (even many shared hosting sites allow access to those files for your virtual host), you could ask your hosting provider support.

It is only possible to provide a more detailed solution once you post the actual error from the error log.


How do I use a different node template on taxonomy term node listing pages? For a node listing on a taxonomy term page, like:

  taxonomy/term/4

It's currently using the node template I set up just for when you are looking at a node:

  node--spot.tpl.php

I added this code to hook_preprocess_node:

if(arg(0) == 'taxonomy') {
  array_push($vars['theme_hook_suggestions'], 'node_taxonomy');
}

The node template file name I want to use is:

  node-taxonomy.tpl.php

I confirmed the hook is running but it's still using:

  node--spot.tpl.php

What am I doing wrong?

Update 1: According to the source code theme_hook_suggestions are listed in reverse priority order, so I changed array_unshift to array_push.

Update 2: I am correctly seeing in Devel themer that my template should be used first, even when it isn't:

  node_taxonomy < node_14 < node_spot < sites/all/themes/hotness/templates/node--spot.tpl.php

This answer had two parts:

As detailed in my Update #1, you have to put your suggestion last in the theme_hook_suggestions array, as last is highest priority.
Your template files must be named with two dashes, not one.

File system:

  node--taxonomy.tpl.php

As added to theme_hook_suggestions array:

  node__taxonomy


How do I get a data value after all AJAX calls are complete? I'm modifying the content of the modal window that pops up when using Linkit module in a WYSIWYG.

This modal uses AJAX so I have to use Drupal.behaviors for the first time.  My code is structured basically like this:

(function ($) {
  Drupal.behaviors.mymoduleLinkit = {
    attach: function (context, settings) {
      $('#linkit-dashbaord-ajax-wrapper').once('linkitSelects', function() {
        //do cool stuff
      });
    }
  }
})(jQuery)

Now, I need to get the existing value of an input box here, so I simply do this:

var $existingData = $('.form-item-linkit-rel input').val();

Then try to return that value, but it's always undefined. I think it's because this page seems to do a few AJAX calls in a row and I am trying to get the value before it is actually loaded into that field and available.

To ensure that waiting until AJAX is loaded is actually the problem I wrapped my code in a timeout() in order to wait for the loading to finish.  This isn't a good solution, but it confirms everything is working once things are loaded.  It looked like this:

   //wait so data is loaded via ajax
  setTimeout(function() {
    //set our select list to any pre-existing values
    var existingData = $('.form-item-linkit-rel input').val();
    if(existingData != ""){
      var $parts = existingData.split('_');
      $('.form-item-linkit-rel .size-select').val($parts[0]);
      $('.form-item-linkit-rel .type-select').val($parts[1]);
    };
  }, 500);

So the question is:  Instead of using a timeout, how can I fire this code only after the initial ajax calls are done?

You can view the full code here including the timeout stuff but please don't get distracted by all the other stuff going on (or my poor coding)...Everything else in here works and I'm really just concerned with getting the data in the question above.

Seems that you are building the elements of the form some parts using ajax and some parts using what you show on JsFiddle.

To run commands after success of an Ajax callback you could use he Ajax framework and Ajax framework commands API documentation. Here is a brief example. You will the hook_form_alter to alter the linkit_dashboard_form and add the commands. This alternative is more accurate to execute the commands after a specific ajax call but would require many changes adding hooks and custom functions.

Another alternative is to use .ajaxComplete() and check if the ajax call retrieves the linkit form elements. Example:

$(document).ajaxComplete(function(event,request, setting) {
 // Add same check you use on your setTimeout to make sure that "form-item-linkit-rel" input exists.
 // You could also use some of the values of the "setting" param of ajaxComplete() function to use additional checks.
});

Note: In case that the problem is caused by something declared inside of  Drupal.behaviors.mymoduleLinkit, try to debug your Js code with Chrome/Firefox DevTools. Add some breakpoints to find out what is causing the issue.


Custom Module: db_select title AND body? I'm a little confused by how the node data is stored in the database.  It seems like the title is stored in the db "node," while the body is stashed field_data_body, and custom fields are placed elsewhere.

I have create a custom module that pulls certain pieces of content, but I need to match up the title with the body.  I've been successful pulling my list of titles:

    function foo() {
      $query = db_select('node', 'n')
       ->fields('n', array('type','title', 'nid'))
       ->condition('type', 'fooBar')
       ->condition('status',1)
       ->execute();
          return $query;
      }
      $result=foo();
        foreach ($result as $node) {
         $id = $node->nid;
        }

How can I match each of these with their bodies?

Thanks!
-JB

If you want directly include the body within your result set, you can do a join on the field_data_body table.

$query = db_select('node', 'n');

$query->leftJoin('field_data_body', 'd', '(d.entity_id = n.nid AND d.entity_type = :node)', array(':node' => 'node'));

$query
    ->fields('n', array('type', 'title', 'nid'))
    ->fields('d', array('body_value', 'body_summary', 'body_format'))
    ->condition('type', 'fooBar')
    ->condition('status', 1)
    ->execute();


Node translation syncing problem with entity references I have a content type with multilingual support (node translation). This content type also has an entity reference (module: entityreference) field.

My content is:

/node/1 English story 1
/node/2 French  story 1 (translation of #1)
/node/3 English story 2 with reference to #1
/node/4 French  story 2 (translation of #3) **entityreference problem here**

I've configured the reference to be synchronized. The problem is that whenever I translate or edit a node, it'll try to sync the reference to other translations.

So I'll always end up with:

#3 -> #1 (correct)
#4 -> #1 (wrong)

or:

#3 -> #2 (wrong)
#4 -> #2 (correct)

I can solve this by disabling syncing on the reference field but then I will have to be maintaining the references for all translations manually which is a problem in a website with many translations.

Had the same problem, wrote this little workaround:

function YOURMODULE_i18n_sync_translation($entity_type, $translation, $translation_language, $source, $source_language, $field_names) {
  foreach ($field_names as $field_name) {
    $info = field_info_field($field_name);
    if ($info['type'] == 'entityreference') {
      $items = field_get_items($entity_type, $source, $field_name);
      foreach ($items as $delta => $item) {
        $translations = translation_node_get_translations($item['target_id']);
        if (isset($translations[$translation_language])) {
          list($id, $vid, $bundle) = entity_extract_ids($entity_type, (object) $translations[$translation_language]);
          $translation->{$field_name}['und'][$delta]['target_id'] = $id;
        }
      }
    }
  }


Template suggestions for page on specific node id I created 2 nodes of the content type page for which i want to create a custom template file.
In the theme_hook_suggestions array there is an element with 'node__821' so i created the file node--821.tpl.php but it doesn't work.

I also tried page--node--821.tpl.php, this works in that it uses the file but this replaces the page.tpl.php and thats not what i need.

According to http://drupal.org/node/1089656 my filenames should work, but since they don't anyone an idea why? Could it have something to do with the page content type?

You need to do two things before this will work:

Make sure you have a copy of the original node.tpl.php file in your theme folder (the overridden template file will not be picked up otherwise).
Clear Drupal's cache

Other than that everything you're doing is perfect so that should fix the problem.


How do I catch 502 exceptions? While running the batch process, it takes more than 5 hours to complete; before that, it returns a 502 error. How do I handle it?

HTTP 502 Bad Gateway is, as its name says, something that happened on your gateway, not on your server. Since the error is between you and your server, Drupal can't really know it happened unless, of course, you are talking about a job that connects to a remote server and the error happens between your site and that remote server. If so, you can either ask admins to fix gateways, or file a bugreports: one to service provider, and the other to the author of the module you are using.


Recover the field from one Drupal page to another What I want to do is recovering the avatar picture the Avatar Selection module generates, and present it elsewhere in my Drupal installation, specifically in pages where it is not appearing.

I have been referred to the dsm() function, but not being a programmer, I am utterly lost with this. I haven't got a clue.
I know that I need to know the field's name, where the picture is showing and then I can render it, but while I know all this, I have no clue as how to do it or if this is all I need.

I haven't found (or haven't understood) any dsm() tutorials out there.

First off, dsm().   You have to install a devel module.  In you code if you do dsm($user) then it would show you a nice user interface of the $user object/array

The location to the user picture (or avatar) is in your $user->picture object.  If $user array is not available, then you can do global $user;


On click of checkbox send email to selected recipients using module

 <?php
 if( isset($_POST['persons_names_Str']) && !empty($_POST['persons_names_Str']) )
  {
 $list = $_POST['persons_names_Str'];
 //print_r($list);
 //$to_arr = explode(",", $list);
 //$to = array_filter($to_arr);
 //echo $to;
 //print_r($to);
 $to = $list;
 $subject = "Test Subject";
 $body = "This is temporary email from Lawandmoney. ";
 $headers = "From: no-reply@lawandmoney.com\r\n" .
 "X-Mailer: php";

 $to =  "no-reply@lawandmoney.com";
 $headerFields = array('BCC: '.$list.', "From: no-reply@lawandmoney.com" ."X-Mailer:    php"');
 if (mail($to, $subject, $body, implode("\r\n", $headerFields))) {
 //if (mail($to, $subject, $body, $headers)) {
  echo("
Message sent successfully! our lawyer will contact you as soon as   possible
");
  } else {
  echo("
Message delivery failed...
");
  }
  exit();
  }

  ?>

  <?php
   $sql = "SELECT * FROM lawyer_details WHERE city LIKE :city AND speciality LIKE   :speciality";
   $result = db_query($sql,array(':city' => '%'.  db_like($_SESSION['selected_county']).'%' , ':speciality' =>  '%'.db_like($_SESSION['lawarea']).'%'));

 $rows_count=$result->rowCount();

 if($result && $rows_count>0)
 {
 while($row = $result->fetchAssoc())
 {
  ?>

<input type="checkbox" name="checkbox[]" id="email1" value=<?php echo  $row['email_id'];?> /><?php echo  $row['first_name'].' '.$row['middle_name'].' '.$row['last_name'];?>

<?php echo $row['street_address'];?>

 <?php

  }
  }
 else
  {
 echo "No Result Found";
 }
 ?>
 Send  Email

only just add jquery file in head section.

"to" parameter in drupal_mail is a string. You can have as many receipent as you like in the the emails "to" string, provided they are separated by commas (",").
You can do like this

$to  = 'one@email.com, two@email.com, three@email.com';
drupal_mail('$module_name', $key, $to, language_default(), $params = array('username' => 'test'), $from = NULL, $send = TRUE);

You may check the documentation of drupal_mail.


How to prevent the login block to be shown twice? When I open my web without being logged in, the login block appears twice. Once in sidebar and once in header (at least I hope it is header section), as shown in this screenshot:

However, in structure/blocks I have it set in sidebar only.
Any idea how to fix this, so that the login block is only shown once?
Theme is ANDROMEDA: https://www.drupal.org/project/andromeda

Follow the steps, Using which can solve your problem.

Go to Blocks under structure admin menu.
You will find user login block in Header section.
If you have added your custom login block then there is no need to have default login widget in header. So change it to null.
If you have default login then just check to put it in appropriate block.

This are the two cases according to your question description.Answer back if not solved.

Please do mention some more description if this solution won't work.


Does drush support everything I can do with web admin interface? I have just learned about Drush. Its great command-line tool. With two words, I can update drupal code within seconds.

I want to know whether I can do everything I do with web admin interface or not?

No, you can't. That's not possible.

Every command needs to be explicitly provided to Drush. Many contrib modules now come with integrated drush commands, for example Devel generate, Features, Views, XML Sitemap and so on.

To see the list of commands that are available to you, call drush help. You can get detailed help on each command with drush help <command>.


Call Remove Button (File Upload) Programmatically using JavaScript How can I call the remove button of temporary uploaded file programmatically using JavaScript?

I want to clear the form fields when the condition changes. I've done all the form fields exept the temporary uploaded file.

Can I call the remove function? If yes, Where is it?

Easiest way to do is what @Molo mentioned in his comment.

$('#element_id').trigger("click"); OR $('.element_class').trigger("click");
$('#element_id').trigger("mousedown"); OR $('.element_class').trigger("mousedown");

Or you could, reset the .html() of the upload element

$('#'+id).html($('#'+id).html()); OR  $('.'+class).html($('.'+class).html());

JavaScript into Drupal can be done in various ways, you could reference your javaScript file in your theme's info file or you override the drupal_add_js function in template.php and add your JavaScript.

For more Information on how to put JavaScript into Drupal see this or this and these (module or module) could also be handy. This article explains how to programmatically submit a form in Drupal.

Here is a good tutorial, how to add your JavaScript to Drupal https://www.drupal.org/node/756722


How to create sticky Social Media Tabs to the right of the website? How to create sticky Social Media Tabs to the right of the website?

See the below screenshot for how it stick at the right:

Is there any Drupal module or plugin available?

Try Social media module, it will display as block and then assign it to the proper region and AFAIK no module exist as such, you need to customize through CSS.

  The social media module helps integrate your website with social media
  sites such as Twitter, Facebook and Google+. It provides an
  centralized way of managing social media profile information and
  plug-in widgets such as follow and share buttons.

if you are looking to share the posts then Share Bar is the right choice for you.

  The Drupal Sharebar module lets you easily add a "floating" social
  media submission bar on your website (like that found on Mashable)
  that includes share buttons for the most popular social media websites
  online such as Facebook, Twitter, and Google +1 Buttons.


How to make the Access by Term module respect User Role permissions first? I need Access By Term (ABT) to respect the user Role permissions before considering the term relation between the user and the node.

Scenario
The user does not have permission to edit "Basic Page" content type but he is term related to a "Basic Page" node. He should not have permission to edit this page because his Role doesnt grant it, but as he is related to this node by a term, ABT grants him "update" permission.

Any ideas? Is it possible without patching it?

You are using Access By Term. I've never used this module, but I have used Workbench Access which allows setting of an Editorial Section for content and people assigned to those sections to edit that content.

It sounds like you want a complex workflow better supported by Workbench.


Paging a view based on a grouping field? I'm upgrading a site I created 2 years ago from D6 to D7. In that site, I have a view of items that are grouped according to year, so that the items for each year show up on a separate page -- you pass the view the year, and it displays the appropriate nodes for that year.  I need to have "previous year" and "next year" links, which would link to pages that show the nodes for the previous or next years, as appropriate.

I did this in the old (D6) site by allowing the header to display PHP code (using the PHP filter), doing math on the passed-in "year" parameter, and writing out the link to the next and previous years as raw HTML.  This feels wrong - very un-Drupal — but I can't figure out how to get views to do it more natively.

My feeling is that I'd like to use something like the grouping field (from "Format/Settings") except that instead of just putting a heading between the grouped nodes (which in my case would result in a page with over a thousand nodes displayed) it would split them into pages based on that grouping field.

Any ideas?

I found some items that point to a possible answer.  There's this previous question:

Views pagination based on taxonomy terms

My years ARE also taxonomy terms, so this would work for me if the question was ever answered as asked.  While there is no actual answer, there is a pointer to this very nice Earl Miles article:

http://drupalwatchdog.com/1/1/how-to-create-new-features-in-views-3

That is VERY close to my use case, and I guess if I have to I can try to create a Views Plugin based on Earl's instructions, but I'm hoping for something simpler.  I'd rather use a plugin than write one!

(In the article, Earl says the code for the plugin could be found at http://drupal.org/project/views_plugin_examples, but when I go to that project it appears to be empty.)

In any case, this looks like a "solved problem" -- but I can't find the solution!  Any pointers, before I re-invent the wheel?

Download the Date module at and be sure to active its Date Views submodule. That will add a Page by date option to the pagers listed in your Views config page. Here is a nice writeup by Richard Schulte on how to configure the date pager.


Get image file values in $form_state in media entity form I am trying to get the values from an uploaded image inside a media entity during form submit.
Where my approach doesn't work:

When first uploading an image in the media_image_add_form form.
When editing an existing media entity and removing, then uploading a new image and trying to save.

My validation only works when editing and submitting an existing media entity (without changing the uploaded image file).
Here is my entire code for brevity, though it may be long, MYMODULE.module:
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'media_image_add_form' || $form_id == 'media_image_edit_form') {

    if ($form_state->getFormObject()->getEntity()->get("field_media_image")->entity) {

      $form['#validate'][] = '_MYMODULE_validate';
    }
  }
}

/**
 * Validates submission values in the FORM_ID() form.
 */
function _MYMODULE_validate(array &$form, FormStateInterface $form_state) {

  // $imageEntity = File::load($form_state->getValues()['field_media_image'][0]['fids'][0]); // Tried File::load here as well.
  $imageField = $form_state->getFormObject()->getEntity()->get("field_media_image");
  $imageEntity = $imageField->entity;
  $imageFileSize = $imageEntity->getSize();
  $imageFileMime = $imageEntity->getMimeType();
  $imageFileName = $imageEntity->getFilename();
  $isIssue = FALSE;
  $showConditionalMessage = FALSE;
  $ciuMessage = "";
  $ignoreWarnings = $form_state->getValues()['field_ignore_warnings']['value']; // Field set on media image entity type.

  // Conditional issue.
  if ($ignoreWarnings === 0 && $imageFileMime === "image/jpeg" && $imageFileSize / 1000 > 150) {
    $isIssue = TRUE;
    $showConditionalMessage = TRUE;
    $ciuMessage .= "
Conditional: This JPG file size is larger than 150kb, have you optimized this JPG image?
";
  }

  // Conditional issue.
  if ($ignoreWarnings === 0 && $imageFileMime === "image/png" && $imageFileSize / 1000 > 200) {
    $isIssue = TRUE;
    $showConditionalMessage = TRUE;
    $ciuMessage .= "
Conditional: This PNG file size is larger than 200kb, have you optimized this PNG image?
";
  }

  // Non-conditional issue.
  if (strpos($imageFileName, ' ') !== false) {
    $isIssue = TRUE;
    $ciuMessage .= "
Filenames cannot contain spaces.
";
  }

  // Non-conditional issue.
  if (strtolower($imageFileName) !== $imageFileName) {
    $isIssue = TRUE;
    $ciuMessage .= "
Filenames need to be in all lowercase.
";
  }

  if ($isIssue) {
    if ($showConditionalMessage) {
      $ciuMessage .= 'To ignore conditional errors, check the "Ignore conditional errors" checkbox below.';
    }
    $form_state->setErrorByName('title', new FormattableMarkup($ciuMessage, []));
  }
}

One caveat for using hook_form_alter() is that some of the errors are conditional, and I would like to provide a field on the media entity type to allow ignoring some of the errors.
How can I get the uploaded file/values in $form_state when adding an image to a new media entity, or adding a new image to an existing media entity?

Normally you use a ConstraintValidator for validating entities. In this case core invokes a hook so that you can add your own error messages to the existing file validation process:
function hook_file_validate(Drupal\file\FileInterface $file) {
  $errors = [];

  if (!$file->getFilename()) {
    $errors[] = t("The file's name is empty. Please give a name to the file.");
  }
  if (strlen($file->getFilename()) > 255) {
    $errors[] = t("The file's name exceeds the 255 characters limit. Please rename the file and try again.");
  }

  return $errors;
}

About the caveat for using form alter. You can add custom #upload_validatorsto the image widget. Add settings if necessary:
$element['#upload_validators']['my_custom_file_validator'] = [$my_setting];


Adding node edit links to a views block display? I have a View with a Block display which shows 4 nodes of 1 type. I'd like to add node/xx/edit links to each node on the block. I've searched Google only to get confused more. Which hook to use? views_pre_execute, views_pre_render, views_pre_view .... And once you get the right hook, how do you actually add those links? Obviously I'd like to check the current user's node_access permissions too before adding those links.

This is Views 2 with Drupal 6.

There is a field called Node :Edit link which can be added to the fields and it will give you the edit link. This also respects the permissions that is it would only be shown to those who have permission to edit a post.


Print object in template_preprocess_page In template_preprocess_page() in my MYTHEME.theme file, I'm trying to validate if node has specific value.
When I dpm($variables) I get:

Array
(
    [node] => stdClass Object
    (
        [__CLASS__] => Drupal\node\Entity\Node
        [in_preview] =>
        [values] => Array
        (
            [vid] => Array
                (
                    [x-default] => 2
                )
...
    [page] => Array
    (
...

When I dpm($variables['node']) I get:

stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
...

When I dpm($variables['node']->values) I get empty result.

Why so?

you can use :

dpm($variables['node']->toArray());


Panels on the front page get invalid $user variable I have a Drupal 7 wite where the front page is a Panel. In one of its tiles I have a custom PHP code that prints out the value of `$user->name'. Now the problem is that it usually prints out a different user's name.

Cacheing and memcache is now switched off. Do you have any idea what might cause this problem..?

Ok, got is. Panels have its own caching that was switched on.


Using a drush alias with Elysia Cron - alias permission missing Problem

I'm trying to run Elysia Cron with Drush. When I use the command drush elysia-cron in the correct folder it runs.

However when I use an alias it doesn't work: drush @main elysia-cron.

The alias works correctly. And after a bit of digging I found the following lines in debug:

"error":"DRUPAL_USER_LOGIN_FAILED"},
{"type":"error","message":"The drush command 'elysia-cron' could not be executed.",
"timestamp":1385993042.4437,"memory":60455120,"error":"DRUSH_COMMAND_NOT_EXECUTABLE"}]

Apparently when I use an alias it loses login permission.

The only user related function for Drush I could find is remote user, but I think that's only for running drush remotely through SSH. How can I give my alias login permission?

You could try drush @main --user=1 elysia-cron to force the active user to be the site admin when elysia-cron runs; however, all of the cron methods should be API calls, and therefore should not care who the active user is.  Note also that the error message that you quote above simply means that part of the Drupal bootstrap is failing for you; this is not a permissions issue (because Drush does not need permission to log on as a user -- it just does it), but is indicative of some other problem.

Run drush status with your cwd set to your site, and run it again vi drush @main status from a different working directory, and compare the output, esp. vis-a-vis the Site URI line.  Also run in --debug mode both times, and look for any other differences in the output.  If you have set root and uri in your alias, it pretty much should run the same both ways.


Export Content from Drupal to WordPress We're not Drupal developers and need to move the content from a Drupal site to a WordPress site.

We've already tried a plugin to help with this but it only imports a limited amount of content.

We then investigated it a little further and managed to find the Views module to export the content.

It is possible to duplicate Views which we will then rename Export To WordPress but it is not possible to convert those Views from the existing Table Format to RSS which we need to be able to import back into WordPress.

If there is a better way to do this, we would appreciate the help.

You may want to try the Forena module (disclosure: I'm a co-maintainer of it) to create a "report" that includes the data that you're interested in. As part of the report design, indicate which export formats you want to allow for exporting the data included in it. Typical export formats that are supported are CSV, XML, HTML, XLS, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "content to be exported". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.


Webform for Contact Information What html code can I use to create a form for readers to submit their contact information (e.g., phone number, email address, etc.) and type a question?

If the Contact module doesn't suit your needs (comes with Drupal core and can be enabled on the Modules page), then your best option is to use the Webform module.


How do you properly render the body when pulling it from the database using db_select? I have a db_select() that returns the *body_value* and *body_format* from the table field_data_body...how to I properly render that in Drupal?

I think the 'proper' way to do this is not to get the data directly from the database at all, but to use the built-in field API:

// Get an entity (node in this case).
$node = node_load(1);

// Get the view for the body field
$view = field_view_field('node', $node, 'body');

Doing it this way you won't have to bother negotiating languages or anything that, and the field will be outputted exactly as it is when it's attached to a node display.

If you do want to do it manually, though, you need to use the check_markup() function:

$text = check_markup($body_value, $body_format);

It might be worth taking note of the comments in that function, you need to be careful about accepting an arbitrary filter format without validating it:

  Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.


How to make a style plugin available only for certain types of panes? I'm trying to simplify the admin UX on a site with a few different custom style plugins. I have plugins A, B, C, and D.

I want plugins A and B only to be able to be applied to menu block panes.

I want plugin C only to be able to be applied to a minipanel when the minipanel is placed via something like Panelizer.

I see that I can easily hook_form_alter() the #options in the form but I don't seem to be able to find the kind of context information that I need to know which ones to hide.

How can I selectively hide style plugin options for irrelevant elements?

I figured out two ways to do this.

First way

It requires that any style plugins you want to filter be

provided by the module in which you're doing the filtering (unless you want to hand-code in a list of modules or something), and
named such that the machine name includes the name(s) of the content type(s) of the panes on which it should be able to be selected.

Inside a hook_form_FORM_ID_alter():

// Only show style plugins relevant to the type of pane we have.
$type = $form_state['pane']->type;
$this_module = basename(__FILE__, '.module');

foreach ($form['style']['#options'] as $key => $style) {
  $style_info = panels_get_style($key);
  $module = $style_info['module'];
  // If the style plugin was defined by our module and it does not have the
  // current pane's type in the name, don't make it an option.
  if (($module == $this_module) && (strpos($key, $type) === FALSE)) {
    unset($form['style']['#options'][$key]);
  }
}

Second Way

After doing it the first way, I wanted to make it more robust (not rely on naming conventions) so I submitted a feature request to Panels and attached some patches. Issue here: https://www.drupal.org/node/2320045

This way allows you to just add something like 'content type' => array('foo', 'bar', 'baz'), (Where foo, bar, and baz are the machine names of Panels content types) to the $plugin declaration, along with the title and description and all that. If you have plugins that don't have that, they won't break, they'll just continue to appear as options for every content type. If you do specify some types, it will only appear as an option on panels of those types.


Enable a flag automatically for specific users using Rules I have a content type called testimonials, and in that I have a user reference field with multiple selection option.
I have a flag called 'Request to review' enabled on nodes of 'testimonials' content type.
I wrote a rule for sending mail to the author of the node if any user clicked on that flag.

What I need to do here is, I want to enable that flag automatically when a new node is saved only for the users who are selected in the form field user reference. And for remaining users the flag should not be enabled automatically i.e., they have to enable it manually by clicking the flag link.

Thanks

I achieved it by writing a new rule, in that i wrote a loop for getting all the selected users.

thanks


How to add a condition (rule) to skip questions when using the Quiz module? I'm using Quiz module and I have a quiz with questions 1 to 10.

I want this:

Question 1: If answer is yes jump to question 2. If answer is no jump to question 7.

How can I achieve this? Do I need to use Rules module?

To get this to work using the Rules module (which I'd also use for this), you should ALSO use the Conditional Rules module. Some more details about this module (from its project page):

  ... provides Rules plugins for conditionally altering execution flow directly inside a group of actions.

Some examples of using the Conditional Rules module:

"How to check whether one's current User Points are negative with the Rules module?" contains an example of a rule (in Rules export format) with an action that uses Conditional Rules with a typical "if"-part and "else"-part.
a screenprint of a rule with an action that uses Conditional Rules, though only with an "if"-part here, no "else":

So by using both of these modules, you could use a Rules Action to redirect (= jump) to either question 2 or question 7, based on the answer (yes or no) provided to question 1.

This would answer your question for "question 1". By creating up to 10 similar rules (1 for each question that has a similar requirement), you should have a solution for all other questions that would need it also. However, you should be able to take advantage of other facilities that the Conditional Rules module offers (by constructing complex conditions as a condition set and then use those in the condition elements). So that you include all the required logic (for all your 10 questions) in a single Rule.


How to add a country to the location module? I have a requirement to add additional countries to the location module.

I need to add England, Scotland, Wales and Northern Island.

I suppose they could be provinces, but I can't figure out how to do that either.

Many thanks for any help :)

PS. I would be using the county codes for css so country would be better.

So maybe my question wasn't worded in the best way, but I have found the answer.

All countries in Drupal (at least in 7) are taken from the /includes/iso.inc file. This includes Location and Address Field.

You can add countries to this list via drupal_alter

An example:

<?php
function hook_countries_alter(&$countries) {
  // Elbonia is now independent, so add it to the country list.
  $countries['EB'] = 'Elbonia';
}
?>

Putting this in a custom module will enable you to add countries as you require. You must use a 2 letter iso code!


How to turn a menu tree into an associative array? I've dig into Drupal menu core to find out a way to build an associative array from a menu tree(eg,the account menu) so that I can output the data as json format. But it seems not possible to do this with Drupal 8. The info I need from a menu tree include title, description, url, and I also need to know whether it has sub menu and if it's enabled. All this can be easily achieved using menu_build_tree() function in Drupal 7. Please understand I tried the so-called Drupal 8 equivalent of menu_build_tree() (\Drupal::menuTree();) but it just gives me large object using which I don't know how to extract the data I need.

You can load up the menu tree with MenuLinkTree::load, which will give you an array of menu links to work with. From there it's just a matter of looping through and getting what you need, e.g.

$tree = \Drupal::menuTree()->load('main', new \Drupal\Core\Menu\MenuTreeParameters());
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url_obj = $item->link->getUrlObject();
  $has_children = $item->hasChildren;
  // etc...
}

The link is a MenuLinkInterface, each item itself is a MenuLinkTreeElement.

It would be preferable to inject the menu.link_tree service if possible, rather than getting it from \Drupal.


Adjust a view so there is one image of size normal and other images are thumbnails I have created a gallery for every user. I would now like to alter the view so that one of the images is a medium size and the other images are thumb nail size. I know you can adjust the layout in a view but I am not sure how to change the size of one image and keep the others as the default thumbnail.

Check out the View Nodes Split module.

This module allows site administrators or builders to have a different view mode for the first nodes of a view result.
If you ever had (or currently have) this scenario: you have a view of nodes but you want that the first node (or first X nodes) to have a different view mode, then this module is for you. The module can split the results from a view into 2 lists. It actually does not make 2 separate lists, it just uses a a different view mode to render the first X nodes from a view.

You can also use a view attachment to display a node and attach more nodes to it. Make sure you offset your attached view by 1.


How to implement question/answer functionality with following feature? I would like to create a question/answer website using Drupal7, where a user can ask a question and other users can answer that question. This one is very simple to implement in Drupal 7. But what additional feature i want is when a user asks a question he will set the expiration period also by choosing from a select list (5Days, 7Days and 15Days etc). Within this duration the STATUS of the question should be shown as "OPEN for Answer". After this period, the STATUS should be changed to "Finalizing Best Answer" automatically and now no new answer can be submitted by any user and after the best answer is selected by the asker, the STATUS should change to "CLOSED" automatically. But the asker of the question can change this STATUS at any time from "OPEN" to "CLOSED" even befor the expiry set by himself, but he can not change any other field of the question form once a question is published. How should i implement this type of functionality in my content type? Please provide your views for this type of functionality.
Thanks!!

Well, while the Answers module does not support this entirely, it does provide some helpful functionality. (FWIW, this has been an open feature request for some time. I haven't gotten around to it ... but if you end up implementing it, I would love to integrate it.).

In particular, the Answers module allows you to programmatically "lock" questions, meaning additional answers are not allowed. You can also extend the module with the Best Answer module (which, naturally enough, enables question authors to select a Best Answer). The Best Answer module already provides an administrative setting which, if set, means that questions are automatically locked after the question author selects a Best Answer.


How to get the language code when a language name is given? We are creating nodes programmatically on submitting a form. The language of a node is an input value in the form.
How can I get the langcode, when I have the Language name?

For example, user may type English. So i should convert it to "en"

If there an in-built function for that?

You can do it with this code.

// Language to search.
$find = 'French';

// Getting all the available languages.
$languages = \Drupal::service('language_manager')->getStandardLanguageList();

$key = key(array_filter($languages, function ($array) use ($find) {
  if (array_search($find, $array) === FALSE) {
    return FALSE;
  }
  return TRUE;
}));

// If you have the devel module installed you can use the dpm function.
dpm($key);


Show video thumbnail and download link in view I want to show a view page such that a grid of video thumbnails with download button below it will be displayed. As shown below:

I tried video module to display video. But it fails to give file path. Because of which I'm not able to achieve it.

Then I tried with normal file field. But I'm not able to show the video using file field.

I rewrote this file field as:

and then in Custom Text field I wrote below code.

{% if field_file_vid %}

{{ field_file_vid }}

Download

{% endif %}

In this case only download link is working not the video.

How to achieve this requirement?

Add field_file_vid again, check mark exclude from display and this time don't use URL to File as formatter, use a different formatter that renders the video.

Rearrange the fields

so that this new field is above the original field.

Now in your original field's rewrite results, use this as your 3rd line:

{{ field_file_vid_1 }}


Canonical link on node's print version I'm using Metatag and Printer, email and PDF versions modules, and I want to have the canonical link on the print version of the nodes too, but for some reason they're only showing on the regular version.

I'm not sure if the Print module is removing it. Even if I manually add the canonical link, it shows duplicated on the regular version but not in the print version.

Any idea about what's going on?

I solved the issue by adding a canonical link via hook_html_head_alter().


Permissions filter like module filter The module filter makes managing modules from the UI very easy to manage. Live update with the search query and grouping. I've been looking for a similar module for the more messy permissions table. A similar module would definitely make it easier to manage that monstrous table :D

Does anybody know if a module exists for this?

I did try searching but I might not have used the right terms just like when I searched for user spoof and it resulted to a module named Masquerade.

The Fast Permissions Administration module is the closest equivalent that I've found

  This module is here to alleviate frustration when trying to manage permissions in Drupal. By providing a better permissions interface hopefully a few innocent keyboards and mice can be saved.

You get a UI like:


How to update SOLR document? This question is related to https://drupal.stackexchange.com/questions/193603/solr-views-flag-newly-flagged-users-do-not-appear-in-search-results

Because previous question can be difficult to understand I'm trying to simplify things.

If I understand SOLR - Drupal integration well, every entity is represents as Document in SOLR.

How to invoke update of document for specified entity?

List of modules that I'm using for search page (a View)

dependencies[] = date_facets
dependencies[] = facetapi
dependencies[] = facetapi_bonus
dependencies[] = search_api
dependencies[] = search_api_facetapi
dependencies[] = search_api_location_views
dependencies[] = search_api_solr

I need to update SOLR document when user flag another user (Flag module).

If you're writing code:

search_api_track_item_change('entity_type', array($entity_id));

That will mark an entity as 'dirty', and it'll be (re-)indexed on the next run.

If you're not writing code, install the rules module, add a rule with an event of "A flag type has been flagged...", and an action of type "Index an entity", with the relevant parameters.


Views using taxonomy I have a simple Drupal 6 website with a content type 'Software' this has various CCK fields regarding evaluation of the software. The software has been evaluated by a speech therapist and the website is used by people suffering from Aphasia to help them pick the software that is right for them.

One of the pages on the site has a comparison table built using views, selecting nodes with their CCK fields.
http://www.aphasiasoftwarefinder.org/comparison-table

I appologise for the amature look of this site, I knew very little about theming and am still learning.

I am now re building this site in Drupal 7 and it has become much more complex with regard to the various evaluation criterion and is also including Apps and other software that may be useful to people. I decided to use Taxonomy instead of CCK fields as there about about 7 areas or evaluation (Taxonomy volcabulary) each with its own list of terms.

Everything is working well except when I come to creating a comparison table.
I want to be able to use the Taxonomy terms that are the same as the CCK evaluation fields from the Drupal 6 site but I am strugling as to how I can achieve this.
So I have a Taxonomy Volcabulary 'Evaluation' with a list of 8 or so terms, I want to be able to separate those terms out as columns along the top of the view and list the nodes down the side, then populate the colunms with a tick if they have that taxonomy term.

If someone could point me in the direction of any tutorials that may help towards this goal or come up with any ideas on how this could be done???

Many thanks
Julie

You can use the Taxonomy : All Terms to display the terms each node has associated with a single vocabulary. You would have to spend some time on styling them properly.


Add node with no title I would like to let users create elements with no title.

In this particulary case, I would like them to enter a registration number, as you can imagine there's no need for a title right here.

How can I remove it from the creation page (node/add/node-type),  so I can only see the fields I want (not the title)?

The Automatic Node Titles module does that.


Classes in body of user profile page I have got a question. I have got drupal 7 running and in the user profile page, the body classes look like this:

<body class="html not-front logged-in one-sidebar sidebar-first page-user page-user- page-user-1">

If you notice, the second last class, 'page-user-' seems like it is missing something at the end, meaning, something is not working right. I have used theme devel and just did some mega digging around (including the user module) to see where this class is being added from, but I have had no luck.

I would basically like to change the styling of some tables in the user profile page via css and would like to identify these tables by a specific class in the body, so that it only applies in this user profile page. If that class was perhaps displaying correctly, I could identify the tables with that, and not have to modify the user-profile.tpl.php page to add a new class. So, I would appreciate it if anyone could tell me where these classes are being added, and what that missing variable could possibly be. Thanks.

Drupal add arguments to page classes to make it possible to theme the page depending on the current page type (e.g. node, admin, user, etc.) as well as more specific data like node-12 or node-edit.


Drupal Commerce Adding fields to Add To Cart page I need some suggestion to add some fields to the "Add to cart" page.

Out of many products, one of the product requires some user information to be filled before proceeding to "Add to cart" process. I am selling a product of type "Exam". Before buying Product of type "Exam" (Before adding to cart), user has to input his person details like name, address, DOB and other mandatory details without which he is not able to proceed.

Could you please guide me, how to achieve this?

Update:

Shall I use Product Attribute fields to capture user inputs over product display page? As this information is not associated with the Product, but with the order and need to be captured before Add to Cart button is clicked.

Thanks all of you for your valuable time and suggestions. More or less all suggestions 'll be required in near future. I have up-voted all of you for your help. However on other side I got the answer, what I was looking for.

  It sounds like you need the Customizable Products module.

  Once you have that module installed, you can go to Administration > Store > Configuration > Line item types. Add a custom line type and add as many custom fields there as you'd like. You'll see - the
  interface for adding fields to the custom line type is the same as
  when you create a content type, so it's easy to use.

  Then, when you've added all the customer info you need in your new line item, go ahead and modify your 'Exam' product to include
  those fields in the product display. Hit the 'Display' settings for
  the content type, and configure the settings for the 'Add to cart'
  field. Make sure you choose the correct line item for it to use and
  Save!

  Helpfull screencast could be found at http://vimeo.com/36106455


How to add more fields after submission? I was wondering how to add more fields to a form after submitting that form.
So the form should have these fields for example:

Name (textfield)
City (select list)
Find (button)

and then when user performs the submission, the result page should look like this:

Name (textfield)
City (select list)
Gender (radio buttons) <-- so they can refine the search by gender
Find (button)

How do I achieve that?

You need to add a submit handler to the button that updates some specific variable in $form_state so you can determine the "step" of the form.
Plus, a $form_state['rebuild'] = TRUE; to rebuild the form.

Assuming you are using Drupal 7, a hook_menu or hook_block_view (or any other function) is calling drupal_get_form function with "my_form" as argument.

function my_form(&$form, &$form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );
  $form['city'] = array(
    '#type' => 'select',
    '#title' => t('City'),
    '#options' => array(
      1 => t('Kandy'), 2 => t('Anuradhapura'),
    ),
  );
  if (isset($form_state['next_step']) && $form_state['next_step']) {
    $form['gender'] = array(
      '#type' => 'select',
      '#title' => t('Gender'),
      '#options' => array(
        'm' => t('Male'), 'f' => t('Female'),
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Find'),
  );
  return $form;
}

function my_form_submit($form, &$form_state) {
  $form_state['next_step'] = TRUE; // You can also change this to FALSE in validate function to prevent the gender from appearing.
  $form_state['rebuild'] = TRUE; // Don't forget this!

  // Do other stuff here.
}

Note how I conditionally added the gender form element, and how the submit handler sets that value.

When the form is loaded for the first time (with empty $form_state), the condition to add the gender element will be FALSE, so no element added.
Then, the form submit handler adds the values so in the next form rebuild, element gets included.
Tricky part is the $form_state['rebuild'] = TRUE; part.

Good luck!


Is there a module for google maps in drupal 7? On a site that I am building (using drupal 7), there is a feature that I need to include that I can't seem to find; Google maps. I am looking for two things;

1: something that will allow you to put in your home address, and it will give you directions to a preset location

2: something that will allow you to imbed a map of the surrounding area of a preset destination by stating the location in a CCK

do either of these exist? if so, where can I find them?

I need it to look like this:
where instead of an image, the map is actually an embedded google map.

There is the GMap Module module, but there is just a development snapshot, for Drupal 7.


add a search field which search for values of specific field in a content type I've created a content type "Submission", which have many fields. One of them is "ID".

Now, I need a search box (apart from regular search box). It should be searched with ID value, it should display search result of content which have this ID value.

Any suggestions please.

You can create a separate Search Page using Views: Here is a tutorial (http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7)

Views:

  You like the default front page view, but you find you want to sort it differently.
  You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain type.
      You like the idea of the 'article' module, but it doesn't display articles the way you like.
      You want a way to display a block with the 5 most recent posts of some particular type.
      You want to provide unread forum posts.
      You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of
  Month, YYYY (X) where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts for
  that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


Showing unpublished content to the anonymous creator I am working on a Drupal 7 module called Anonymous Publishing.  In brief: It lets the anonymous user create posts.

The anonymous user create contents using the standard content creation node_form.  When the user press save, Drupal automatically creates and loads the node.  However, since the node is unpublished at this point, the user just gets an access denied message.  I want to avoid this, and instead show the user the node just created.  I've so far only managed to do this with this rather nasty kludge in a hook_node_grants():

$result = db_query("SELECT created FROM {node}
   WHERE nid = :nid", array(':nid' => $nid))->fetchField();
$delta = time() - $result;
if ((0 == $account->uid) && ($delta < 20)) {
  $grants['anonymous_publishing'] = array(1);
}
return $grants;

What the above code does is this: It checks the age of the node, and if it was created less than 20 seconds ago, it grants the anonymous user the right to view it.

While this works (sort of) it is ugly and it may even expose the content to someone else if there is another anonymous user around that requests the content within the same 20 second window.

Any suggestions for a better solution?

You can (relatively) safely store per-user data for anonymous users in $_SESSION. So if you intercept the node page view callback and add some extra code in there for the case in question (falling back to the core function), you should be able to achieve what you are after.

To elaborate: when you save the node in question, save its ID and an expiry timestamp in an array in the session, via a hook_node_insert. In the new callback check if that entry exists and has not expired. If present, fetch the node and display it. Otherwise call the regular node view callback.


Conditional display of a Views field The issue at hand is to change the display of one of a View's fields, based on a condition in another field of the same View. The field to be affected is the display of checkboxes associated with Flag Lists/List Operations. The conditional field would have a value "yes" or "no" and would be excluded from display. Ideally, the checkbox would simply be absent if the value is "no." Alternatively or additionally, it would be helpful to display a message explaining why the item can't be selected to include in a list. Can anyone provide suggestions for a general approach? Thank you for any help and suggestions.

By conditional field do you mean a simple Boolean? If so, you should be able to pull this off with some tactical field rewriting.

When creating the Boolean in your content or entity type, have 'Yes' as the only value, leaving the unchecked state assumed as no. Then in views add the flag list field first and exclude. Next the Boolean but don't exclude. Use its default formatting not its key. In its settings rewrite using the flag list field replacement pattern, and in the empty behaviour (eg the result of the empty checkbox when no value has been specified for it), choose to hide rewriting.

You may need to fine tune this or perhaps add additional fields, chasing the replacements until it works. You'll be amazed at the sophisticated conditions you can set up in this fashion.


Views - D7 - Filtering by authorname only works with admin role I've created a view which is displaying time tracking information.  Everything works great except one thing and I can't figure out what the issue is.  I have an exposed filter which filters by authorname.  The filter by default is an autocomplete text field.  When I am logged in as an admin role, the autocomplete works as it should, however when I am logged in as an authenticated user, that filter stops working.  All my other exposed filters work, except this one.  I am assuming it is a permissions issue, but I cannot for the life of me figure out what I need to enable to allow a regular user use this filter.

Any suggestions would be appreciated. I am using D7 with Views.

I just installed the Administration Views module and ran into this issue.  Setting the "View user profiles" permission fixed the problem.  Thanks @Marius Ilie.


How to redirect after submitting a multi-step registration form? I want to redirect after submitting  multi-step registration (Two step registration), and also I want to prevent the automatic logging to drupal website after registration completes.

I tried the normal way

$form_state['redirect'] = 'url';

But it doesn't work.

Then I checked the form action, it also goes to the specified URL after completing the first step.

I just put some of the codes in my module here

function caubo_registration_form_alter(&$form, &$form_state, $form_id) {
if ($form_id != "user_register") return;

// custom codes
.....

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 2) {
caubo_register_page_two($form, $form_state);
return;
}

if (isset($form_state['storage']['page']) && $form_state['storage']['page'] == 3) {
caubo_register_page_three($form, $form_state);
return;
}
}

I tried the Rules Module and implement the method here, but after completes the registration form, the user is automatically logged in to drupal website, how prevent it?

First, make sure no modules with a higher weight than yours are changing the value of $form_state['redirect'] in their hook_form_alter() implementations. Stepping through with Xdebug is a fairly easy way to do this.

If that is not the cause, then it sounds like a call to drupal_goto() is happening somewhere in the process and interrupting the page flow. If your multistep form is working up until the final step, it could well be your own code doing it. Otherwise, check if anything you are doing would trigger any hook implementations or other code that could contain immediate redirects (a.k.a drupal_goto).

Devel can also display a redirection page, which may be a useful feature when debugging this.

Finally, check that $_REQUEST['destination'] isn't being set via the URL or otherwise.


Modal form instead of redirect I have a site-wide contact form setup that redirects the user to the homepage and posts the submission result to the help section. It works as intended, but I was wondering what I would need to do to change this behaviour.

Instead of redirecting, I would like to display the form submission result in a modal (maybe jQuery) popup.

How could I achieve this?

I wouldn't like to lose the core functionality, just maybe override it with a custom module or something. Any thoughts?

EDIT:

Starting with @rémy 's suggestion, I created a .module file where I'm trying to override the standard behavior for form submission.

Right now the only thing I have is as follows (although it doesn´t work):

<?php

/*
*  Override the the form submit behaviour.
*/

function modal_contact_form_result_form_node_form_alter(&$form,       FormStateInterface $form_state, $form_id){
    $form['actions']['submit']['ajax'] = array(
        'callback' => 'ajax_test_dialog_form_callback_modal'
    );
}

function ajax_test_dialog_form_callback_modal($form, FormStateInterface $form_state){
    $response = new AjaxResponse();
    $content = 'Form submitted successfully, thank you!';
    $title = 'YForm submited';
    $response->addCommand(new OpenModalDialogCommand($title, $content, array('width' => '700' )));

return $response;

}

But at this moment it neither prevents redirecting nor pops up the modal.

In a custom module, you need to alter the contact form and add an #ajax attribute to the submit button:

function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['actions']['submit']['#ajax'] => array(
          'callback' => 'ajax_test_dialog_form_callback_modal',
    );
}

And then provide this method, using OpenModalDialogCommand, in your module too:

    function ajax_test_dialog_form_callback_modal($form, &$form_state) {
      $response = new AjaxResponse();

      if ($form_state->getErrors()) {
        unset($form['#prefix']);
        unset($form['#suffix']);
        $form['status_messages'] = [
          '#type' => 'status_messages',
          '#weight' => -10,
        ];
        $response->addCommand(new HtmlCommand('#my_form_wrapper', $form));
      }
      else {
        $content = 'Something to show in the modal';
        $title = 'Hi, I'm a Modal';
        $response = new AjaxResponse();
        $response->addCommand(new OpenModalDialogCommand($title, $content, array('width' => '700')));
      }
      return $response;
    }

  Here I'm making use of the form element status_messages to display
  validation errors, otherwise we pop up a modal with custom text.

With drupal_get_messages() you could get the system messages and clear the queue.

Don't forget to make the classes available

use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;


Linking nodes using views I am having the hardest time figuring out how to display multiple content types in a page using views.

In my example I have a music studio.

I have a content type for user including basic personal info

I have a content type for studio including room capabilities

And finally I have a content type for computer including hardware specs.

I'd like to have all this viewable on a page together so that when a user views a studio they see the user (engineer) and the computer information.

I'm very slightly familiar with entity ref but it appears to only show the title of the node when viewing and I'd like to have a page with composite information containing fields I select from each node/content type

This can be achieved with Entity reference and relationship

Create a views of studio.
Make a relationship of Entity reference with user and hardware information
Now when you select fields all the fields from user, studio and hardware will be available in the list.
Select those fields which you need. and that's it.


Is possible to use multiple taxonomy terms name (not tids) as contextual filter in Views? For example: example.com/TermName1+TermName2+TermName3.

It seems that the "Allow multiple values" option only works with tids.

Maybe too late for this to matter, but you may be able to do this with hook_views_pre_view().

Possible example:

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if (!empty($args)) {
    // change the argument to term IDs
    $term_names = explode('+', $args[0]);
    foreach ($term_names as $term) {
      $terms[] = taxonomy_get_term_by_name($term)->tid;
    }
    $view->args[0] = implode('+', $terms);
  }
}


Get the number of followers and following in user relationship I have created a relationship Followers which can be reciprocated using the user relationship module. Now user A's relationship is something like:
Followers(Them to you):  User B, User C, User D
Followers(You to them): User D

Now i want to create a view which only shows the number of followers and following:
Follower: 3
Following: 1

I went about to create the view (Views 3, Drupal7) but was not able to do. Didnt get any filters or relationships regarding this. Also, tried using the Views Cal but am not clear. Would appreciate any help.

Thanks

Edit:

Apologies for not being clear.

I created a view of type Users. Then i added a relationship (this is the part where i am not sure if i am correct or not). I tried with all the available relationships pertaining to this such as User relationships:

 User relationships: Requestee user
 User relationships: Requestee user is current user
 User relationships: Requester user
 User relationships: Requester user is current user
 User relationships: RTID

(i tried individually all of them and various combinations of them as well)

Then under Others i clicked yes for Use Aggregates and when asked for the grouping function ("Group type"), i selected "Count and unchecked the label in the configure field screen, so that it only shows the number.

I also added a filter that the user is logged in. However, it just shows me the number of relationships of different users who have requested the current one.

Edit 2:

Found this thread: http://drupal.org/node/809476. However its for Drupal 6..., am trying to implement it for 7. lets see...if you have any pointers i would be grateful...will keep you posted

Edit 3:

Based on the above thread i wrote the following code into a custom block.

<?php
global $user;
$user_id = $user->uid;
$params = array("requestee_id" => $user_id, 'rtid' => 3);
$count = user_relationships_load($params, array("count" => TRUE));
echo $user_id;
echo $count;
?>

I just printed out the user id to check if correct user or not and it prints the correct user. However, count prints 0. Why is that?

Edit 4:

I think i am on the right way using http://drupal.org/node/203396. However there are some fixes there. The correct code is:

<?php
global $user;
$requests = user_relationships_load($param = array("approved" => 1, "user" => $user->uid), $options = array(), $reset = FALSE);
$requestcount = count($requests);
echo  $requestcount;
?>

This displays the total number of approved relationships. Now i want only the followers type relationship number. Looking into that. If anyone has any suggestions would appreciate them. Will keep you all posted

Edit5:

And now i am stuck. Whatever i try to do i am only getting the total number of relationships. I just want the number of followers(them to you) in one block and then using that, i hope, i will be able to get number of following(you to them). Would appreciate any help.

Thanks

The following function works for me to display the count of friends a user have:

function mymodule_user_friends_count ($user) {
  $count = user_relationships_load(
    array("user" => $user->uid, 'approved' => 1, "name"=>'Friend'),
    array('count' => TRUE));
  return $count;
}

Notice I only count approved friends and only relationships of type 'Friend'


How do I connect to an external database and specify the schema to use? I want to connect Drupal to an external Database and I need to specify the schema on the settings.php file, otherwise Drupal schema module connects by default to the 'public' schema. I tried, without success, with the following code.

 $databases['conservation']['default'] = array(
   'database' => 'conservation',
   'schema' => 'projects_test1',
    'username' => 'xxxxxxxxxxx',
    'password' => 'xxx',
    'host' => 'xxx.xxx.xxx',
    'port' => '5432',
    'driver' => 'pgsql',
    'prefix' => array(
      'default'   => 'projects_test1.',
      'users'     => 'shared.',
      'sessions'  => 'shared.',
      'role'      => 'shared.',
      'authmap'   => 'shared.',
    )
  );

I have done some googling, but I haven't found anybody trying to do this.

You can specify a PGSQL schema using the prefix setting in settings.php

 * You can also use a reference to a schema/database as a prefix. This may be
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );

More info: https://api.drupal.org/api/drupal/sites%21default%21default.settings.php/7 > "View Source"

If that's not working for you, make sure the rest of the database connection details are correct. (e.g you're using 'shared.' presumably that schema also exists)


How to send values to an external database with a custom module? Working on Drupal 7.54

I am more a site builder than a developer but now I have no choice, I need to write a little module for Drupal 7.

So, I was wondering if someone could help me to write this custom module (at least help me to start).

Here is my problem :

I need to send form values to an external database.

For the moment, I managed to tell Drupal that it will need another database (in settings.php, everything is fine here).

Following "Inserting data to external DataBase
", I managed to create a little form to add a new line in the external database (using hook_form, hook_form_submit, db_set_active and db_insert).

Now I would like to complete this custom module to achieve this :

an user open the node edit form
an user submits changes
the form is submitted
the form values are saved as usual on Drupal database
AND the same values are saved on the external database

Finally, I need a module to synchronize Drupal nodes with external database tables.

I suppose this is something totally doable and easy for someone used to Drupal API.
Thanks in advance for any help on this.

PS : you may find a first brainstorming on this problem here : How to edit external database from Drupal 7 interface?

Related questions

How to define and use an external database connection in a custom module

I'm a little fuzzy on the details of what you already have but the code below should help you get you in the right direction (I think). It will check for changes to the fields, make sure the node exists in the external database and then update the external database table.

Just remember to change the db_set_active statements to the name of your database and change the table names.

As a side note, as you said you are more of a site developer, if you install the Devel module you can use dpm() to print variables, arrays,  messages etc. to the Drupal message space. E.g. if you wanted to see what was in $new, after the foreach() where we add the updated fields to $new, adding a new line with just dpm($new) will display the array in a structured and pretty way.

Its an invaluable tool for module development!

/**
 * Implements hook_node_update().
 */
function external_update_node_update($node) {
  // Get a list of fields for the content type.
  $fields = field_info_instances("node", $node->type);

  // Set variables as arrays.
  $old = array();
  $new = array();

  // Get the values of the fields for both the original and updated states
  // and add them to the arrays.
  foreach ($fields as $key => $values) {
    $temp_field = field_get_items('node', $node->original, $key);
    if (isset($temp_field[0])) {
      $old[$key] = $temp_field[0]['value'];
    }
    else {
      $old[$key] = NULL;
    }
  }
  foreach ($fields as $key => $values) {
    $temp_field = field_get_items('node', $node, $key);
    // If the field is not empty...
    if (isset($temp_field[0])) {
      $new[$key] = $temp_field[0]['value'];
    }
    // Else add an empty value.
    else {
      $new[$key] = NULL;
    }
  }

  // Check if there are any differences between the new and original states.
  $diff = array_diff($new, $old);

  // If there are differences then an update can occur.
  if (!empty($diff)) {
    // Start the database transaction in case something goes wrong.
    $transaction = db_transaction();

    // Add a try/catch to be able to roll back the database if it errors out.
    try {
      /** Check all node fields exists in external database. **/

      // Get database fields.
      $sql = "SHOW COLUMNS FROM update_save";
      // Switch to external database.
      db_set_active('external');
      $query = db_query($sql);
      // Switch back to drupal db.
      db_set_active();

      // Add list of database fields to array for use later.
      $db_fields = array();
      foreach ($query as $row) {
        $db_fields[$row->Field] = $row->Field;
      }

      // Check if the node contains new fields that are not in the database.
      $field_diff = array_diff_key($fields, $db_fields);
      // If extra fields exits set a log message
      // and remove these fields from the update.
      if (!empty($field_diff)) {
        foreach ($field_diff as $missing_field) {
          watchdog('node_update', "The field $missing_field is missing from the external database.", WATCHDOG_ALERT);
          unset($new[$missing_field]);
        }
      }
    }
    // If something went wrong and it threw an error,
    // catch the exception, roll back any database changes and log the error.
    catch (Exception $e) {
      $transaction->rollback();
      watchdog('node_update', "
$e
");
    }

    try {
      // Check if node already exists in the external database.
      $sql = "SELECT nid FROM update_save WHERE nid = :nid";
      // Switch to external database.
      db_set_active('external');
      $query = db_query($sql, array(":nid" => $node->nid));
      db_set_active();
      $nid = "";
      foreach ($query as $row) {
        // If there are any results add it to the $nid variable.
        $nid = $row;
      }

      // If the query came back with results and therefore $nid is not empty,
      // then the update can continue.
      if (!empty($nid)) {
        // Switch to external database.
        db_set_active('external');
        db_update('update_save')
          ->fields($new)
          ->condition('nid', $node->nid)
          ->execute();
        db_set_active();
      }
      // Else add a watchdog log.
      else {
        watchdog('node_update', "The node currently doesn't exist in the external database.", WATCHDOG_ALERT);
      }
    }
    // If something went wrong and it threw an error,
    // catch the exception, roll back any database changes and log the error.
    catch (Exception $e) {
      $transaction->rollback();
      watchdog('node_update', "
$e
");
    }
  }
}


Variables injected or set in a Twig file are undefined after the first position of an entity reference field I have a Paragraph setup that has an entity reference field allowing an editor to select multiple nodes to use in a display.

Based on the count of nodes, I want to trigger a class. I figured a way to do this was with hook_preprocess_node() in the theme:

$referringItem = $node->_referringItem;
    if (!empty($referringItem)) {
      $referringEntity = $referringItem->getEntity();

      if (
        !empty($referringEntity)
        && ($referringEntity instanceof NodeInterface || $referringEntity instanceof Paragraph)
       ) {
        $referringEntityType = $referringEntity->getType();
        $referringEntityTypeId = $referringEntity->getEntityTypeId();
      }
    }

if ($referringEntityType == 'homepage_feature') {
        $count = $referringEntity->get('field_items')->count();

        // Default.
        $variables['top_image'] = FALSE;
        $variables['right_image'] = FALSE;

        // Should this be count is only 1 AND it is the first delta item in field_feature?
        // If not, any single item Homepage Feature will get top-image which may not be
        // desired.
        if ($count == 1) {
          $variables['top_image'] = TRUE;
        }
      }

The logic above might be too involved. Basically I am looking back to see what paragraph type was used, so I can pass new variables to the template.

What I noticed is that even though the code is hit for every node listed, the variables only exist in the first node. I dumped them in the template and it is correct there, but they are undefined in the other nodes.

In Twig, I tried dumping the variable at the top of the template:

{{ top_image }}

I can see it in the first record 1 above the markup, and then it never shows again.

How can I ensure the variables are passed to the template, correctly, every time?

Edit:

Looks like using the same node with the same view mode in different paragraphs or entity references on the same page can cause this to happen.

Is the solution then to add cache tags/context to the node being rendered to account for what parent is outputting it?

Based on the comments to the question, I extended the EntityReferenceEntityFormatter class and modified one part in the viewElements method (the rest is the same):

  $view_builder = $this->entityTypeManager->getViewBuilder($entity->getEntityTypeId());
  $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()->getId());

  try {
    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    // Add special information for different paragraph types.
    if ($parent_entity->getEntityTypeId() == 'paragraph') {
      if ($parent_entity->bundle() == 'homepage_feature') {
        $elements[$delta]['#style_flags']['top_image'] = FALSE;
        $elements[$delta]['#style_flags']['right_image'] = FALSE;

        if ($parent_entity->get('field_items')->count() === 1) {
          $elements[$delta]['#style_flags']['top_image'] = TRUE;
        }
      }
    }
  } catch (\Exception $e) {
    // Add logging
  }

Later on, down in preprocess_node:

// ONLY for the homepage handling of featured content.
      if ($referringEntityType == 'homepage_feature') {
        $variables['top_image'] = $variables['elements']['#style_flags']['top_image'];
        $variables['right_image'] = $variables['elements']['#style_flags']['right_image'];
      }

I was able to then add the same node in the same paragraph type multiple times with the correct information. The correct classes are now applied.

Edit:

Just to add to this too, be sure to set your cacheable dependencies so any change to what holds references will not require a cache clear:

$parent = $items->getParent();
$entity->addCacheableDependency($parent);

Edit 2:

Thanks to extra guidance from 4k4, I injected the renderer service and reduced down to:

    $parent = $items->getParent();
    $parent_entity = $parent->getValue();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->id();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->bundle();
    $elements[$delta]['#cache']['keys'][] = $parent_entity->getEntityTypeId();
    $elements[$delta]['#cache']['keys'][] = 'context_aware';

    if ($this->paragraphDisplaySettings->isApplicable($parent_entity)) {
      $elements[$delta]['#style_flags'] = $this->paragraphDisplaySettings->getSettings($parent_entity);
    }

    $this->renderer->addCacheableDependency($elements[$delta], $parent);

paragraphDisplaySettings is a custom service object that aids in evaluating different flags to pass through from the original code just to keep it cleaner and leaner. It's working great.


D8 generate double URL for commerce product I need to create double URL alias for commerce product. I tried with code below :

function mymodule_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
    if($entity->getEntityTypeId() == 'commerce_product'){
        $alias = '/store/'.$entity->getTitle();
        $source = '/product/' . $entity->id();
        $path = \Drupal::service('path.alias_storage')->save($source, $alias, "en");
    }
}

but doesn't work. My alias is overridden by pathauto and I have 2 equal alias.
I need to create /catalog/[commerce_product:title] and /store/[commerce_product:title] URLs.

The first one is set with pathauto pattern and created succesfully. The second one is create with the code above.

After updating the product i have 2 equal URLs:

/catalog/product-title
/catalog/product-title

why do not I have

/catalog/product-title
/store/product-title

how can I save double different alias?

Thanks in advance.

In your hook_entity_update() do like below

    function mymodule_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
      if($entity->getEntityTypeId() == 'commerce_product'){
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $aliasStorage = \Drupal::service('path.alias_storage');
        $source = '/product/' . $entity->id();
        if ($aliasStorage->aliasExists($source, $langcode)) {
          // alias already exist. So save your second alias here.
          $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS, $language);

        }
        else {
           $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS_1, $language);
           $aliasStorage->save('/product/' . $entity->id(), YOURNEWALIAS_2, $language);
        }
        }
    }


Get the "href" attribute of an image I created a new content type in Drupal 7, and added an image field named "field_photo." Can anyone tell me how I can extract the "href" attribute of that photo? Is there a short code I can use?

When you access the field on your node you will get the file id. This can be passed to file_load which will return the file object. One of the properties is filepath which holds the path to the actual file. I'm guessing that's what you are after - images doesn't use href <a> tags do.


Insert bank detail in email if the user choose to pay with bank transfer I want to add a to order checkout emails the bank account details managed by commerce_bank_transfer module.
I create a rule for the order with the bank transfer payment method but I'm not undertanding how to add in the mail my site's bank account infos.

I tryed to add this code to the email

<?php
   $payment_method = commerce_payment_method_load('bank_transfer');
   echo commerce_bank_transfer_bank_details($commerce_order->order_id, $payment_method);
?>

I did some test and in the mail there is nothing where I was expecting my bank info.

Reading commerce_bank_transfer module I saw that commerce_bank_transfer_bank_details function request a 'setting' key in the $payment_method array but if I retry the payment method by

commerce_payment_method_load('bank_transfer');

I have no 'setting' key.

How can I retry the setting from a payment method?

I solve with this code:

<?php
$payment_method = commerce_payment_method_instance_load($commerce_order->data['payment_method']);
echo commerce_bank_transfer_bank_details($commerce_order->order_id, $payment_method);
?>

commerce_payment_method_instance_load() function need in input a string like

'bank_transfer|commerce_payment_bank_transfer'

and it returns a paymente method with all data [ setting included ]


How to create a content type with associated products and customized attributes? I am creating a little CRM at work and I have two content types:

Offers - with some text fields and references to users and companies.
Products - very simple with SKU, Title, Price

Now I want to attached some products to Offers and then alter their attributes like price, add quantity and then display all this as a view with the total amount of all prices sum together.

The final goal is to have multiple offers referencing products but with own price and quantity.

I hope this is not to confusing? I tried already entity reference but then I cannot at a custom price or quantity to those products.

You can use the Field collection module

  Provides a field-collection field, to which any number of fields can
  be attached.

And create a Field collection field (in your Offer Content Type) with a reference to Product and a field named quantity and other named custom price.

So in your Offer you can have many Products with theirs quantities and custom prices.


How to restrict node access based on user roles? How can I allow only specific nodes to be displayed based on user roles?

Basically, I do not want to allow nodes to be accessed by users of some specific role.

What you're talking about is Drupal node access control, which is a huge subject.

The core's built-in support for node access control is rather coarse, and to control access to view a node by role, you must use some sort of node access control module.

There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module to control access based upon roles.

When working with access control, it helps to understand how Drupal access control modules actually work, here is a quick description:

Users granted permission to administer nodes are never restricted by node access control. Users who do not have permission to View published content can never be granted access by a node access module. Only users who have 'access content' and not 'administer nodes' are eligible for the wild world of node access module control.
Node access control in Drupal is as a rule additive. This means that any module doing access control in accordance with the “the Drupal philosophy” should only allow access, not deny it. An administrator who wants to fine tune access to a node must first make sure nobody has access, and then add access grants to anyone that shall have access.

This means that it may be rather cumbersome to restrict access to individual with a module like Content Access, since you must start by denying everyone access, and then add it back to those nodes you don't want restricted.  However, I think it is the best option if you really need to do it node by node. Its primary resolution is content types, but it allows you to override this for single nodes.

Unfortunately, you shall not be able to use Deny access since it only works on content types, with no override for individual nodes.

NB: Using more than one node access module is not recommended.

Note that if you can change your requirements so that you can use content type as your basic unit for node access control, then Deny access would be ideal.   For instance, if you have a role "student" and you want to deny access to nodes with answers, then you can create a content type "Answer" (which can just be a clone of the default "Article") and Deny access will take care of protecting all nodes of the type "Answer" from being viewed by the role "student".


Manually update core from 7.0 to 7.78 in one fell swoop I have recently become an admin for a site that has not been updated since 2011. there are broken links (internal links to the site's blog go to page not found, index error.) I think this is due to a bug, so I want to update the software. However this would be a manual update of Drupal Core and I'm wary of doing anything that might mess up the site's code, not being a coder myself.
Should I go somewhere in the middle of the 7.x updates, or should I go straight to the latest one? What issues may arise from my site from updating to the most recent available?

The latest update contains all of the updates before so going straight to the latest one should be okay and is what is usually recommended. Be sure to backup your site and test the backup on a dev copy.
You should update your contributed modules at the same time as some of them may rely on updated versions of Drupal (core).
Lastly and very importantly, there have been numerous security releases since the 1st release and some of them are quite bad so I would say you should probably assume your site is compromised. That's 78(!) releases you've missed out on, including the infamous Drupalgeddon.