How to get the URL addresses of all the photos on form I have standard input form for custom content (for example, /node/add/page and /node/%/edit) with image-field in which you can upload multiple photos. How to get the full URL addresses of all the photos when user add new content or editing old one (delete or upload extra photos)?

I implemented it this way. Hopefully this will save someone's time. The code works well if you upload files, delete if it works after the removal of the second file in this list and removes only the first remote URL.

function testmodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_photo']['#element_validate'][] = 'my_function';
}

function my_function($element, &$form, &$form_state){

        $lang = $element['#language'];
        foreach (element_children($element[$lang]) as $key) {
                $fid = $element[$lang][$key]['#value']['fid'];
                $file = file_load($fid);
                $url = file_create_url($file->uri);
                dpm($url);
        }
}


Saving a webform programmatically in a custom webform handler throws "Entity validation was skipped." I am trying to save a webform submission inside the postSave in a CustomWebformHandler class.

class CustomWebformHandler extends WebformHandlerBase {
[..]
     public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
        $data = $webform_submission->getData();
        $data['ssa_attachment'] = $doc_id; //doc_id is retrieved with a query
        $webform_submission->setData($data);
        $webform_submission->set('in_draft', TRUE);
        $webform_submission->save();
     }
}

I get the following exception.

  Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "Entity validation was skipped."

I tried to validate before saving and I get this exception.

  Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction: SELECT w.next_serial AS next_serial\nFROM\n{webform} w\nWHERE webform_id = :db_condition_placeholder_0 FOR UPDATE;

How can I trigger the validation before saving?

The WebformSubmission::resave() method prevents the ::save and ::postSave recursion issue from occuring.


drupal 7 contextual filter views update I updated views 3.0 to 3.7 and it broke a slideshow view that was setup with contextual filter to display certain content based off the url. Same setup just updated views if anyone can tell me why this does not work with the new views or how to make it work, would be most appreciated.

I was able to track the issue to a change made in views module that was committed with 3.1 release. Contextual links statement was changed from 'OR' to 'AND' causing issues with the setup that was run with version 3.0.

http://drupal.org/node/1451218#comment-5980636


Dynamic arguments in an AJAX link I have a link that uses Drupal's use-ajax CSS class to AJAX-load some node teasers. The callback for the link uses arguments to set a range in the Entity Field Query used to return the teasers:

function marketplace_ajax_list_menu() {
  $items = array();
  $items['marketplace_ajax_list_callback/%/%/%'] = array(
    'page callback' => 'marketplace_ajax_list_response',
    'page arguments' => array(1, 2, 3),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

function marketplace_ajax_list_response($type='ajax', $collection_nid, $start, $page_limit) {
  if ($type == 'ajax') {
    $output = marketplace_ajax_list_collection_latest_content($collection_nid, $start, $page_limit);
    $commands = array();
    $commands[] = ajax_command_append('#ajax-target', $output);
    $page = array('#type' => 'ajax', '#commands' => $commands);
    ajax_deliver($page);
  }
}

function marketplace_ajax_list_collection_latest_content($collection_nid, $start=0, $page_limit=10) {
  $q = new \EntityFieldQuery();
  $q->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', array('story', 'reader'))
      ->propertyCondition('status', 1)
      ->fieldOrderBy('field_date', 'value', 'DESC')
      ->fieldCondition('field_ref_collection', 'nid', $collection_nid, '=');

  // Get the matching items within the range
  $q->range($start, $page_limit);
  $result = $q->execute();
  $nids = array_keys($result['node']);

  // Make node teasers
  $nodes = node_load_multiple($nids);
  $teasers = node_view_multiple($nodes);
  $build = render($teasers);

  return $build;
}

When the node teasers are appended to the list, I have a jQuery function that updates the arguments in the AJAX link in order to update the range used in the query:

(function ($) {
  var page = 1;
  var page_limit = 10;
  var collection_nid = 12345;

  Drupal.behaviors.marketplace_ajax_list = {
    attach: function(context, settings) {
      page++;
      var link = '/marketplace_ajax_list_callback/nojs/' + collection_nid +'/' + (page_limit * page) + '/' + page_limit;
      $moreBtn.attr('href', link); // $moreBtn is the AJAX link
    }
  };
})(jQuery);

The link's href changes correctly, with the updated arguments, but the new arguments aren't used in the callback's query - the same arguments are used each time, so the same items appear on each click.

If I take the value that jQuery sets in the href and open the link in another tab, I see the correct items.

So I think the issue has to do with the AJAX behavior getting attached to the link and that's not updated each time the function runs. Is there a command I can add to make that happen?

Solved! I found this post - https://drupal.stackexchange.com/a/52788/260 - which answered a very similar question, and that changed everything. This issue is essentially a duplicate of that one.

The fix here in my case was to not just change the link's href but to also update the Drupal.ajax object, like this:

Drupal.ajax['load-more'].options.url = link;

"load-more" is the ID of the AJAX link.


Set select list option value I'm trying to set value of select list programmatically with hook form alter

I have select list with options:

$options = array(125 => 'USA');

and setting value like this

$form['field_news_rubrique']['und']['#options'] = $options

But this don't work.

if i change options like this

$options = array(0 => 'USA');

it's working

if i have multiple value in options like this :

$options = array(124=> 'EN', 125 => 'USA');

it's working too

Do you want to set the value before submission or after?

Before submission:
Use $form and set the default value for the select list using the key.

After submission:
Use $form_state['values']


Can't submit data when rendering a webform programmatically I'm working on a Drupal 8 project, when trying to load a webform programmatically in a controller, the webform is rendered correctly but when data has been submitted no values founded on webform results page (still always empty).

Injecting the form in a paragraph as block and then submit data work perfectly, also submitting data from the webform node page works as it should (We can find data on form results page).

Here is my code:

MyController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\webform\Entity\Webform;

class MyFormPage extends ControllerBase {

  public function content() {
      $webform = Webform::load('my_webform_id');
      $view_builder = \Drupal::service('entity_type.manager')->getViewBuilder('webform');
      $webform        = $view_builder->view($webform);
      return [
        '#theme'   => mycontroller_page',
        '#content' => [
          'title'     => t('I am a page from your controller'),
          'form'      => $webform,
        ],
      ];
  }
}

mycontroller-page.html.twig

{{ content.title }}

    {{ content.form }}

Any idea about this behaviors?
Thanks

@see How to embed a Webform?

I recommend using something like...

return [
  '#theme' => mycontroller_page',
  '#content' => [
    'title' => t('I am a page from your controller'),
    'form' => [
      '#type' => 'webform',
      '#webform' => 'my_webform_id',
    ],
  ],
];


How do I get my custom route to a custom menu link What I am trying to do is:
I want my custom form to show up on a custom path under

    /admin/config/content/mymodule

My routing.yml looks like this

    mymodule.mymoduleform:
      path: '/admin/config/content/mymodule'
      defaults:
        _form: '\Drupal\mymodule\Form\Mymoduleform'
        _title: 'Mymodule'
      requirements:
        _access: 'TRUE'

And my menu.links.yml like that

    mymodule.admin:
      title: 'Mymodule'
      description: 'Manage mymodule'
      parent: system.admin_confifg_content
      route_name: mymodule.mymoduleform
      weight: 100

Pityfully the doku is very thin about that hope you guys have a clue bout this :)

Or maybe i have to figure out how I get the right parent.
I want that menu link displayed under "Content Authoring"

Have a look at filter.links.menu from core. There you can see how the filter module is placing its link under 'Content Authoring'. You can do is the same way.


How do I get a custom script to run when using hook_cron in my custom module? I am brand new to module development, fresh off the D7 tutorial boat. What I want to do cannot be that hard.

I have created my first module called get_weather, with get_weather.info and get_weather.module properly installed and drupal recognized.

I created another simple script that has one function, which I want to run when cron runs. 'update_weather' the ONLY thing this does is return the temperature for that time and store it in the database.

There is nothing to display, there are no blocks to render. However, this does not work:

function get_weather_cron() { update_weather(); }

What's going on here? I get no errors, but nothing happens at all? How do I get my module to run my custom function when cron runs?

Note that my custom function works fine if I run it from a script outside of a Drupal module environment.

Here is code based on comments feedback:

include('weather.php');
function get_weather_cron(){
    watchdog('get_weather_debug', 'Cron function triggered');
    update_weather();
}

Also here is update_weather, which is included in the weather.php include file:

function update_weather() {
    $page['weather'] = scrape_weather();
    //insert into db code here;
}

Again, when I simply run this php normally outside of the drupal enviroment, everything works fine. All I want to do is run this same script when cron runs so this is done automatically. No function in my entire library for this functionality has anything to do with Drupal. I am simply trying to activate it by using cron.

Welcome to drupal! One of the first things that will learn is that Drupal keeps an internal cache of all hooks implemented on the site. Just because you implement hook_cron() in your custom module, and then run cron, does not mean it will work.

Steps I would suggest to help fix

Install drush (this is Drupal's Swiss Army knife)
run drush cc all
run drush cron

Hopefully it will all be resolved

To check if your module is installed and enabled correctly you can

drush pml | grep get_weather (or alternatively look at the modules list in the UI)

Or to check if there is something wrong with your function update_weather();, you can run it in the context of drupal (i.e. alter a full drupal bootstrap with all modules loaded)

drush php-eval "print update_weather();" - you can also place additional logging or printing in your function to see what is going on.

Of course, don't forget to define all you functions that you want to execute in the .module file, as every enabled module, has it's .module file included on every request. On a side note, why don't you do away with calling another function from hook cron?

function get_weather_cron() { update_weather(); }

Simply use something similar to the following one.

function get_weather_cron() {
  // more actual weather getting code here
  variable_set('get_weather_temp', 23);
}

It should be easier to read for the next person too.


I cannot import a large HTML body Am using content import module in drupal 8 to import nodes. For test i have defined like below

It works fine when smaller body content. But when the body is too large. Then the import is undone with no fail message.

Test Case:

I have unchecked the below in the configuration,

I turned on the source mode in ck editor and pasted large body html content. And saved the changes it works.

Content Type: Basic Page

Sample Body Content(Formatted):

Total lines will be around 500.

Is it possible to import the file attachment too?

I have overcome by using the Migrate CSV plugin, now i can able to import large body content.


Translate logo and favicon? I am wondering if there is a method to translate the appearance settings section for each theme, for example the logo URL.

This "Variable Translation" module should help you out: http://drupal.org/node/1113374


Use of batch in REST endpoints I want to use batch in POST in rest endpoints in Drupal 8, but my batch is not getting progressed.
I am creating rest endpoints for my module which will send email to bulk users. So for this purpose I need to use batch which will send email to all users without giving time out error. Please help.

my source code is:

class BatchController {

    public static function callBatch() {

        $batch = array(
        'title' => t('Sending ...'),
        'operations' => [],
        'init_message' => t('Sending is starting.'),
        'finished' => '\Drupal\module_mail\sendEmails::sendEmailsItemCallback',
        );

        $subject='hello';
        $body='body';

        $data = array(0 => array('id'=>1,'Fullname'=>"joy", 'Email'=>"example@gmail.com")
            );
        foreach($data as $row) {
        $batch['operations'][] = ['\Drupal\module_mail\sendEmails::sendEmailsUserItem',[$row,$subject,$body]];
        }
        batch_set($batch);
        return batch_process('home');
    }

}

namespace Drupal\module_mail;

class sendEmails {

    public static function sendEmailsUserItem($user, $subject, $body, &$context)
    {
        $message = 'Sending emails';
        $mailManager = \Drupal::service('plugin.manager.mail');
        $module = 'module_mail';
        $key = '';
        $to= $user['Email'];
        $params['email_body'] = $body;
        $params['email_subject'] = $subject;
        $langcode = \Drupal::currentUser()->getPreferredLangcode();
        $send = true;
        $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
    }

        //batch completed
    public static function sendEmailsItemCallback($success, $results, $operations)
    {
        if ($success) {
            $message = \Drupal::translation()->formatPlural(
                    count($results),
                    'sent.',
                    'Emails sent succesfully'
            );
        }
        else {
            $message = t('Finished with an error.');
        }
        drupal_set_message('Sent succesfully');

    }

}

Right now I am getting this output:

Batch API operations are driven by the end user and browser with meta refresh, which makes it not possible to use in web services. However we can think about implementing the same thing using Queue API.

This should give you enough to go on to re-implement your RestResource or Controller to use your own Queue service.

Summary

I've used the following pattern in the past.

First request has a payload that can instantiate the operation.

It's important to make sure we're not flooding the serve so make sure you have flood protection.
Make sure that we have access to do the operation.

A response is returned with progress state and a queue item ID.
Subsequent requests have a payload with the queue item ID from the previous response.

These requests process 1..n queue items.
We need to claim queue items ourselves because we're processing queue items manually and not with a cron queue worker.
Make sure that things are valid and return the appropriate response code for validation, fatal or other errors.

Request payloads

Initial: {"queue": null}
Subsequent: {"queue": {"item_id": 1}}

Response payloads

Initial

{
   "success": true,
   "finished": false,
   "queue": {"item_id": 1},
   "progress": 0,
   "max": 23,
   "errors": [],
   "result": "something custom here",
}

Finished

{
   "success": true,
   "finished": true,
   "queue": null,
   "progress": 23,
   "max": 23,
   "errors": ["something wrong happened at some point"],
   "result": "something custom here",
}

Queue API

The complexity here is that we cannot use cron queue workers. So we need to implement the database calls to get and claim queue items ourselves. Unfortunately the current Queue API classes are pretty limited in both Drupal 7 and Drupal 8. In the former, I used custom functions to fetch and update queue items directly from the database while in the latter we can create our own service, based on DatabaseQueue, and inject that into your RestResource plugin or Controller.


IP address to trusted_host_patterns I tried to add IP address to for example : 172.20.0.3
I get this error : The provided host name is not valid for this server.

Here my settings

$settings['trusted_host_patterns'] = array(
  '^172\.20.\0.\3$',
  '^localhost$',
);

Your regex is incorrect. You placed the second and third \ after the . instead of before.

$settings['trusted_host_patterns'] = array(
  '^172\.20\.0\.3$',
  '^localhost$',
);


How can I check if the current user is accessing his/her own user page? I would like to print something in page-user.tpl.php only when the current user is accessing his own user page.
(any URL starting with /user/%uid/ but when %uid/ is the user id of the current logged in user)

For example, printing something like "Your are viewing your own user page now." in page-user.tpl.php

How can I make this condtion?

There are two paths a user could be visiting their own page: "user" and "user/UID" where their UID matches.

There is a global variable $user that stores the currently logged in user.

So in the variable preprocessor for the template you can determine whether or not a user is on their own user page and save it to a variable that you can reference in the template file, like below.
Note the use of $variables['logged_in'], which is an available variable as listed in the page.tpl.php documentation.

/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  // If we are on the 'user' page or a sub-page of it.
  if (arg(0) == 'user') {
    $variables['own_account'] = FALSE;
    // If we are on 'user' and are logged in then we are on our own user page.
    if (!arg(1) && $variables['logged_in']) {
      $variables['own_account'] = TRUE;
    }
    // If we are on 'user/UID' then check against the current user.
    else if (is_numeric(arg(1)) && !arg(2)) {
      global $user;
      if ($user->uid == arg(1)) {
        $variables['own_account'] = TRUE;
      }
    }
  }
}

Then you can use the variable $own_profile in your page-user.tpl.php template, which in this case might look something like this:

<?php if ($own_account): ?>
  <div class="own-account-msg">
    Here is some markup for the message a user sees when they are on their own account page.
  </div>
<?php endif; ?>


How to create a custom content type region template? I built a sub theme based on Omega's adaptive Alpha theme. I made a content type called "project". For that content type I need to edit what gets displayed on the project detail page. What is the best way to do this?

I currently have a page--type--project.tpl.php file that I can edit, but Ideally I would like to just edit the region, like with using something like region--content--project.tpl.php file or something. Is that possible? I haven't found anything online with modifying a region based on the content type.

There is a lot of ways to accomplish your goal. I'll point some of them:

Using template files

One of them is to add the new region to your current theme and just use the modules suggested by Sohail (Delta and Context) to make the blocks to be shown in the project detail page. This means that your current theme will be a new site wide region to be used as you need.

There is some other questions that cover this:

How do I create custom regions in a theme?

Render a custom region inside node template

Using GUI

Another way to do this is by using the Display Suite module. Here goes a summary of the module description:

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files.

You can also use the Panels module suite and also the Panelizer module to achieve this goal.


Use different settings for a Views' block basing on the content type of the node being shown I have 2 content types,  photo articles and video articles. On a photo article page, I want to have a block that shows 5 other photo articles. When I place this same block on a video page, it should show 5 video articles.

How can I use contextual filters to achieve this? I don't want to install a separate module to achieve this.

You can use Entity Views Attachment to attach your view to those content types instead of using blocks. EVA will allow you to pass in the content type of the current article as a contextual filter.


How to hide or show Field's Label? Is there any programming method to hide or show each Field's Label of custom content type in twig template files, regardless of fields manage display setting?

Override the template for that specific field and don't print the label.

field--field-thing.html.twig

{% if multiple %}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% else %}
  {% for item in items %}

{{ item.content }}

  {% endfor %}
{% endif %}

Alternatively, you can preprocess the field and remove the label/change the display, but personally I would do it in the templates so later on the label could easily be added back in.


how to get valid URL in combination of text and field content in VIEWS Field HOSTNAME returns IP Adress.
I have to overwrite the field output .
Is there a way to modify this with an given URL like this:
'www.ip-tracker.org/locator/ip-lookup.php?ip=' and adding the field content of HOSTNAME to get an valid URL?

Yes you can use the Rewrite results option on your Field settings. Use the Output this field as a link option and enter only the URL with the field token replacement pattern at the end of it.

You can look up the token under Replacement patterns under the Rewrite results option.

If you need some more control over the link HTML you can use the Rewrite the output of this field where you construct the entire link HTML <a href="....


How do I create a block? I am trying to create a block using hook_block, in Drupal 7. I have the following code in my module file (module.module its not actually called that but, this is an example).

function module_race_results_block_info($op = 'list'){
  $block = array();

  if ($op == 'list') {
    $block[0]['info'] = t('Race Results Block');
  }

  return $block;
}

function module_race_results_block_view($delta = 'raceresults') {
  $block = array();

  switch ($delta) {
    case 'raceresults':
      $block['content'] = module_race_results();
      break;
  }

  return $block;
}

function module_race_results() {
  $content = "Testing Race Results Block";

  return $content;
}

How can I test this? The block is not showing up in the blocks list (/admin/structure/block).

Quickly, it's $block['content']=module_race_results(); in your hook_block_view(), and $blocks['raceresults']... in your hook_block_info() so it matches your hook_block_view().

More precisely, this is probably more of what you are trying to accomplish:

function module_race_results_block_info() {
  $blocks = array();

  $blocks['raceresults']['info'] = t('Race Results Block');
  // any more blocks here

  return $blocks;

}

function module_race_results_block_view($delta) {
  $blocks = array();

  switch($delta) {
    case 'raceresults':
      $blocks['subject'] = t('Race Results');
      $blocks['content'] = module_race_results();
      break;

    // any more blocks here

    }
  }

  return $blocks;
}

function module_race_results() {
  $content = "Testing Race Results Block";  // eventually this should become a renderable array instead of plain text or html
  return $content;
}


Creating a store open hours widget using Field API I need an open hours widget that outputs something like:

Mon 8:00am to 5:00pm
Tue 8:00am to 5:00pm
Wen 8:00am to 5:00pm
Thu 8:00am to 5:00pm
Fri 8:00am to 5:00pm
Sat 11:00am to 3:pm
Sun Closed

I think the best way to do this is create a three column field table with day of week, open and close columns. Then create a field widget form with three drop down boxes and a formatter that puts it all together.

Has somebody already done this in Drupal 7? If not, does anybody have any ideas on how to do this best?

I would check out the Office Hours module. It has a dev version for D7, you can either help finish the port, or at the least pick up some ideas on how to best accomplish this.


Module can't update after updating core I updated my Drupal 8 website from 8.2 to 8.3. I have a module that has a block and includes a configuration form which has various data form fields.
The block of the module appears to work fine.
But when I try to update any of the configuration data it simply doesn't change anything! Something to do with not updating the database, maybe?

Example: I want to change the modules block name.
The old name is "oldname" and I want it to be "newname". After typing in the new name on the configuration page and clicking save the name will still remain "oldname".

There is not a single error within Drupal or my servers log file that would explain this.
Is there anywhere else I can look to find what the problem is?

What's changed with the new version of Drupal that might cause this?

After searching for awhile and cleaning out some old modules from the database I've finally come across an error relating to forms. It' quite long but here's the first part:
Warning: strip_tags() expects parameter 1 to be string, array given in Drupal\favorites\Form\AddForm->buildForm()

Use drush config-edit, as stated in the docs.

Or implement an upgrade path for you module, see hook_update_N.


Why does simpletest report a missing schema for my Drupal 8 module? My module is working as expected with the following settings, config and config export. But when I try to run tests, I get the following error. I'm not sure what is wrong.

  Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for riddler.settings with the following errors: riddler.settings:riddles missing schema in Drupal\Core\Config\Testing\ConfigSchemaChecker->onConfigSave() (line 102 of /var/www/sb/sboss/docroot/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php).

# settings.yml
riddles:
 -
    question: 'Do you really hate Spam?'
    response: 'Yes!'
langcode: en

--------------------------------

#schema
riddler.settings:
  type: config_object
  riddles:
      question:
        type: label
        label: 'Question'
      response:
        type: label
        label: 'Response'

#config export

riddles:
 -
    question: 'Do you really hate Spam?'
    response: Yes!
  -
    question: 'What''s your favorite primary color?'
    response: 'blue, yellow, red'

I see several errors, not sure which one trips you: you missed a type for riddles and tried to define a mapping immediately under. But riddles is a sequence and each element in the sequence is that mapping. So:

riddler.settings:
  type: config_object
  mapping:
    riddles:
      type: sequence
      sequence:
        type: mapping
          question:
            type: label
            label: 'Question'
          response:
            type: label
            label: 'Response'

At least that's what I would attempt...


Change the "Submitted by" date type? By default, in Drupal 7, the "Submitted by" date type is set to Medium.  I want the "Submitted by" date to be rendered using a different type.  How do I do this?

It's hard-coded into template_preprocess_node() so to override it you'll need to implement your own preprocess function, either in a theme or custom module:

function MYTHEME_preprocess_node(&$vars) {
  if (variable_get('node_submitted_' . $vars['node']->type, TRUE)) {
    $date = format_date($vars['node']->created, 'date_type');
    $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $vars['name'], '!datetime' => $date));
  }
}


How to alter tabs that have wildcard in bartik main menu The problem is that I have some menu items with wildcard that I wanna add in main menu tabs, but can't realize how to do it. It can't be solved by hook_menu as I undestood. Tried use preprocess_links__system_main_menu, menu_tree__main_menu but they didn't execute. How correctly do this?

Solve this by page preprocess function. Not sure is this correct way or not.

function mobitek_custom_preprocess_page(&$vars) {
  $nid = arg(1);
  $node = ($nid && arg(0) == 'community' && is_numeric($nid)) ? node_load($nid) : FALSE;
  if (!$node) {
    return;
  }
  $main_menu = &$vars['main_menu'];
  $mobitek_menu_items = array(
    'communities',
    'reports',
    'administrators',
    'users',
  );
  // Remove links by this.
  foreach ($main_menu as $key => $menu_array) {
    if (isset($menu_array['identifier']) && in_array($menu_array['href'], $mobitek_menu_items)) {
      unset($main_menu[$key]);
    }
  }

  ....

  foreach ($community_links as $title => $community_link) {
    $new_tab = array(
      'title' => $title,
      'href' => $community_link,
    );
    array_unshift($main_menu, $new_tab);
  }

  // Add link by this.
  if (arg(0) == 'community' && arg(2) == 'profiles-roles') {
    $on_roles_page = (arg(3) == 'user-roles');
    $profiles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-profiles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $profiles_item,
      '#active' => !$on_roles_page,
    );
    $roles_item = menu_get_item('community/' . $nid . '/profiles-roles/user-roles');
    $vars['tabs']['#primary'][] = array(
      '#theme' => 'menu_local_task',
      '#link' => $roles_item,
      '#active' => $on_roles_page,
    );
  }
}


How can I pull the latest published revision for a referenced node using the CCK node reference field? Right now if I reference a node in another node via a CCK node reference field, if I change the referenced node, which creates a new revision of that node, it shows the edits on the page that's referencing that node even though I haven't published the latest revision.

I'm looking for a way to patch the node reference field or CCK to join on the node_revision table so it will pull only the latest PUBLISHED version instead of the latest edit.

I have looked through both nodereference.module and content.module under CCK to try to find where the body is pulled in so I can edit the query.  I can't find that query.

Any help is GREATLY appreciated.

Which module are you using to get forward-revisions? Revisioning?

This just seems like a bug in node reference field in that it makes the assumption that the latest revision is always published (which is true in core).

http://drupal.org/node/738116 has a patch which seems like it fixes node titles on auto-complete widgets and in the list of nodes. But it falls short of completely fixing the issue.


How to add integer field to content type? I am trying to add  year field to content type. I selected integer as field type, then i see text field as widget. How can I set to 4 digits max and allows only numbers only?

Thanks,
D

You could use the Date Module

Then when you add a new field, select Date as your Field Type.

When you configure it use something like this


Adding "terms" on the fly and/or mutiple term referance submission with "unlimted values" I have an issue which I’m hoping you guys can point me in the direction.  I’m currently building a music press/media site in which I want to use “terms” for things like the artists, venues etc.  Eventually writers will be able to submit their work via the normal add content route and all the various terms will be created when there filling out the submission form.  At the moment I’m using a “Term Reference” field with the “Autocomplete term widget (tagging)” widget to add in the main artist.  I have a separate field for the support artists  with the Number of Values option set to “unlimited” however I don’t get an option to add another support artist in (like you would if the fields reference was set to text).

So I’m looking for a way to get an option within the node submission form to keep on adding support artists as term references  and/or a method of adding term references on the fly so they can be selected via a drop down list whilst the submission form is being filled out (i..e not the term references are add and in place before the form is saved.
Any help on this would be mostly appreciated as this has had me stuck for a while now.

Thanks.

I would recommend you try the Hierarchical Select module if you want to have a drop down select as well as have the ability to add new terms on the fly. You select this option when setting up the Hierarchical Select for the term reference field. It will add 'Add new term' to the select list.


How NOT to delete original account picture when uploading a new one? When a user updates his account picture (default "picture" field,) his existing picture is deleted and replaced with the new uploaded picture. This is normally done by default.

How, using Rules (or any other way,) do I prevent the system from deleting the original stored picture so that the old and new picture reside in the same directory?

Thanks. :)

Update: Someone suggested making the field multiple value. I do not want users to be able to upload several account pictures. All I want is that a newly uploaded picture will indeed replace the old one but the old picture not to be deleted. Like I said in a comment below, the Heartbeat module takes a snapshot of the account picture. When users uploads a new picture, the old picture in the snapshot no longer displays (of course, it was deleted!) and a blank empty space is shown instead. Keeping the old picture would solve this issue.

When a user adds a new pictures make a copy of this pictures with rules to a user specific directory. When a user wants to restore his picture browse this directory, let the user decide which picture he wants and copy it back with rules.


Facebook Share the older version of the article I using facebook share to share my article to facebook.

Sometimes I edit my article title and image.

While I share it to facebook, the article title and image is still shows the older version of the article.

Anyway to fix this problem?

Use Facebook Debugger to clear the cache. The title and image will updated.


Is there a way to get the controller class from a Request object or any other service class? My controller class holds some not-so-easy logic to receive some data from a route parameter I need in a block plugin. As this block will only be rendered on this specific route, I would like to simply get the route controller route with this block which would receive its data from the controller.
Is there any way to get the controller class from any of the services like current_route_match?
I can get the route object or the route name, but I didn't find a way to get the controller class.

You find the controller class in a request attribute:
$controller = \Drupal::request()->attributes->get('_controller');

You need to instantiate the controller and run the code a second time. For not-so-easy logic it might be a better idea to refactor the code to a service which then caches the result for the second run, as @Hudri commented.
Or take a different approach. Place a custom block with a static placeholder on the page and replace it by attaching bubbleable metadata to the controller output. See Add an attribute to $variables from a Controller
Instead of a render array you can also replace the placeholder in a lazy-builder callback.  This depends on the structure of the data in controller and block and how dynamic this is. At the end this is all about caching performance.


How do I change hashing algorithm? We are transferring our old data to Drupal 8. Our users' password has been encrypted by MD5 and Drupal 8 hashing system works with SHA algorithm.

Which file should I edit to change the hashing system to the simple MD5?

We are aware of risk, but it has been decided.

In Drupal 8.1+, password hashing and checking is managed by a service that can be replaced in your site's services.yml file.  You need to provide your own implementation of PasswordInterface.

Instead of replacing the hash method, it would be safer for your implementation to inherit from PhpassHashedPassword and override the check() method to accept your MD5 hashes (but otherwise use the parent implementation). You can use a dedicated prefix to detect old hashes. And thanks to the PhpassHashedPassword::needsRehash($hash), your password will be securely rehashed over time.

For instance, the following code expect you old hashes to be prefixed with BAD$ in the database.

class MyPasswordService extends PhpassHashedPassword {
  function check ($password, $hash) {
    if (substr($hash, 0, 4) == 'BAD$') {
      // Migrate MD5 has
      $stored_hash = substr($hash, 4);
      $computed_hash = ... old and insecure hash code ...;
      return $computed_hash && Crypt::hashEquals($stored_hash, $computed_hash);
    }
    return parent::check($password, $hash);
  }
}


How can I create a variable with different values for each domain using Domain Access? I have a numeric value that is unique to each domain (using Domain Access) on my site. I'd like to use the same variable name so I can use the same theme and display this value on all domains. Is this possible?

I'm currently defining the variable in a custom module, but I'm only storing 1 value. Can I alter the code in the custom module so that each domain can have it's own unique value for this variable?

UPDATE:

Adding the following when defining the variable in my custom module worked :D

'multidomain' => true,

I can edit the variable through admin/config/system/variable/edit/ and I get unique values across my domains stored in the variable_store table. The problem I now have is that I want to create an admin form for getting/setting a bunch of domain variables and the usual variable_get/variable_set don't work...any thoughts?

You must enable "domain configuration" submodule (domain_conf)
This will provide you the save per domain option:

function your_module_form($form, &$form_state) {

  $form['variable'] = array(
    '#type' => 'value',
    '#value' => time(),
  );

  return system_settings_form($form);

}

getting the variable manually:

function domain_conf_variable_get($domain_id, $variable = '', $all = FALSE, $reset = FALSE)

seeting the variable manually:

function domain_conf_variable_set($domain_id, $variable, $value = NULL)

There is a module which aims to be a replacement variable handling module for Domain Access,If you need setting different variable values for each domain and for each language at the same time you need domain variable module https://drupal.org/project/domain_variable


Entity metadata wrapper - how to get field value, NOT key I hhave field_something which is a select field with multiple options:

key1|Value 1
key2|Value 2

I'm trying to get the value of this field using the Entity metadata wrapper.

$wrapper->field_something->value();

This will return the key, not the value as defined in the node's fields.

Any ideas?

You may use $wrapper->field_something->label().


Base migration class? What's the procedure for including a base migration class that some of my migrations extend? I have some common functionality across multiple migrations class and would not like to repeat the code in all classes.

My question is how do I "register" my base class with Migrate? I need it to get autoloaded. Perhaps if I just include it in the module's list of files?

Take a look at the example migration for beer and wine that ships with Migrate in the 'migrate_example' folder.

You will need to register your your migration and handler classes explicitly with hook_migrate_api(). See 'migrate_example.migrate.inc' inside 'migrate_example'.

However, you don't need to explicitly register abstract intermediate classes that hold common info for other migrations you're implementing. See the abstract class 'BasicExampleMigration', inside 'beer.inc' as an example.


Set view's filter to show nodes of entity refference field of current node I have nodes of content type "product" and this content type has an entity reference field with multiple values, that contains references to another product nodes.

Is it possible to set the filter of view block to show only products that are in current opended product's reference field?

What you want is views' right column.

You need to use a contextual filter of Content: nid, choose to provide a default value Content id from url. If you want to suppress the current product (eg. for a related products display use the Exclude option in the More fieldset at the bottom.)

Then add a relationship and select your entity reference field.

Finally you can add the field Content: rendered node and at the top choose your newly created relationship. This should give you a list of referenced products.

Update: I guess the exclude option takes no effect in this case, since you'll be only listing the referenced products.


How do I avoid "geo:" is removed from links? I need to place on my site link with geo scheme:

some location

But drupal cuts schema from link and i have following result:

some location

Is there any way to disable geo scheme filtering?

I'm using drupal 8.3.5, basic installation without any additional extensions(except autoinstalled during setup process).

UPD.
I using view that displays some fields of custom nodes as HTML list.
Most of fields marked as "excluded from output" and for one field i'm using html output override like this:

{{ field_linktitlefield }}

field_somefield and field_linktitlefield is a simple text.

You need to add geo as an allowed scheme. See https://blog.werk21.de/en/2017/06/06/change-list-valid-uri-schemes-drupal-8 for details.


Multi-Step Registration Profile2 Drupal 7
Modules:   Profile2 Registration Path, Multi-Step Registration, Profile2, Logintoboggan.

I have a Drupal 7 site that has three roles.  User, Advertiser, Auctioneer, each with their own Profile2 fields.  Currently when a user clicks register ALL the profile2 types show up on the page.  The functionality I'm after is, depending on which role they select after filling out username, password and role, the appropriate profile2 type is shown to the user to finish before finishing the user account creation OR something similar.  Is this possible?

Thanks for any guidance.

The Profile2 Registration Path module allows you to create different registration forms to register users using different roles and different profile types.


How disable creating new terms (tags)? I am using drupal 6,How can I disable creating new terms during node submit?
Is there any option to do this? I do not see it in vocabulary settings.

I found, that Content taxonomy module have to do it, but I can figure how!
Thank you for your attention

By default terms not add in drupal,Properly you  are using active tag module,install autocomplete_deluxe module and use it as that field widget.


No title on article page I have created a view which displays the 10 latest news items (articles). They show up fine in teaser format. When clicking on the full article there is no title displayed and I can't work out why. This is my node--article.tpl.php:

  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

        <?php print $user_picture; ?>

        <?php print render($title_prefix); ?>
        <?php if (!$page): ?>
        <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

        <?php endif; ?>
        <?php print render($title_suffix); ?>

        <?php print render($title_suffix); ?>

        <?php if ($unpublished): ?>

                <?php print t('Unpublished'); ?>

        <?php endif; ?>

        <?php if ($display_submitted): ?>

            <?php print $user_picture; ?>
            <?php
                print t('!username • !date • !time',
                array('!username' => $name, '!date' => date( "d/m/y",$node->created), '!time' => date( "G:i",$node->created)));
            ?>

        <?php endif; ?>

    <div class="content"<?php print $content_attributes; ?>>
        <?php
            // We hide the comments and links now so that we can render them later.
            hide($content['comments']);
            hide($content['links']);
            print render($content);
        ?>

            <?php print render($content['links']); ?>

    <?php print render($content['comments']); ?>

Also I should note that I'm very new to drupal and I don't know PHP very well.
If anyone could tell my why that would be really helpful. Thanks.

Your template is expecting that the node title will be displayed as the page title, which in controlled in the page.tpl.php. Either the title is printed, but not where you expect or you don't print the page titles at all.


Where to adjust number of returned results on the /admin/people page? I know, don't hack core I know, you don't need to tell me. Don't Hack Core but I just need to display 1000 user records rows on the /admin/people page temporarily and I'll switch it back. I promise...

Install the Admininstration Views module; it converts that page to a View, which you can edit and set up with paging of your choice.


Programatically Attach a Field to a CCK Type in Drupal 6 I am in the situation where I need to made some modifications to a content type in my .install file. I know how to create a content type programatically, just create it via the UI and export, and recreate the form to submit it.

But in this case deleting the existing content type and recreating it screws up the existing content type instances, so I need to add an existing field to an existing content type. Is that easy to do programatically?

Also what's up with Drupal's API or lack thereof to do these kinds of things? I'd love to do something like:

$foo_content_type = get_content_type('foo');
$foo_content_type->add_field( $the_field );

Why is this kind of stuff so bound to the UI? Is it just because of the historical development of Drupal? I'd say design the programatic API first, then bind the UI to that...
Is Drupal 7 much better?

Anything in the UI eventually has to call a function, so...

The UI for editing a content type goes to path:

admin/content/node-type/NODETYPE

This path is "owned" by the cck module.  Looking in there, you can dig through the forms and hook_menu()s etc to see it eventually calls a function:

content_field_instance_create($field)

which is defined in

content.crud.inc

inside the cck module's inc directory.


How to write an Webservice API Wrapper the drupal 7 way I have been trying to find a standardized way of writing a Webservice API Wrapper the drupal 7 way but I was not able to find any documentation on this.
How does one write an Webservice API wrapper for Drupal 7? An example will be much appreciated.

The standard solution is to use the Services module, which provides hooks for you to define your own endpoints.

There's also Restful Web Services which has similar functionality but is geared more towards entity API integration.

If you literally want to write your own API from scratch then just use your best judgement - there aren't any Drupal-specific standards for that.


Use views result to send data to a rule I have a custom view that display several email address.
How I can use these addresses to send it an email with a rule?

This module will help you views_rules

From module page:

  View loop

  A view loop is similar to a regular Rules loop, but allows looping
  over rows of view results.

  Collect view result rows (action):

  This action collects each variable in all view result rows into list
  variables for use in Rules.


Is there a way to show a page dynamically when hovering on it's link? Just wondering if there is a module or some way in general to do the following:

When hovering on a page link show the content of that page as a tooltip or some kind of small dropdown window.

Thanks.

Beauty Tips is a drupal module and a jQuery plugin that will allow you to display content tooltip style via hover, click or a range of other events.

It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.

Most importantly, it allows developers to add their own custom beautytips popups to their site without having to delve into jQuery.

You can use this module and fetch the data which do you want to display in tool tip.


How to make FROM and TO filter? I have a height field for users.

How can I make a simple filter in views where visitors can search to and from?

Like:

Search users: From 150cm To 180cm

Thanks,
Bruno

You can do it from views itself from the filter criteria.

Or if in need of additional options try out the Better Exposed Filters

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience


Drush Command for Installing core Is there a simple drush site-install script for Drupal 8? I've gotten very used to running the following script to install Drupal.

drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://username:password@localhost/sitename -y;

I manage to install Drupal 8 with Drush after creating the project with Composer from drupal-composer/drupal-project. Steps I take are as follows:

Create project with dev dependencies:

composer create-project drupal-composer/drupal-project:8.x-dev directory-name --stability dev --no-interaction

Create site-database for the project.
Run inside web folder:

../vendor/bin/drush site:install standard --account-name=admin --account-pass=admin --db-url=mysql://username:password@localhost/site-database -y


append values to drupal7 cck link field entry I've got a question about the CCK link field.

I'm using the link field as a way to get a youtube video embedded onto a page and displayed through colorbox, but in order to make it work I have to include all the embed video information like size and iframe acceptance.

i.e. ?width=560&height=315&iframe=true

Ideally I'd love my users to just have to put the video link in and not worry about including the size specs.

is there any way i can append this kind of information to this field?

I'm using:
D 7.23
CCK link mod 7.x-1.1

Thanks!

You can use the Media: Youtube module.

You would then create a file field with a Media file selector widget. Make sure you configure the field to use the Youtube URI schema.

You can configure the size of the video through the field display settings.

When you create a new node, you will need the share url, like http://youtu.be/n1yxNjU7u_8 to embed it.


Webform Rules - Create a Drupal User I'm using Webforms (via the Webform module) and using Rules (with the Rules module and the Webform Rules module)... as a side note, I'm also using CiviCRM although I don't think that is has an impact of the issue I am having...

When using Rules I can specify an action to take place on a given event - in my case when a particular webform is submitted.  When webform 'a' is submitted I want a Drupal user to be created...

If I use the action 'create entity' and specify that the entity to be created is of type 'User' then if I statically enter the value for the username and the e-mail address the Drupal account is created.

However, if I try to tell the action creation process to use the value entered in the webform as the username and the e-mail address ( e.g. [data:{component}-value] where {component} is substituted for the machine name of the field in question ) for the intended Drupal account, no Drupal account is created.  Does anyone know why this is the case and what the solution for this is?

Side note: I know the value used in [data:{component}-value] is correct as I added an action saying output a message and added the data field to the message and it shows the correct details (e.g those entered in the webform)

You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:ComponentFieldName-value-raw] (and with a data type which equals the data type of your Webform component). Looks like you need 2 variables though: 1 for the username, one for the eMail ID.
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).


How to display multiples jQueryUI progressbars in a page in Drupal 7? I am developping my personnal website with Drupal 7. I would like to show a progressbar for each of my skills, but with differents values.

For exemple, I would like to see a progressbar under (or between if possible) a text, and (also if possible) with a percentage.

So I tried to use jQuery UI to solve my problem.

I want all my progressbars with a different value for each. Below, an exemple of the code of my website :

<?php
drupal_add_library('system', 'ui.accordion');
drupal_add_library('system', 'ui.progressbar');
drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion();});', 'inline');
drupal_add_js('jQuery(document).ready(function() {jQuery(".progressbar").progressbar({ value: 37 });', 'inline');
?>

RÉSEAU

Windows Server 2008

50%

Ubuntu Server

50%

Virtualbox

90%

But it does not work.

To solve that problem, I tried that kind of code found on that website, but I does not work for me, when I include it in drupal like that :

<?php
drupal_add_js('jQuery("div.progressbar").each (function () {var element = this;jQuery(element).progressbar({value: parseInt(jQuery(element).attr("rel"))});});', 'inline');
?>

Perhaps, I am in wrong, but any answer would be so great. Thank you in advance. :)

Your first code example for the progress bar has a small syntax error (missing a }); at the end of the line). I'm not sure exactly why your second example doesn't work, (I didn't try it) but this code works perfectly for me using your HTML as an example:

drupal_add_js("
  (function($) {
    $(function() {
      $('.progressbar').each(function() {
        var val = $(this).attr('rel');
        $(this).progressbar({ value: parseInt(val) });
      });
    });
  })(jQuery);",
  'inline'
);

This code produces:

EDIT

I've just noticed you have some invalid HTML in your code which probably won't help. You're wrapping <h4> and <div> tags in a <p> tag, which is invalid XHTML. It might not be the problem but it would be better practice to change that <p> to a <div>.


How to create a sponsors logo block? I have some experience with Drupal 7, but not that much. Now I'm working on my first Drupal 8 website and stumbled over the following situation:

In a first iteration, the website should use the default theme and should be as drupal-ish as possible in its solutions. One requirement is, that I have a list of 5 "sponsor logos" that should appear on the frontpage and the imprint. They should all appear in the same height and in one row (on a desktop browser and probably break on mobile).

Due to the fact that they should appear on different pages, I guess, I want to create a block for this. But what would be the most Drupal way, to add this row of logos to this block?

Just adding pictures in the editor feels a bit "undrupalish" and it seems to be meant for only one image. Adding code by hand and adding the addresses of the images feels a bit like "Why am I actually using a CMS?"

I hope my question is precise enough to get some input.

A proper way IMO is a “Sponsor” Entity content type with the Fields you need, then create as many Sponsors as you need. Then use Views to create a Block display and select all published Sponsor content and output it as needed. Then place the block in the desired region. Later you may want to expand on sponsors and add more structured data around them, which is why you'd have a content type (or custom entity type) over just a single-use block type.


Panopoly add content panel I have seen this Panel on Panopoly distribution where you can add different elements from the left side, add content to them and also have a preview.

I was wondering if this is powered by Panel (or its related contributed modules) or is only available if you install Panopoly?

Many thanks,

Luca

I just tested installing panopoly distribution and a series of module needed to build same functionality on standard drupal profile installation

Here are my findings

The functionality you are asking does not seem to achieve with one contrib module instead its a result of lots of modules
Check this
link. This links lists the feature list or the main modules
list.
lets take panopoly_pages contrib module, this module
allows user to add content or landing page
but again this module
depends on several other modules to work in desired way
Here is
the link for complete list of all required modules.

My findings
Installing all required modules I found it almost become the complete panopoly profile,so in my views it will be better to use panopoly distribution instead of separately installing the modules

How you can add this to existing site ?

https://drupal.org/node/1717728

Check out more on panopoly here.


Joining 2 uids in custom table with users table I have a custom table. Inside that table I have 2 uids.

Using hook_views_data_alter I know how to make a join with users table. My field is called also "uid".

The join looks like this:

    $data['ofertas_producto']['table']['join'] = array(
        'users' => array(
            'left_field' => 'uid',
            'field' => 'uid',
        ),
    );

    $data['ofertas_producto']['uid']['relationship'] = array(
        'base' => 'users',
        'field' => 'uid',
        'handler' => 'views_handler_relationship',
        'label' => 'Creador del Producto',
    );

As you can see the join defined in the first array has only one possible definition with the users table and one left field inside of it. So if I want to define another join with a second field "uid_2" it will override the first declared join.

Am I right? Thanks for your knowledge.

It will not be overridden. It will be another relationship. See the example at the API docs: https://api.drupal.org/api/views/views.api.php/function/hook_views_data_alter/7

See also the example here: https://stackoverflow.com/a/11103419/2467536


Assign a class to an element dependent on multisite domain? I need to have a special class for example for body element which will be showing me on which site from multisite installation I am in.
Here is a solution loading different css files but is there a way to have a simple class?

Well i decided to use different .css files with this code:

// Allow a site-specific user defined CSS file (useful for multisite installations):
// If a CSS file "local-[SITE].css" is residing in the "css" directory (beside "local.css"),
// it will be loaded after "local.css". SITE is the site's host name, without leading "www".
// For example, for the site http://www.mydomain.tld/ the file must be called called "local-[mydomain.tld].css"
global $base_url;
$site = preg_replace("/^[^\/]+[\/]+/", '', $base_url);
$site = preg_replace("/[\/].+/", '', $site);
$site = preg_replace("/^www[^.]*[.]/", '', $site);
drupal_add_css(path_to_theme() . '/css/local-[' . $site . '].css', 'theme', 'all');


Grouping Exposed Filters (using Better Exposed Filters) We have a view using Better Exposed Filters called Programs with an exposed filter on a taxonomy term "Level of Study". I'd like to group this so that the only values in the exposed filters are Graduate and Undergraduate.

I first tried to "group" the terms as follows

but then got errors as follows:

Warning: Illegal offset type in views_many_to_one_helper->ensure_my_table() (line 954 of /var/www/html/sites/all/modules/views/includes/handlers.inc).

I then tried to rearrange the taxonomy so that Graduate and Undergradute terms are parent to the others as follows:

Graduate
- MFA Degrees
- Professional Degrees
- Doctoral Degrees

Undergraduate
- Majors and Minors
- Modules
- Interdisciplinary Programs

And this still does not yield the desired result.

So I'm at a loss and opening up a bounty.

First I'd recommend adding a taxonomy term 'Graduate Interdisciplinary Program' to match the 'Undergraduate Interdisciplinary Program'

Assuming you have these taxonomy terms 'weighted' to their respective parent terms 'Graduate' and 'Undergraduate' you can proceed to configure your view.

Configure the filter criteria as follows:

Settings
Content:Has Taxonomy Terms
Vocabulary: Graduate/Undergraduate Programs
Selection Type: Dropdown
Depth: 1

Configure Filter Criteria
Tick - Expose this filter to Visitors, to allow them to change it.
Tick - Grouped Filters
Widget Type - Select List
Label - 'Area of Study'

Finally configure the table as you have it in your screen-shot ... ideally without the overlap of the term 'Multidisciplinary Program' ...


Populating a node reference field using PHP in Rules I have a rule which is triggered when a node is flagged. Currently, the rule loads some content (1) that has been referenced by a field on the flagged content. I have set the rule to create a new piece of content (2) and would like a node reference field on this new piece of content to reference content (1). I know there is a way to do this with PHP but am not sure of it...

Got one more...

I'm now trying to use rules to populate a select list field on a new piece of content. I need the value of the field to be the same as a piece of referenced content that's available to rules. Usually I would use tokens but as its a select list field there is nowhere for me to insert a token. I'm thinking some PHP would do the job, but I don't know where to start.

This should actually be pretty simple:

Create your rule for the event "A node has been flagged, under "NAME OF YOUR FLAG" and name your rule
Add an action of "Add new content" and click "Next"
Choose what you want the auto-created content's title to be (w/ or w/out tokens) and select what content type you want created and click "Save"
Add another action of "Populate a field", for the arguments configurations choose "new content type of CONTENT TYPE YOU CREATED" and for field, choose your node reference field and click "Continue"
Again on arguments change to "new content type of CONTENT TYPE YOU CREATED"
Open the fieldset titled: "Advanced: Specify the fields value with PHP code" and enter:

return array(0 => array('nid' => $node->field_NAMEOFYOURFIELD[0]['nid']));

Note: You can find the field names by going to admin/content/types and click "Manage Fields" on the content type you want OR you can do a print_r($node); on a node of that content type to see the node object structure

Now when you view your rule, you should see something like:

and whenever you use that flag, a new node will be created having the same reference as the node you flagged.


Two views blocks content synchronized I have two content types: "banner wallpaper" and "banner1".

I'm using two views blocks. The view "banner wallpaper" displays the content from content type "banner wallpaper" and "banner1" the content from "banner1".

I have two wallpaper banners and two banners1 content.

With format views slideshow, timer delay set to 0 and marked random option in view I successfully managed to display the two banner wallpapers by refreshing the page. That goes same for Banner1.

My goal is: when the first wallpaper banner is displayed, the first banner from banner1 to be displayed too. When I refresh the page the second wallpaper banner and the second banner from Banner1 will be displayed, so they will be synchronized.

For an example we have two brands that will wants to advertise in the website.

Green and Orange.

These two brands wants to have wallpaper banner and flash banner.
So, when Green wallpaper banner is displayed, the flash banner from Green has to be displayed too, not to be mixed with Orange. After refresh the wallpaper from Orange will be displayed and the flash banner from Orange too... I think I'm clear.

Is there any filter or sorting available to achieve this with views?

I would use a taxonomy to tag your content.

Create a taxonomy vocabulary (E.g.: Brand), add the two terms (Green, Orange), add a new field of "term reference" to your content types and tag the content.

Then in your views, you can add a "Contextual Filter" (in the advanced options) to get term_id from the URL, so both will show the same tagged content.

Note that I've set the Path component to be 2, that's because the term_id will be passed as 2nd argument on your URL (can be anything you want).

Don't forget to validate the value to be one from your vocabulary. That's on "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED", check the option "Specify validation criteria" > "Validator" = Taxonomy Term > Check your vocabulary from the list.

Then you need to set your view URL, so you can pass the term_id by the URL:

By doing all that, you should be able to go to your page, type http://yoursite.com/brand/term_id and your content should appear.


Testing if email was sent in Kernel test I am trying to write automated tests for a or that will sent an email on submission.
I can write the test to check for the presence of the entity that is created along side the email, but I also want to have my automated test check that the system is sending an email too.
The examples I can find seem to relate to Laravel and the use of spies to see if a particular class method is called, however I can't find any examples of how to do that in Drupal 8 and in my particular use case I am using the function _user_mail_notify() and not a class method.
Does anyone have an example of testing that emails have seen sent at all?

Look at core tests that utilize email. For example:

MailCaptureTest::testMailSend()
EmailActionTest::testEmailAction()

The tests demonstrate ways to inspect the plugin.manager.mail service for signs that mail was successfully sent.


How can I have multiple versions of the same form, in different pages? There is a default Drupal 7 form called "user_profile_form". I would like to show certain elements of this form on one page of my website, and then a different set of elements from this same form on another page.

Is there a way to either:

a) have multiple versions of the same form (keeping the same ID) or
b) clone the form and then modify it (there will be two different form IDs)

Can you point me in the right direction?

You can use hook_menu() with drupal_get_form() to use any form on any path (see Using a node editing form on a page that not a node edit page).

You can then use hook_form_alter(), and get that to work differently depending on the path.

You can use $_GET['q'] for the full path or arg() to get parts of the path. and use if() logic to determine how to alter the form.


List of Logged out users In using drupal 7

1 .Is there any way to get List of logged out users for last 30 mins?
2. can we track browser close ?

Yes you can, you can do it with views
go to admin admin/structure/views/view
create users views, add filter last acess -30 mintures,
you can import below views

$view = new view();
$view->name = 'logout_users';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'logout users';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'logout-users';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: User: Last access */
$handler->display->display_options['filters']['access']['id'] = 'access';
$handler->display->display_options['filters']['access']['table'] = 'users';
$handler->display->display_options['filters']['access']['field'] = 'access';
$handler->display->display_options['filters']['access']['value']['value'] = '-30 minutes';
$handler->display->display_options['filters']['access']['value']['type'] = 'offset';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'logout-users';


Standard practice for adding new fields to a table created by a contrib module I have to add a field to the webform table generated by the webform contrib module.

I was thinking about implementing the enable hook in the .install of a custom module in order to do this:

function mymodule_enable( ) {
  db_query('ALTER TABLE webform ADD COLUMN is_valid int') ;
}

But I don't know if this will generate problems if the module is disabled and enabled again in the future and tries to add the field (which would be already created by then).

Is this correct or is there a better way to do this?

Well, you could always use hook_update to generate a new field in the table. This gets executed when you do a database update.

It's even possible to use it in your own module.

http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_update/7


Programmatically get webform submissions of a specific nodes webform In Drupal 8 there is no function webform_get_submissions() as of this writing.

Webforms can be attached to nodes.
How to get all the submissions of a webform that belong to a specific node (e. g. node ID = 15):

webform_get_submissions_by_node_id() ... is the wanted function.

There are similar questions here but the PHP code to get only the submissions which where created on one specific node is different. And for this there is still now answer to find.

Thank you 4k4. Here is now the correct and full code for use in mytheme.theme file (we need the getData() function:

$storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$webform_submission = $storage->loadByProperties([
  'entity_type' => 'node',
  'entity_id' => $variables['node']->id(),
]);
$submission_data = array();
foreach ($webform_submission as $submission) {
  $submission_data[] = $submission->getData();
}


Form Submit Handler not firing on Page Reload with GET parameters I have a simple form

function example_form($form, &$form_state) {
  $form['#attributes']['method'] = 'get';
  $form['button'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  $form['search'] = array(
    '#type' => 'textfield',
    '#required' => FALSE,
  );

  return $form;
}

and a submit handler

function example_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
  drupal_set_message(t('Form Submitted'));
}

When I click the button, the form submits properly and the URL gets all the form parameters.

but when I reload the page with all those URL parameters, the example_form_submit() is not firing, how do I make my form submit/fire the submit hook when the URL is reloaded with GET parameters?

The correct way to change the method to be used by a form is to use the #method element rather than by setting the attribute, as otherwise the form API will still expect to be triggered by a POST.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#method


Hiding fields from RESTful services? So, this may be a stupid question because it seems pretty basic to me, but I can't find any information about this on here or elsewhere. Is it possible to specify fields to be visible/invisible to RESTful requests in Drupal 8? I would expect that this should be possible to configure--or, at the least, that fields hidden from the display would not be accessible via such requests.

Is this possible, or is there something that I'm simply not understanding here?

The only way to do this is using field access (hook_entity_field_access()) and denying view access to fields that you don't want to be visible.

The primary use case that the default rest.module/entity integration aims to support is data synchronization. My standard suggestion for anyone who wants to offer public services on a site or build a custom frontend is to consider writing and defining services tailored for that specific use case.

It's also quite possible that more flexible solutions will be developed in contrib, one of those is relaxed, I don't know if it helps with this specific use case, though.


How do I show/hide elements on a page using jquery? I am trying to hide check-box selectors in the custom search module when the page initially loads and then have a clickable link to show them. I have the clickable link working but the check-boxes are initially in a visible state. How can I hide the check boxes when the page/module loads? I tried placing the following code in my THEME_form_alter(&$form, &$form_state, $form_id) function

drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types")[0].hide(); });', 'inline');

and

drupal_add_js('jQuery(document).ready(function () { $("#edit-custom-search-types").hide(); });', 'inline');

But neither worked. Any help would be appreciated. thanks

the easiest way of adding custom javascript-snippets is to create a custom.js file in your themefolder and declare it in your theme.info file like scripts[] = custom.js. Add all your snippets there.

In your JS file you can hide the elements.
If you have multiple checkboxes create an array and hide them with a for each loop.

example

// create array with stuff you want to hide
    checkboxes = [
        '#checkbox1',
        '#checkbox2',
    ];

// Hide arrays
    for (i = 0; i < checkboxes.length; i++) {
        jQuery(checkboxes[i]).hide();
    }


User email verification link Is there a way to store/save the user verification email link in the database after a new user creates an account?

Yes, hook_mail_alter() enables you to alter any email messages sent out from hook_mail() if you know the specific key associated with the email. In this case, the key is user_register_no_approval_required. From that point, all you have to do is parse the email message body for the relevant URL and save it to your desired location.

function MYMODULE_mail_alter(&$message) {
  if($message['id'] == 'user_register_no_approval_required') {
    //@TODO: Parse $message['body'] for email verification link and save it
  }
}


Ajax Form Not Working in some Some Regions I created an ajax based contact form in my module.Then I made a block view for the form. I tried putting that block to several regions. When I put the block to 'Sidebar Second' the form works as desired.But when I put the same block to 'contact' Region (custom region) , the form's ajax part does not work .

This is the code I used to print the block .

$contact = render(block_get_blocks_by_region('contact'));
print  $contact;

When I inspect the element the form-id is 'myform' as given by me . Still the ajax part is not working .

I got the solution for this . Just want to tell  the answer for anyone who might come across this problem. The problem was :

I was printing it in html.tpl.php.

The solution is

print it on either page.tpl.php or page--xxxx.tpl.php and print it as

<?php
     print render($page['contact']);
 ?>


Using drupal behaviors for a Bootstrap carousel I created a custom front page using page--front.tpl.php, and I added a Bootstrap carousel on it which works fine, but the javascript I have (carou.js which is in mysubtheme'/js/carou.js') is not called. This is the Drupal behavior code.

(function ($) {
Drupal.behaviors.carou = {
    attach: function(context, settings) {
        $('#myCarousel').carousel({
            pause: false,
            interval: 3000,
        });
    }
}
})(jQuery);

I added it using the following code in the template.php file.

function bootstrap_subtheme_preprocess_page($vars) {
  if (drupal_is_front_page()) {
     drupal_add_css(drupal_get_path('theme', 'bootstrap_subtheme') . "/css/frontpage.css");
   //adding carou.js to front page
     drupal_add_js(drupal_get_path('theme', 'bootstrap_subtheme') . '/js/carou.js', 'file');
   }
}

I want to control the carousel options of pause: false interval:3000 but I was not able to do so. This makes me think the JavaScript code is not being called, and I don't know what is not right in the code. I am not also very well versed with Drupal behaviors.

What is wrong in my code?

Finally fixed it. I modified the code this way

drupal_add_js(drupal_get_path('theme', 'bootstrap_subtheme') . '/js/carou.js', array(
                                                                                'type' => 'file',
                                                                                'group' => JS_LIBRARY,
                                                                                'weight' => -1));

I added group and weight to it then then drupal.behaviors code had some few errors in the structure. The last line was})(jQuery);
But i fixed it to }(jQuery));


Drupal Commerce have customer choose how many items to buy I would like to give my customers an option of how many products to buy.
So I would like to have a page (or view) that gives the user the option to but 1, 3, or 6 items of my product each with a little more discount.
For example:
 1 for $3.50
 3 for $7.50
 6 for $10.00

And have those three options displayed next to each other.

Also, I would like to give the customer no other quantities. It is either 1, 3 or 6 items that they can buy.

Anyone knows how to do this?

You could just create 3 separate products in Commerce to represent each quantity. This makes sense especially if you only have a few like you describe. Each "bundle" product can have it's own SKU/model number, and it's own price. This also provides historical record, if you change your bundles in the future, you can keep the old SKU but archive it, and make a new one to represent your new pricing/quantities.


Is this correct usage of hook_node_view()? hook_node_view_alter(&$vars, $hook) {

  global $base_url;

  if($vars['#node']->status == 0) {
    header('Location: '.$base_url.'/?errCode');
  }
}

Simple hook to redirect unpublished nodes to prevent 404s (this is just a proof of concept).

Factor 1: There is already existing unpublished pages that have redirects (via the Redirect Module from Drupal Core) - this shouldn't affect that.

This is placed in my theme/template.php file but I'm not confident that this hook is best suited (although it works). Is there a lower level menu router hook which I can use?

Is there a lower level menu router hook which I can use?

Yes, there is - you would need to use hook_menu_alter() to achieve this. Here's the code you should use:

function YOUR_MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'YOUR_MODULE_node_page_handler';
}

function YOUR_MODULE_node_page_handler($node) {
  // If the node is unpublished, redirect the user.
  //
  // Note: I would recommend adding an extra check so administrators and
  // users who can manage the nodes are not redirected. This way, they can
  // work with unpublished nodes.
  //
  // This is what you would use instead in that case:
  // if ($node->status == NODE_NOT_PUBLISHED && !user_access('administer nodes')) {
  //
  // This will work for ALL users on the site, including the administrators.
  if ($node->status == NODE_NOT_PUBLISHED) {
    drupal_goto('<front>', array('query' => array('errCode' => 1)));
  }

  // Let the core node handler serve the request otherwise.
  return node_page_view($node);
}

Notes:

You should do this through a custom module instead of the theme.
Bear in mind that this might interfere with functionality of other modules, as well as workflows. See my comments and alternative version of the code.
Use drupal_goto() for redirection instead of setting the location in header.

Hope this helps.


Drush not seeing right CLI PHP version I am not able to get Drush to recognize the installed PHP 5.4.20 (cli).

$ php -v
PHP 5.4.20 (cli) (built: Oct 10 2013 18:41:48)

$ drush
Your command line PHP installation is too old. Drush requires at     [error]
least PHP 5.3.3.

I logged out and in. Any quick thoughts?

Have you just now updated your PHP than you may need to restart the apache and check if it works, and still if you get the above error than check Installing and Troubleshooting Drush.

One dirty hack of installing the drush is mentioned here: https://drupal.org/files/drush-document_env_var-1841324-25.patch. But I won't recommend you to use this as you are already having the PHP 5.4 and that hack for PHP version < 5.3.3


how to count results in a Calendar view? I enable the calendar module, then "Add view from template" on /admin/structure/views/add-template, but I cannot count nodes published at the same day in the month view by following this tutorial.
I want events occurred in the same day can be counted like "3 events occurred" other than the original output in the red box, and the counted field can be rewritten.

I tried aggregation feature of views, but no luck.

Finally, I get it working.
After I turn on View's setting "Show the SQL query", I notice there is an unnecessary GROUP BY field "nid" in the Calendar view, then I unset this field in a hook_query_alter(QueryAlterableInterface $query) as below:

if ($query->hasTag('views_' . $view_name)) {
    $fields =& $query->getGroupBy();
    unset($fields['nid']);
}


Adding pagination to nodes I'm using Drupal 7, CKEditor (not wysiwyg module). By default the nodes are not paginated but the client wants to have nodes of certain content-type to be paginated. And wants control of this pagination i.e. set page breaks.

How can I make the nodes to paged? And how can I control it?

P.S. I cannot find any  useful explanation (tutorial) of how drupal pager works, so if you know any, it's highly appreciated to post it here.

It is incredibly easy. Use BOOK content type. Just need to enable Books in core modules. If you already have lots of existing content (to much to copy/paste into book pages), you could add a field for Node Reference and link the pages that way.  Book has all that "pagination" functionality -- as well as local menu/index -- built in. Great solution if you aren't too far along.  At the very least, enable Book module and do a sample to demo for client -- to help you conceive the exact behavior that you want.

By the way, that approach is independent of your WYSIWYG (CKEditor).


How can I skip field validation if the field is hidden? I get a node form with node_form and then I render it with some modifications.

One of the modifications is that I duplicate the fields so I have the same fields twice. One field is disabled and the other same field is enabled, I also have a checkbox to show or hide the disabled/enabled field with #states. So I have only one field visible at time, for example, I have a disabled field visible, if I check the checkbox then disabled field is hidden and enabled field is shown.

The problem comes with the #requried = TRUE fields. When I submit the form it validates the two fields (enabled and disabled) but I only want to validate the visibile field. So, if it's visible the disabled field, I don't want to validate the enabled field.

What is a good way to achieve this?

I've tacked a variation on this before and this was the only solution I found that didn't have problems of some sort.

The key is not to skip all validation as you may add security holes so you have to specifically skip required validation. - Specifically what I'm getting at here is don't use #limit_validation_errors.

You cannot stop drupal core from validating that required fields are not empty, so you have to make the fields not required when they get validated.

Note that this example will make all fields not required, so you'll have to add some logic to only do that for the fields you are interested in.
I couldn't add this because I don't have enough info about your setup.

In your form add this:

  // Add an after build callback so we can modify the form before validation.
  $form['#after_build'][] = 'MYMODULE_form_after_build';

Then add that after build function and a helper function:

/**
 * Form after build callback.
 *
 * We are using this to modify the form after it has been submitted,
 * but before it has been validated.
 * This means we can remove required flags for certain fields.
 *
 * @param array $element
 *   An associative array containing the structure of a form element.
 *   In this case the form.
 * @param array $form_state
 *   The form state array.
 *
 * @return array
 *   An associative array containing the structure of a form element.
 */
function MYMODULE_form_after_build($element, &$form_state) {
  // Check that the form has been submitted.
  if ($form_state['process_input']) {
    // Deal with required fields.
    _MYMODULE_remove_required($element);
  }
  return $element;
}

/**
 * Make elements of a form not required.
 *
 * This example function will make all required fields not
 * required.
 * In your case you want to only do certain fields so you will have
 * to add logic in here to only affect some fields.
 * You could do this based on field name or some other flag you have
 * set, or whatever.
 *
 * @param array $elements
 *   An associative array containing the structure of a form.
 */
function _MYMODULE_remove_required(&$elements) {
  // Recurse through all children.
  foreach (element_children($elements) as $key) {
    if (isset($elements[$key]) && $elements[$key]) {
      _MYMODULE_remove_required($elements[$key]);
    }
  }
  if (!empty($elements['#required'])) {
    $elements['#required'] = FALSE;
  }
}


hook_views_query_alter all condition I have an exposed filter that shows products which have multiple entity references. The user should be able to pick some number of entities and the view should show entities containing all those references. In my mind that should mean changing the in operator on the where clause to an all operator.

function hook_views_query_alter(&$view, &$query) {
  if ($view->vid == 7) {
    dpm ($query);
    if (isset($query->where[1]['conditions'][2]['operator'])) {
      $query->where[1]['conditions'][2]['operator'] = 'all';
    }
    dpm ($query);
  }
}

However this seems to have no effect. the operator is changed from the first dpm to the second and it does break if I enter some other value in the all does not change the results. Do I have the wrong operator? Or am I going about this all wrong?

[edit]
According to Payou the function should look like

function falk_products_query_products_alter($query) {
  $conditions = &$query->conditions();
  $conditions2 = &$conditions[0]['field']->conditions();
  $conditions3 = &$conditions2[0]['field']->conditions();
  $my_query = &$conditions2[0]['field'];
  $my_conditions = &$my_query->conditions();
  dpm ($my_query->conditions());

  if (isset($my_conditions[2])) {
    foreach ($my_conditions[2]['value'] as $target) {
      $my_query->condition($my_conditions[2]['field'], array($target), 'in');
    }
  }
  dpm ($my_query->conditions());
}

Which at the dpm's give me arrays that look good to me but dont work if more than one value is input.

Altering a query like this is really not recommended.

First of all, you should use SelectQuery methods provided by "$query" variable.
You can get an array of query conditions by using "SelectQuery::conditions()" method.

Be careful, if you want to alter this array get the array like the following snippet :

$conditions =& $query->conditions();
//Now you can use and alter your query conditions.

Some others tips related to your code :

1) You can tag your query in Views UI

Add a tag to your Views Query :

With this trick you can define a special hook for altering all query who use this tag. This hook is "hook_query_TAG_alter"

Now you can use this code :

function YOUR_MODULE_query_my_tag_alter($query) {
  $conditions =& $query->conditions();
  //This condition is useless now
  //if ($view->vid == 7) {
  //Check conditions and do your updates

  //}
}

2) Careful to the module weight

When you alter something, other modules can do it too...
This order is determined by the module weight saved in the "system" table.

By using your own tags on your query, other modules should not know about this tag and should not alter your query.

You can change your module weight but this is not the thread of this post

Links

SelectQuery Api

SelectQuery::conditions() method

Query Alteration recommandations by Drupal

hook_query_TAG_alter

Change Module Weight


Where to put Commerce Kickstart translation po file? After installing a blank Commerce Kickstart site, I'd like install another language as default for the site.

I can see the language .po file to download -> here

Where should I put the .po files and how can I enable the new language as default?

The internationalization process is not unique to Commerce Kickstart; it is the same for all Drupal sites and handled by the Locale module.  The Drupal.org documentation can be found here.  (Start with Install a language.)


Node Reference input with HTML preview I am trying to show a multiple node reference input control that shows the title and an image of each node.

I have achieved it using Autocomplete Deluxe but it allows users to create new objects in the control itself which I cannot allow. I have also tried Chosen with a reference view but it strips all HTML before showing in the list.

Are there any other modules or techniques I could try to achieve this?

In my opinion that is the case for a View. You should prepare a view with the fields you want to display from referenced nodes.

Then install Entity Reference View Widget module. With that module you will be able to use your view to select the node references.


D7 update field in database problem function sms_user_delete($uid, $number = FALSE) {
  userfieldmobil_user_update($account->uid); // my custom field about users i call this manually.
  $query = db_delete('sms_user')
    ->condition('uid', $uid);
  if ($number) {
    $query->condition('number', $number);
  }
  $num_deleted = $query->execute();
}

function userfieldmobil_user_update($uid) { // i make it manually not able to update this
$num_updated = db_update('field_data_field_mobilnumber')
->fields(array(
'field_mobilnumber_value' => '',
))
->condition('entity_id', $uid, '>=')
->execute();
}

What i'm doing wrong sms_user delete OK but my custom field has value but not updated.

If you want to update your field when user was deleted you should put your update query into your sms_user_delete. Because userfieldmobil_user_update will only works if u update user data, not delete it.

function sms_user_delete($uid, $number = FALSE) {
  userfieldmobil_user_update($account->uid); // my custom field about users i call this manually.
  $query = db_delete('sms_user')
    ->condition('uid', $uid);
  if ($number) {
    $query->condition('number', $number);
  }
  $num_deleted = $query->execute();

  $num_updated = db_update('field_data_field_mobilnumber')
     ->fields(array(
     'field_mobilnumber_value' => '',
     ))
     ->condition('entity_id', $uid, '>=')
     ->execute();
  }

Its not like in drupal 6 where u can use hook_user, read about hook_user_update and hook_user_delete for more info.


Add a block to a render array I have a block I would like to add it to my renderable array (given to a page callback), with prefix and suffix - what's the cleanest way to do this?

I understand I can do it this way:

$markup = '';
if ($block = block_load('views','results_anonymous-block')) {
    $block_content = _block_render_blocks(array($block));
    $build = _block_get_renderable_array($block_content);
    $markup = drupal_render($build);
}

$content['page'] = array(

    '#markup' => $markup,
);

return $content;

But wondered if there was a better way (e.g. without rendering the block or using the private function).

Modules provide their block titles and contents through implementations of hook_block_view(). If you're looking for something similar to your posted code that doesn't rely on calls to private functions, what's below should give you a render-ready array that you can place anywhere within another render array.

$renderable_block_data = module_invoke('views', 'block_view', 'results_anonymous-block');
$renderable_block_contents = $renderable_block_data['content'];

Caveat: while the docs for D7's version of hook_block_view() suggest that the returned "content" key should be a render array, some modules/blocks may be implemented in such a way that they return plain HTML strings, in which case you'd need to put the content in a #markup element before adding them to your parent render array.

Further discussion can be found in this drupal.org post.


Display nodes that reference the same node than current page I have a Drupal 8.5.3 installation. I'm struggling to fix this, I have read many threads but none is exactly what I need, or at least I'm not being able to solve it:
I have 2 content types: A, and B. They both have an entity reference field that references to another content type, C.
I'm trying to create a block view to embed into any node of type A a list of B nodes that reference to the same C node that the current A page.

In other words:

Content type A: Cities

Content type B: Brands

Content type C: Countries

If node Rome (A) has a field that references to Italy (C), I'd like to display on it all the brands (B) that have also a field that references to Italy (C).

I have tried using relationships, contextual filters, providing default values from URL, etc. But I'm unable to make it work.
I've tried selecting my entity reference field as a relationship, and then adding a contextual filter of Content ID that uses that relationship. I have also tried some other combinations but it's not working.
I would appreciate some help!

Thank you very much!

It can be tricky to orient yourself around this, but it is a fairly common request to list sibling nodes according to whatever criteria (usually Taxonomy and Entity references).

The solution involving Entity references is to use two Relationships, one pointing to the common node (C), then another to point to the nodes that reference it (A) and then a Contextual filter that feeds the Views context on what node you're currently on (B).

Create Views listing your content A
Add a Relationship Content referenced from field_ref_C
Add another Relationship Content using field_ref_C, and set it to use the Relationship from the previous step field_ref_C: Content
Add a Contextual filter ID (from Content Category) and set it to use the second Relationship (field_ref_C the one from the previous step) with these options:
When the filter value is NOT available:
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria (optional)
Content
[your appropriate types - B]
Add another Contextual filter ID  but this time Do not use a Relationship:
When the filter value is NOT available:
Provide default value
Content ID from URL
More: Exclude

This will exclude the node you're currently viewing from the list.

If you want to check the output in Views Preview at this point enter the same node ID both times, for example to see what the block would output on node 14 enter 14/14.

The first argument is taking the current node of type B and navigating through the connections, to the country C and back to content A you want to show, the second argument is excluding the current node from the list.
Place your block in a region shown only on content B, don't forget to set the option Node from URL on block settings.