Setting up an exposed filter to only filter conditionally I am trying to build a D7 view, and I have the view correctly only showing results using a contextual filter, but I am trying to build one more filter (an exposed one), to drill down even more.

I have a list of students, each students assigned to different districts. A user is assigned to one (or multiple) districts, but should never be assigned to all (but could be). The contextual filter is checking the assigned_user field of the district using the logged in user, and that works.

I have the student and district relationship setup, and it pulls all data from both entities correctly.

Now I am trying to build an exposed filter so that the user can select which district they want to filter by, but ONLY list the districts they are assigned to. When using the 'expose filter' option on the district name, if I use 'Single Filter' it makes it a textbox instead of a select box, and if I use 'group filter', it makes a select box, but I have to manually put in each district.

I am trying to #1, get the exposed filter to be a select list,
and #2 ONLY the districts the user has access to (via the assigned_user contextual filter). The views UI doesn't appear to have a way to do this, so is it possible for me to write a hook to create the filter myself?

If the district is a term, entity reference, or a list field value, then you should be able to do this. Otherwise, You'll need to do something more involved (and honestly, at that point, you're probably better off just restructuring that data to work with views.

As far as only exposing options that will provide valid results, I'd recommend taking a look at Views Selective Filters (https://www.drupal.org/project/views_selective_filters). Be wary though, as the views_selective_filters module does an additional query, per selective filter as the view is loaded. Not a huge problem for 1 or 2 filters. But can start to cause performance issues if you're not careful.

Edit
The question as I (now) understand it: How do you change the options of a select list exposed filter based on an arbitrary value set against the currently logged in user?

First, hook into the exposed filter form and modify the district filter.

function mymodule_form_FORM_ID_alter(&$form, &$form_state) {
  $district_options = mymodule_get_district_options();

  if (!empty($district_options)) {
    $form['field_district']['#type'] = 'select';
    $form['field_district']['#options'] = $district_options;
  }
}

Next, you need to actually write mymodule_get_district_options().

function mymodule_get_district_options() {
  // Load the current user.
  global $user;
  $account = user_load($user->uid);

  // Default to loading all districts.
  $district_ids = FALSE;

  // Get the districts value from the loaded account.
  if (!empty($account) && !empty($account->field_districts)) {
    $district_values = $account->field_districts;
    foreach ($district_values[LANGUAGE_NONE] as $delta => $value) {
      $district_ids[] = $value['target_id'];
  }

  // Load the districts set on the current user, or ALL districts if none are set.
  $districts = entity_load('district', $district_ids);

  $options = [];
  if (!empty($districts)) {
    foreach ($districts as $district) {
      $options[$district->id] = $district->title;
    }
  }

  return $options;
}

Something along those lines should work. I haven't tested this.


How do I remove js from a specified page? How do I remove js from a specified page?

templates.php

You can use hook_js_alter()

function MYTHEME_js_alter(&$javascript) {
  if ($some_condition) {
    unset($javascript['path/to/script.js']);
  }
}


How to show messages starting with "Debug : " to an administrator only? I'm developing a lot of complex rules in D7 and for debugging reasons it is very handy to have different messages (the standard Drupal message) within the website. For this I use "showing a message on the site".

If a message of this starts with "Debug : " then I want it to only be displayed for the role of administrator. I do not want to add a condition to every message. That's is just to much.

How to achieve this?

Note: I wrote my first "Hello world" module last month, so I have a custom module in the site. I have to find the correct hook for this, so I looked into https://api.drupal.org/api/drupal/includes%21module.inc/group/hooks/7. But I cannot find a good hook for this.

Option 1: Use the Disable Messages module

Use the Disable Messages module for this. Here is a quote from its project page:

  Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Some of its features are:

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

Available for either Drupal 6 or Drupal 7 (and a DEV version for Drupal 8).

Option 2: Write your custom code

Use a variation of the approach as explained on Hook into and Preprocess Drupal Messages? Here is a quote from it:

  The following example hides all error/warning messages from anonymous users and user's who don't have the 'administer nodes' permission. You can easily add your own conditions to filter out which message types should be displayed to who.

function mytheme_status_messages ($display = NULL) {

  $output = '';
  foreach (drupal_get_messages($display) as $type => $messages) {

    // skip all error/warning messages for anonymous users
    if (!user_is_logged_in() && ($type == "error" || $type == "warning")) { continue; }

    // skip error/warning messages for users who don't have the 'administer nodes' permission
    else if (!user_access('administer nodes') && ($type == "error" || $type == "warning")) { continue; }

    ...


How can I see full server request to track suspicious requests? I have very bad luck with spammers. Even though I employ both reCAPTCHA, Spamicide and BOTCHA, I get about one spammer per day, though 300 are blocked. I guess that's a pretty good ratio, but it still justifies me having to manually authorize new user accounts.

My website gets about 30K requests per day (as per access logs) of which 500 are POST requests. It runs on Drupal 6, though we are soon moving to 7.

I want to be able to see what the spammer sends when they make the request. Ideally, I would like to see the reCAPTCHA challenge they saw and what they wrote down. I'll be good with only the postdata, though.

Is there a way to achieve this using triggered rules? Is there a module which will allow me to do so (i.e. send the full request to log/email?)

I can't think of a module that would do this for all the different anti-spam modules. I know that the CAPTCHA module implements this for its own fields.

An alternative is a simple custom module that implements hook_form_alter to target the the desired form, adds a new submit handler to the form and store the submitted information using watchdog.


How to use Search API with Solr? I am new to drupal , I have installed SEARCH API . I have opened an account with open solr and following the process suggested in https://drupal.org/node/2137651
since I am not using apache solr  search I am going to search api setting (last para in help )
the setup was succesfful and I was able to connect to solr server and infact was able to delete the index , However I am geeting the error message in config->search api->server as" You are using an incompatible schema.xml configuration file. Please follow the instructions in the INSTALL.txt file for setting up Solr"
I am also not able to index , it gives error 400
I dont know where I went wrong in follwing document of https://drupal.org/node/2137651
.I also copied the schema.xml from (open solr ) to drupal/sites/all/modules/search_api_solr/solr-conf/4.x

Any help is highly appreciated
Regards
Carol

Copy the schema.xml from the Search API Solr module into Open Solr. Also be warned that compatibility with 4.x is not stable, so consider using solr 3.x configuration instead.


My first module: db_select question I'm working on my first module, in this module I want to show a pager to two similar nodes. (Yes I know there are modules for this but it's more complex then the above but I kept it simple to make my question more clear). I'm completely new to making modules and the way de db_select works so I need some help with keeping my code clean and simple.

I have three tables I need information from.

Table 1: node
Table 2: field_data_field_issue (referenced node)
Table 3: field_data_field_order (order of nodes field)

First I need to get the current node id. For this I use the following code:

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);
}

Now I need to find the nid of the node the current node refers to. I have to do this in Table 2. So I use this query:

$subquery = db_select('field_data_field_issue', 'i');
 ->fields('i', array('field_ref_nid'))
 ->condition('entity_id', $nid)
 ->execute();
 return $subquery;

Third I need to find all nodes that have the same referenced node and order them by nid and order. So I'm going for a query with join:

$query = db_select('node', 'n');
$query->join("field_data_field_issue", "i", "n.nid = i.entity_id");
$query->join("field_data_field_order", "o", "n.nid = o.entity_id");
->fields('n', array('nid', 'title'))
->fields('o', array('field_order_value'))
->fields('i', array('field_issue_value'))
->condition('field_issue_value', $resultsubquery) //I don't know how to get the result in here?
->orderBy('nid') //First order by nid
->orderBy('field_order_value') //Then order by order
->execute();
return $query;

This is what I have till now. Things I didn't figure out yet and where I could use some help with are.

How to get the result of $subquery in $query.
Is this the way to do it? Is this clean enough and am I missing out
on something?
I need the two nodes next to the current node. So if the ordering is
(nid): 3,2,4,5,1,6,8,9 and I'm currently at node 1 I want to output
node 5 and 6.

Thanks in advance!

$header = array(
        array('data' => 'title',        'field' => 'title', 'sort' => 'ASC'),
        array('data' => 'cal name 1',   'field' => 'field_order_value'),
        array('data' => 'Cal name 2',   'field' => 'field_issue_value'),
    );

// $result = db_query("SQL here");

$rpt_data = array();

    foreach ($results as $key => $rpt_data1){
        $rpt_data[$key][] = 'Result item';
        $rpt_data[$key][] = $rpt_data1->product_title;
        $rpt_data[$key][] = $rpt_data1->stock_value;
    }

    if (count($rpt_data) == 0) {
        $output = t('
Record not found.
');
    } else {
        $per_page = 20; // Initialize the pager
        $current_page = pager_default_initialize(count($rpt_data), $per_page);  // Split your list into page sized chunks
        $chunks = array_chunk($rpt_data, $per_page, TRUE);  // Show the appropriate items from the list
        $output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page])); // Show the pager
        $output.= theme('pager', array('quantity',count($rpt_data)));
    }


How to pass an array from module to template file? I have an array printing in module file. I want to theme that array data,so I am not getting how can I get that array data in template file. I don't want to create theme function and all. is there any inline solution to pass from module to template. My code is like below.

$data['listfiles'] = array(
    '#theme' => 'table',
    '#header' => $filesheader,
    '#rows' => $rows,
    '#empty' => t('No content available.'),
  );

  return $data;

I want to pass $data variable to the template file, so that I can theme the data.Thanks in advance for any suggestions.

In form.

/**
 * Implements hook_theme().
 */
function YOURMODULE_theme() {
  $themes = array(
    'example' => array(
      'template' => 'templates/example',
      'arguments' => array('data' => NULL),
    ),
  );
  return $themes;
}

after this you can pass your data as

  return theme('example', array('data' => $data));

Refer this

And if want to use preprocess to alter data, see hook_preprocess_HOOK


Profile2 Registration Path loose registration field after translate URL alias I use Profile2 and Profile2 Registration Path module. This is the original Registration Path, set in the configuration.

I tried to translate the Registration Path at Administration » Configuration » Search and metadata » URL aliases.

But when i visit for example the Belgium dutch version, i loose my extra added Profile field at my Registration form (RIZIV number)?

Profile2 Registration Path module does not support multilingual URL aliases. Profile2 fields are added to reg form based on the alias that you set up on profile2 edit form. That is why your profile2 fields are not displayed on dutch version of reg form. Your best choice is to remove translated alias and set your original regpath alias to something that sounds good in both languages. Or you can improve the module by adding multilingual alias support (though it may require some reworking in module's logic).


MySQL date format functions in Drupal How can I do a MySQL date function in Drupal?
I have this now:

$select = db_select('someTable', 'st');
$select->addExpression('DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m")', 'createdMonth');

$date = $select->execute()->fetchAll();

When I run this I get an exception that says:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column '%Y-%m' in 'field list'"

But if I print the $select object I see it should run

SELECT DATE_FORMAT(FROM_UNIXTIME(created), "%Y-%m") AS createdMonth FROM {someTable} st

And when I copy this to Sequel Pro it just runs.

What am I missing?

You're a 'victim' of MySQL's ANSI_QUOTES SQL mode:

  Treat “"” as an identifier quote character (like the “`” quote character) and not as a string quote character. You can still use “`” to quote identifiers with this mode enabled. With ANSI_QUOTES enabled, you cannot use double quotation marks to quote literal strings, because it is interpreted as an identifier.

Emphasis mine.

That explains why MySQL is trying to find a column called '%y-%m' rather than interpreting it as a string.

So you need to switch your SQL mode to something else, or (more reasonably), just use single quotes for literals:

$select->addExpression("DATE_FORMAT(FROM_UNIXTIME(created), '%Y-%m')", 'createdMonth');

Many other DBMSs don't accept double quotes for string literals, so using single quotes is a good habit to get into anyway.


Create a field to type in name of body class I want to create a field where I can put in what will be a class on the body of the node that I'm creating.  The picture below depicts my local and live environments:

How can I do this?

Johan, if the only thing out of sync between your live and local environments are the node nids, you can do this with css like so:

/* this will target both and will work on both environments if the other nid
   does not exist in the other environment */

.node-page-1521,
.node-page-1497 {
  /* whatever CSS you need here */
}

as Drupal puts the class node-page-NID in the body of each page created for a specific node.  If the "other nid" exists in the local or live site, then you will have to get a bit fancier, but this does show that Drupal can target specific node pages.

Another way would be to use hook_preprocess_html() a custom module or theme, eg, something along the lines of:

function YOURMODULE_OR_THEME_preprocess_html(&$variables) {

  if (isset($variables['node']) && $variables['node']->nid == THE_NID_YOU_WANT) {
    $variables['classes_array'][]='SPECIAL_CLASS';
  }

}

Just realize the above snippet is dull ax; eg, you would probably want to do something better than just hard coding a nid in there, eg storing it in a variable specific to the machine (look into variable_get() and creating an admin form for your theme/module).

If it is something else, eg, you want to have a field that allows the user to somehow specify something special in the display about this (and other similar nodes), you can certainly do that as well above, eg, look at that field instead of the nid and then add a class if it has a certain value.


Create custom display of element using field values Lets say I have a Company content type that contains the following fields:

Company Name
Company Description
Company Logo Image
Company Website URL

I use the Entity Reference module to relate companies to Articles. When displaying an article page I would like to show the company logo which should link to the URL with the description on-hover. If I were using a view I'd do a rewrite for something like this:

[Company-Logo-Image]

[Company-Description]

How could I do something similar for the actual individual article page?

I assume you have an entity reference field "Company" in the content type "Article". You could implement hook_node_view() to achieve this on the individual article node page. Check the following example code:

function mymodule_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if( $node->type == 'article' ){
            // load the entity reference 'company' in full
            $company = node_load($node->field_company[LANGUAGE_NONE][0]['target_id']);

            $logo        = $company->field_logo[LANGUAGE_NONE][0]['uri'];
            $logo        = '';
            $website     = $company->field_website[LANGUAGE_NONE][0]['safe_value'];
            $description = $company->body[LANGUAGE_NONE][0]['safe_value'];
            // delete the default entity reference display
            unset($node->content['field_company']);
            // add the company logo to the node view
            $node->content['logo'] = array(
                '#markup' => l($logo, $website, array('html'=>TRUE))
            );
            // add the company description to the node view
            $node->content['tooltip'] = array(
                '#markup' => '
'.$description.'
'
            );

        }
    }
}

API reference for functions used in the hook.

node_load
file_create_url
l


Place the footer AND the copyright blocks at the bottom of the page responsive I installed Industrial Theme from Zymphonies and I am struggling to place the footer and the copyright (2 block layouts) at the bottom of the page.

So, on my website it looks like that.

I tried a lot of methods but I do not know how to deal with 2 containers simultaneously.

If you are indeed looking to create a sticky footer, not sure what option this particular theme gives you but the idea is the same with any drupal theme

Add both blocks to a region that you will dedicate for this purpose
if no available region exists you can just create a new one
using custom css on your theme you can make this specific region position: fixed but there are other ways as mentioned by No Sssweat


How to make a page look like it would have w/o tpl Say, for example, I want to customize the edit user page, so I have created a user-profile.tpl.php. Is there a way to echo out what the page would be normally? What variables should I have access to?

I have tried var_dumping $node, $form, $page, $content, and $user_profile and all but the last are null...

print render($user_profile); results in a list of profile fields, but not the edit-user page that I get without the tpl file.. (where you can change password, email, etc.

I'm curious for pages/nodes/etc in general, not just this particular one. It's an issue I always struggle with.

To see the array $var / $variable -

echo "<pre>";
print_r($var); //or $variable whichever is applicable.
echo "</pre>";

This will output the entire $var/$variable array in structured manner and you can find out all the data available in your tpl.

Hope that is of some help...


How to load some selected files in Media Browser I have a run time list of image files with their fid's. I am using Media module to handle image files. I want to load only specific set of image files fid's in the media browser on node add/edit page.

Please help me to achieve this specific stuff.

This is little bit tricky. Media browser generally opens all the files. So, when we present the file field in the front end, we need to pass file type (Even we can pass fids too, after uploading the files).

On the views side either using views_query_alter or a filter in the views we need to filter them out.

Using this scenario we can alter media browser files options.


How can a user select a different language to the site default language? My Drupal 6 site should always display in French for all users except me. I need to administer the site in English.

Using the Locale module I have both languages installed and default set to French. In the language negotiation settings ('Configure'), I have selected 'none'. The help text says that "users may (optionally) select a preferred language on the My Account page".

Even though I have selected English in my account settings (under "Language settings"), everything remains in French when I login?

Have you tried using the Administration Language module?

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).


Theming a views field with template Apologies if there is a good documentation out there, I searched and read other topics for over 30 minutes now, could not figure it multiple things with theming a field.
My objective is to customize a field inside a views called  field_calendly_url. I found the following field template. I have several questions;

Would I need to make changes with set classes, for example change field--name- to field--calendly--url?
How can print my field value, I tried {{ field.calendly.url }} and {{ fields.calendly.url }} but neither worked.
Do I have to keep the if statement for label even if I am not using a label?

`
{%
set classes = [
'field',
'field--name-' ~ field_name|clean_class,
'field--type-' ~ field_type|clean_class,
'field--label-' ~ label_display,
]
%}
{%
set title_classes = [
'field--label',
label_display == 'visually_hidden' ? 'sr-only',
]
%}
{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

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

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

      hello...
    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

<a href="javascript:void jQuery.colorbox({html:''})" class="btn-box">Request Meeting

`

In case anyone else will look for this later, I was able to display the views field value with the following.
{{ view.field.field_calendly_url.original_value }}


how can i specify in my migration not to migrate unpublished content? in a drupal 8 migration, is there a way to specify in the .yml that i dont want to migrate any content that is unpublished .  Or would that have to be done in a plugin?

You could try using the skip on value plugin.
Untested, but probably like:
process:
  status:
    plugin: skip_on_value
    method: row
    not_equals: true
    value: 1
    source: status

Should only import published content.


altering a block that is embedded in a view I have a view and in the header of the view, I am rendering a custom block. The block is showing up just fine, however, I need to alter it and I cannot seem to figure this out. I have tried hook_preprocess_block, hook_block_view_alter and a couple others. I know the ID of my block but it isn't helping.

If I am embedding the block in the view and I want to alter the block, do I need to first alter the view and tell it to rerender the block? I am using drupal 8. Any help would be appreciated.

I assume you're displaying a block_content entity.

That is not actually rendered through the block system, it's an entity, so you need to implement hook_block_content_view() (see hook_ENTITY_TYPE_view() for documentation)


Submitting a form with ajax, when multiple instances of the same form are on a page I am battling with D8 ajax right now, hoping someone can shed some light on where I'm badgering this implementation.

The goal is to update a value based on the on the state of a checkbox.  The issue seems to be that there are multiple instances of this same form on the page.  However, I've confirmed they all have unique build ids.  They do have the same $form['#form_id'], but I think that's to be expected, $form['#id'] is different.

Here is the code:

public function buildForm(array $form, FormStateInterface $form_state) {
  $widget = $form_state->getBuildInfo();
  /* @var $widget Factorywidget */
  $widget = current($widget['args']);

  if ($form_state->has('widget_id')) {
    $widget_id = $form_state->get('widget_id');
  }
  else {
    $form_state->set('widget_id', $widget->id());
  }

  $ajax = [
    'wrapper' => 'widget-toggle-status-wrapper',
    'callback' => '::ajaxRebuildForm'
  ];

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  $form['toggle_widget_status'] = [
    '#type' => 'checkbox',
    '#title' => 'Toggle Status',
    '#default_value' => $widget->field_widget_status->value,
    '#ajax' => $ajax + ['trigger_as' => ['name' => 'widget_toggle_submit']],
  ];
  $form['widget_id'] = [
    '#type' => 'textfield',
    '#default_value' => $form_state->get('widget_id'),
    '#title' => 'widget ID is',
    '#size' => 10,
    '#disabled' => TRUE,
  ];

  $form['widget_toggle_submit'] = [
    '#type' => 'submit',
    '#name' => 'widget_toggle_submit',
    '#value' => $this->t('Submit'),
    '#submit' => ['::widgetToggleSubmit'],
    '#limit_validation_errors' => [],
    '#ajax' => $ajax,
    '#attributes' => [
      'class' => ['js-hide']
    ]
  ];

  return $form;
}

/**
 * Ajax submit handler that will return the whole form structure.
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *     The current state of the form.
 *
 * @return array
 *   The form structure.
 */
public function ajaxRebuildForm(array &$form, FormStateInterface $form_state) {
  return $form;
}

public function widgetToggleSubmit($form, FormStateInterface $form_state) {
  $widget = $form_state->get('widget_id');
  $form_state->setRebuild();
  /* @var $widget Factorywidget */
  //$widget = FactorywidgetService::toggleFactorywidgetwidgetStatus($widget);

  //return new AjaxResponse();
}

Again, there are multiple instances of this form on the page.  I added in widget_id as a textfield just to see if the widget Id was correct.  When viewing the page, widget ID in the textfield is correct:

The problem is, no matter what toggle I click, the widget_id in $widget = $form_state->get('widget_id'); in widgetToggleSubmit is always the widget Id for the first form on the page.  I added a shuffle to the render array which displays these to confirm - it's always set to the first form on the page.

To, hopefully illustrate, this screenshot shows the Debugger for a breakpoint I put in widgetToggleSubmit at $form_state->setRebuild():

The toggle has been triggered for the widget with id 3, but $form_state->get('widget_id') will only return the value for the first form on the page.

You can do this by setting a custom form ID for each form. So you define your form like this:

class MyForm {
  protected $formId;

  public function __construct($formId) {
    $this->formId = $formId;
  }

  public function getFormId() {
    return 'my_form-' . $formId;
  }
}

Then, when you call your form, you pass a unique Form ID for each form:

$my_form = new MyForm('some-unique-id');
$form = \Drupal::formBuilder()->getForm($my_form);

Pass a different ID for each form on the page.


How do I get a field value in another field's template on a paragraph? I have a Paragraphs bundle that has 2 fields.  I want to have the value of the first field in the second field's template so I can combine it with {{ loop.index }} to make unique classes for a grid layout.

Is this possible using a preprocess function and a theme template?

For non-paragraph fields, there is a node object available in the variables of the field template, so you can put this in a field.html.twig file:

{{ element['#object'].machine_name_of_other_field.value }}


Automatically shorten URLs on website with other domain name that I own Yesterday I purchased the domain stps.me to be able to shorten URLs for my other website setups.co.

I found two modules, Shorten URLs and ShURLy, that were able to shorten URLs.

However, I can't find the option to use my own domain name, and therefore I'm asking you for help.

I know there's a free tool to make your own URL shortening service called Yourls, but I can't figure out how to implement this to Drupal to automatically shorten and display a URL when I upload new nodes.

Thanks in advance :)

Found this module, Yourls, that works exactly like I described above.


Write the value of a field as a css class to another field Could someone point me in the right direction to write the value of a field A to the css classes array of field B?

In my case I'm using a field collection (with text and file/image field, to make a sort of paragraph) and want to make a select field (with 4 preset options) so the node creator can choose if they want the file/image field displayed top, left, or right.

I don't really want to mess around with dynamic views or special formatters, just write the value of my select list to the class of the file/image field wrapper.

Here is some sample code to help you further which adds a class on a field (field_image) based on the value of another field (List field of type text) (field_alignment).

You will need to implement 2 preprocess hooks:

On node preprocess to retrieve the objects / values of the fields and add extra datamember which contains the class value
On field preprocess to retrieve the previously added extra datamember and merge it with the default classes_array part of a field

function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_image']) || !isset($variables['field_alignment'])) {
        return false; // if 1 of both fields is not available, don't do anything
    }

    $alignment = reset($variables['field_alignment']); // retrieve first item of array
    $variables['content']['field_image']['#extra_classes'] = array($alignment['value']); // add an extra datamember containing an array with the value of the other field
}

function YOURTHEME_preprocess_field(&$variables)
{
    $field = $variables['element'];
    if ($field['#field_name'] !== 'field_image') {
        return false; // only manipulate the image field
    }

    if (!isset($field['#extra_classes'])) {
        return false; // don't do anything if the array with extra classes is not available
    }

    $variables['classes_array'] = array_merge(
        $variables['classes_array'], $field['#extra_classes']); // merge the default field classes with the new added class
}

Update - When assigning class to field_image which sits within a field collection (named field_collection)

function YOURTHEME_preprocess_node(&$variables)
{
    if (!isset($variables['field_collection']) || !isset($variables['field_classes'])) {
        return false;
    }

    if (!isset($variables['content']['field_collection'])) {
        return false;
    }

    $alignment = reset($variables['field_classes']);
    foreach (element_children($variables['content']['field_collection']) as $index) {
         foreach ($variables['content']['field_collection'][$index]['entity']['field_collection_item'] as &$field_collection_item) {
              if (!isset($field_collection_item['field_image'])) {
                  continue;
              }

              $field_collection_item['field_image']['#extra_classes'] = array($alignment['value']);
         }
    }
}


determine custom templates in custom module hook_preprocess_page function I'd like to create a module that use a set of custom templates depending on http status code

Very well inspired by
Custom template for 404 error pages

Here is where i am so far

function my_module_preprocess_page(&$vars) {
  $header = drupal_get_http_header('status');
    if ($header == '404 Not Found') {
      //this
      $vars['template_files'][] = 'page__404';
      //or that
      $vars['theme_hook_suggestions'][] = 'page__404';
    }
}

in my module templates folder , i have created a

page--404.tpl.php

this template is not overtaken !?

EDIT :
i have also tried what's in there

function my_module_preprocess_page(&$vars) {
$header = drupal_get_http_header('status');
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'page__404';
}
}

function my_module_theme() {
  return array(
    'page__404' => array(
      'template' => 'page__404',
      'variables' => array('xxx' => null),
      'path' => drupal_get_path('module', 'my_module')
    ),
  );
}

function my_module_preprocess_page(&$vars) {
$header = drupal_get_http_header('status');
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'page__404';
}
}

function my_module_theme() {
  return array(
    'page__404' => array(
      'template' => 'page__404',
      'variables' => array('xxx' => null),
      'path' => drupal_get_path('module', 'my_module')
    ),
  );
}

thanks to sareed, drush vset theme_debug 1 allowed me to see :

<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--404.tpl.php
   * page--psnmssss.tpl.php
   * page.tpl.php
-->
<!-- BEGIN OUTPUT from 'my_module/page__404.tpl.php' -->

<!-- END OUTPUT from 'my_module/page__404.tpl.php' -->

so i changed page--404 to page__404 and it worked

how could i restrict the template suggestion only for the content region of the page ?


Unique product creation I'm trying to figure out the best way to create a product on Commerce 2.x.

What we have is physical products that don't have variation, so basically each product is a stand-alone.
What would be the best practice for creating a product?

Currently, I created (in this order):

Product Variation type (with fields that represent product properties)
Product type (where I select the variation type)

I didn't create any attributes though.

Would this be the right way of doing it?

Also for my second question, I created a Product list page with Views and selected Table view. However, I can't find "add to cart" field nowhere.

Sounds like you've configured the entities properly. Nothing requires you to make use of attributes, so if you don't need them, you don't have to make them. : )

Re: the field formatter for Views to display an Add to Cart form, it hasn't been developed yet.


Turn location CCK 'city' field into taxonomy autocomplete field I am using the "Taxonomize Location" module to automatically save all Location CCK Field submissions into the "location" taxonomy. Terms in the location taxonomy are saved in 3 layers: Country -> Province -> City.

The location CCK field offers Country and Province as select lists, and City merely as a text field. Is it possible to display the City field as an autocomplete field that pulls city suggestions from the third layer of my location taxonomy, depending on what Country and Province was selected?

What you can do is use hook_form_alter.
You will define an #autocomplete_path and use hook_menu to create a menu item for this path. In hook_menu, you will define a page callback. This will be a function that will return the list of cities from your taxonomy items.


How to provide a specific node template in a custom module I am using a custom module and using Bartik theme(from Drupal 8 core module) and hence need to define a content type specific template like node--[type].html.twig

I added hook_theme in my custom module as follows

function custom_autofill_reference_theme($existing, $type, $theme, $path){
   drupal_set_message($path);
   return [
    'node' => [
      'path' => $path . '/templates',
      'template' => 'node',
    ],
  ];
}

but not sure on how to add a content type specific template in a custom module without the need to create a custom theme?

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_content_type' => [
      'base hook' => 'node',
    ],
  ];
}

Then make sure that you have the content type template under custom/templates/node--custom-content-type.html.twig


Suppress VIEW on a specific URL There are two URL's on which I want to suppress a VIEW , Below are the urls's :

http://mysite.com/drupal/?q=searchpanel&body_value=
http://mysite.com/drupal/?q=searchpanel

How can I stop a view to appear on above link .

Thanks for any help in this!

Create the view and render it as a block, then go to block settings, set the view to show on every page except:

  drupal/?q=searchpanel&body_value=

  drupal/?q=searchpanel

Edit: Add the created view block to the content area where you want it to display e.g footer, content etc. it will show on every page except the pages above


How do I access the "#default_value" property from $form_state['values'] I am trying to get the "#default_value" property of a form element that is embedded in a fieldset.

The problem is that in my code I know the element name only, but I do not know the element fieldset in which it resides. Is there a mechanism to fetch that out without having to search up and down the $form array to find in which fieldset my element resides, and then getting it using $form['someFieldset']['myElement']['#default_value']?

The array indexes contained in $form_state are reported in Form generation.

The default values are only present in the $form array, which is passed as argument to the form validation handlers, the form submission handlers, and any implementation of hook_form_alter() (including hook_form_FORM_ID_alter()).

The only way to access the default value for a form field is to know the array structure of $form. If the code is using a form created from a module you are writing, that is not difficult; if the code is using a form created by a module you didn't write, you need to check the structure of the form array created by that module.


Drupal Mollie Payment no rules trigger We are working on a drupal ecommerce subscription service.

Modules: Commerce, Commerce Mollie, Payment etc..

Everything works 99%.

After finishing the payment the user needs to get the right role + a message.

This works with the default test creditcard payment.

But the commerce mollie integration module, is not triggering any rule after finishing the payment.

This is a real problem for us.

Screenshots:

UPDATE

https://www.drupal.org/project/mollie_payment
https://www.drupal.org/project/payment_commerce
https://www.drupal.org/project/payment

I would love any help, if there is information missing tell me!

Thank you guys.

You need to use event named order_paid_in_full.

the mollie module does not take of that, it just create the transactions.
(take a look at payment tab in the order)

So you have two options:

Create you own rule, based on the event above, and grant the user the role.
Use commerce_license module - it has a role module, and this is what you need.


How to show custom user profile fields in a view? In Drupal 7, I am using Profile2 (7.x-1.0-beta1) module to add custom fields like 'Author Name' etc to an user's profile page. How do I pull those custom fields in a view (7.x-3.x-dev)? All other custom CCK fields shows up in a view's selection list but not those added to an user profile page.

I fail to understand why anyone would use Profile2 (or Content profile) when users in Drupal 7 are fieldable.

From what I understand from the Profile 2 project page, it utilizes Entity API; you may need to use EntityFieldQuery Views Backend.


Using hook_menu in a custom module, how do you add a menu item to more than one menu in Drupal 7? I am working with Drupal 7.  I have created a custom module that supplies several menu items using hook_menu.  I am adding one of these menu items to the main menu:

$items['my-chapter'] = array(
    'title' => 'My Chapter',
    'page callback' => 'mymodule_my_chapter',
    'file' => 'includes/pages.inc',
    'menu_name' => 'main-menu',
    'weight' => '110',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

Adding the menu item to the main menu works fine using this code.  But I have a secondary menu that also needs this link.  Is there a way to add it to another menu in addition to the main menu I'm already adding it to?  Adding another $items['my-chapter'] will obviously just overwrite the previous one and the 'menu_name' only takes a single string.

Can anyone shed some light on how/if this can be done?  Thanks.

I'm pretty sure you are looking for menu_link_save() as adding the menu_name in hook_menu() just puts this callback in that menu instead of defaulting it into the navigation menu.  So, after creating it above, with or without the menu_name, you should be able to add it to any other menu(s) with menu_link_save().


Formatting elements without formatting similar elements throughout entire site So I've been fiddling around with elements, or blocks around my site.

I find the element or item I want to change my right clicking it in my browser and clicking "Inspect Element". Then, I find where the CSS file is and head to that directory in my FTP client. When I find the class or styling section, I copy that to my theme's global.css file.

However, when I edit some class/header/basically anything, any other object in my site that uses the same titled class is affected.

If my descriptions aren't very clear, here's my attempt at clarification. So let's say www.example.org/home has a H1 class that I'd like to center to the left. But there's an element over at www.example.org/aboutus that also uses the H1 class style. If I copy and edit the H1 class into my global.css file, both of those elements are affected, when I only want the one at www.example.org/home to be changed.

Is there a way to go around this? Should I try renaming the class that the element in www.exmaple.org/home so that it doesn't end up using the same class as everything else?

while writing your css for any html element you  need to be more specific. Suppose you are writing a css for an h1 tag which you want to get applied on that tag only , then be more specific by giving the h1 tag an id or class so that this css do not apply on other tags .More over you can alos filter your result as shown...
eg you have a h1 tag in your header region eg.

 Hello There i am in header tag region 1

 Hello There i am in header tag region 2

 How are you I am not in header tag

CSS
h1 {                            for last h1
color :red;
}
header #first h1 {
color:green;
}
header #second h1 {
color:blue;
}

..
output
Hello There i am in header tag region 1 and i will be green
Hello There i am in header tag region 2 and i will be green
How are you , i will be red
................
now if you write your css in this way..
h1 {
color : #262626 ;
}
then it will get applied to all the h1 tags...so you just need to be more specific
you can also filter the tags by using pseudo classes...
you can learn about the css specificity on these links...

http://www.youtube.com/watch?v=0ZOV-KTTI1E

http://www.youtube.com/results?search_query=css+specificity&oq=css+spe&gs_l=youtube.1.2.0l4.1505.7011.0.9461.7.7.0.0.0.0.247.1042.1j4j2.7.0...0.0...1ac.1._LOJTw6jxBA


Add rows inside added row I'm trying to create content type which can be used to add Workouts. Content type has fields: Exercise, Set and Reps.

First user chooses Exercise (this is autocomplete field). Then he can add Set(s) to thise exercise (unlimited amount of sets can be added). Every Set should be added by clicking Add new row. For every set user can add reps.

Then User can add second Exercise and sets and reps to it. Etc.

See picture:

I have tried to use Multifield -module, but it does not allow multifield inside multifield.

Any suggestions how to achieve this kind of functionality?


How to get the base path in JS I need the base path in my custom.js file. I have added this custom.js file in my MYTHEME.info file.

In custom.js file I'm trying to print

var baseUrl = Drupal.settings.basePath;
console.log(baseUrl);

Gives me empty value.

This variable Drupal.settings.basePath is provided by drupal.js, just make sure the page includes this js file.(right click view source code to check)

If this did not work, you can create your own variable and use it on the client side:

You can add your custom.js file into your file .info
scripts[] = custom.js or drupal_add_js(drupal_get_path('module','my_module'). '/custom.js');
Use preprocess function in a custom module

    function moduleName_preprocess(&$vars){
             global $base_url;
             global $user;
          drupal_add_js(array('moduleName' =>
      array(
        'basepath'=> $base_url,
        'another_variable' => $user->uid
           ),'setting');
        }

access the variable into your js file :

  var basepath = settings.moduleName.basepath;

that should be it!


Can You Use HOOK_node_builder() to Set Custom Node ID? Drupal 8.x

How do you set the node id in HOOK_node_builder()? Is it even possible?

There is a similar question here: Specifying a custom node id when creating new content, however it is a different approach or need.

MYMODULE.module:

function MYMODULE_node_builder($entity_type, NodeInterface $node, $form, FormStateInterface $form_state) {

    $node->setTitle('Node Title');

}

I am able to set the title fine. I am hard pressed to find any docs or posts on this hook.

There is no HOOK_node_builder, here are the available hooks in the Entity API.

I think hook_ENTITY_TYPE_presave is the one you are looking for.

function MYMODULE_node_presave(\Drupal\node\NodeInterface $node) {
  $node->nid->value = 5;
  $node->enforceIsNew(TRUE);
}

Here is the order of hooks and other events that happen during an entity save:

preSave() is called on the entity object, and field objects.
hook_ENTITY_TYPE_presave()
hook_entity_presave()
Entity is saved to storage.
For updates on content entities, if there is a translation added that was not previously present:

hook_ENTITY_TYPE_translation_insert()
hook_entity_translation_insert()

For updates on content entities, if there was a translation removed:

hook_ENTITY_TYPE_translation_delete()
hook_entity_translation_delete()

postSave() is called on the entity object.
hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
hook_entity_insert() (new) or hook_entity_update() (update)


How to deal with duplicate table name with db_select left join Basically I have a db_select that has two left joins.  And will be calling up two table fields with the same name.  The fields have different data though, so I need to be able to have access to both in my results.  In a normal query I’d set this in the SELECT - how can i do the same in db_select

SELECT table1.column AS column1, table2.column AS column2
FROM table1
LEFT JOIN table2
ON table1.column = table2.column

here's my code that i need to change

$query->leftjoin('migrate_map_emp', 'm', 'm.sourceid1 = i.ID');
$query->leftjoin('migrate_map_emplogo', 'ml', 'ml.sourceid1 = i.ID');

$query->fields('i', array('ID','Name'))
      ->fields('m', array('destid1'))
      ->fields('ml', array('destid1'));

[solved]

the above code works.  I did a 'drush_print_r'  on the rows returned at the second item is labelled ml_

[destid1] => 5
    [ml_destid1] => 2

Many thanks

You can fetch data with drupal db_select as below code:-

$query= db_select('table1', 'column1');
$query->join('table2', 'column2', 'column1.column=column2.column');

$query=$query->fields('column1',array('column'))
       ->fields('column2',array('column'))
       ->execute()->fetchAll();

For more information on db_select join queries click on this link


ImageCache or different CCK image fields? I'm setting up a website with lots of different image presets (probably up to five or six), so basically depending what page and what view my story teasers end up in they will have different dimensions, however, the web publishers need to have as much control as possible over the way the photos are cropped and resized. Is it better to use ImageCache or have different CCK image fields and have the publishers crop the images to their liking in an external image editor such as photoshop and then upload all of the presets to Drupal so the story can automatically display the right preset depending on what page and view displays it?

Also, is it possible to set up different presets for ImageCache depending on which view displays the image? Finally, it doesn't seem to me that imagecache offers cropping functionality per se. Am I correct?

Imagecache can crop. Exact or relative dimensions.

And yes, you can choose the preset for an image field in views. It is very easy. And you can manipulate it with code, but that would be much more complex. I don't think you need this.

If you really need the publishers to manipulate the image on the node edit form, just use IMCE. It integrates with Imagecache, so they could use that.

But the more you can automatize the process, the better.

So try to allow your publishers to send images the way they like (only being bigger than the minimum size you will ever use), and then you use imagecache dynamically to crop and resize the images the way you want over all the places on your site.


How to render specific form elements from the *.theme file I am using Drupal 8 and would like to customize how form elements are being displayed. Specifically, I don't like how uneditable, populated textfields are displayed as plain text. I would have it being displayed as an editable textfield (or have the text look like it is in an uneditable textfield). I have looked at various hook functions to try and achieve this but nothing seems to work.

I figure the best way to go about this is if I can render the form fields individually myself and then create a twig file that displays the individual fields as I would like them to be displayed. Here is what I would like the twig field to look like:

  {{ form.mail }}

  {{ form.message }}

  {{ form.actions }}

This is what I came up with so far:

function theme_preprocess_form(&$variables) {

  $elements = $variables['element'];
  foreach($elements as $key => $element) {
    if (substr( $key, 0, 1 ) !== "#" ) {
      // $variables['form'][$key] = render[$element];
      // This is where I need the code to actually render the element
    }
  }

}

What is the function I need to call to return a fully rendered form element?

To clarify, I would like to accomplish this by only using they my_theme.theme file for my_theme.

Thanks.

The base hook form from the question is for rendering the HTML form tag. To render single form elements you need to specify a separate custom template.

1. Register the custom template in a theme hook

mytheme.theme or mymodule.module:

/**
 * Implements hook_theme().
 */
function mytheme/mymodule_theme() {
  return ['entity_moderation_form' => ['render element' => 'form']];
}

2. Add the custom template to the form

While building the form

EntityModerationForm::buildForm():

  public function buildForm(array $form, FormStateInterface $form_state, ContentEntityInterface $entity = NULL) {
    ...
    $form['#theme'] = ['entity_moderation_form'];
    return $form;
  }

or to an existing form in a form alter hook:

mytheme.theme or mymodule.module:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mytheme/mymodule_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#theme'] = ['entity_moderation_form'];
}

You can skip this step if you use as template name the form id, see the comment from @BradJ.

3. Use the custom template to style single form elements

entity-moderation-form.html.twig:

{{ attach_library('content_moderation/content_moderation') }}

{{ form.current }}

{{ form.new_state }}

{{ form.revision_log }}

{{ form.submit }}

{{ form|without('current', 'new_state', 'revision_log', 'submit') }}

The example is from the core module Content Moderation.


How to restrict field formatter to selected fields? I created new field field_csob_srcode in my custom code:

<?php
$field = array(
'field_name' => 'field_csob_srcode',
'type' => 'text',
'settings' => array(
  'max_length' => 4,
),
  );
 field_create_field($field);
?>

I would need to create custom formatter for this field. I am using such implementation of hook_field_formatter_info

<?php
function mymodule_field_formatter_info() {
  $info = array(
'csob_webpay_description' => array(
  'label' => t('SRCODE - text description'),
  'field types' => array('text'),
  'description' => t('Displays text description of message from CSOB GP     WebPay'),
),
  );
return $info;
}

It works ok, but now, I see my new formatter as option at all fields settings, which have type = 'text'. Is it possible to restrict using of formatter, not only by field type, but also by field?
When I try to set field in hook_field_formatter_info:

'field types' => array('field_csob_srcode'),

then it does not work, formatter disappears from options in field display settings.

EDIT:  I have not problem to set formatter for my field, I just need to restrict formatter ONLY for my field. So other text fields cannot use my formatter. So the formatter will not appear as option in selectbox, when selecting format for display

Use default formatter in your field implemention

$field = array(
  'field_name' => 'field_csob_srcode',
  'type' => 'text',
  'settings' => array(
  'max_length' => 4,
  ),
  'default_formater' => 'csob_webpay_description',
);

it should works.


is there a safe way to convert a pressflow website to drupal 6? I have a website that was built on Pressflow, and the client wants to upgrade it to Drupal 7.

Is there a way to convert Pressflow to Drupal 6?

Pressflow and Drupal are API compatible, so you can simply replace Pressflow with the equivalent version of Drupal core. The only snag may come if someone has used private Pressflow functions in their module code on the site - but this is highly unlikely.

To upgrade, you can follow the normal upgrade path, which is to go to the highest version of Pressflow first, then upgrade to Drupal 7 or Pressflow 7.


How to add margin between columns with Drupal Bootstrap View Grid I need help I'm trying to add some margin between columns using drupal Views Bootstrap module the grid view but the columns are closed together. How can I add margin between columns. I have tried through the module settings but there isn't any option to. How can I achieve this?

You can use only CSS for this, look for the columns classes and then add it in a CSS file that is loaded on your page.


How to force node.status=0 I need to force the status value of a node=0 when the user has a certain role.

I've made

 function mymodule_node_save($node){
    if($node->type=="mytype") {
        global $user;
        if(in_array("simple",$user->roles)) {
            $node->status=0;
        }

    }
}

But the status is always saved as 1. What am i doing wrong?

@redhatlab is correct about Drupal 7 not invoking hook_node_save(). If you need to be sure the status is effectively set to 0, without other modules to alter it, I would use code similar to the following one.

function mymodule_node_insert($node) {
  mymodule_update_status($node);
}

function mymodule_node_update($node) {
  mymodule_update_status($node);
}

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_insert' || $hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_update_status($node){
  if ($node->type == 'mytype' && in_array('simple', $GLOBALS['user']->roles)) {
    $node->status = 0;
  }
}

The code checks the roles assigned to the currently logged-in user. If you want to check the roles assigned to the node author, you should use $node->uid to load the user object of the node author. It is then generally preferable to check the user has a specific permission, rather then checking which roles are assigned to the user.

node_save() first invokes hook_node_presave(), and then hook_node_insert(), or hook_node_update(). The code I wrote would allow your module to be the last one changing the node status.

References

node_save()
hook_module_implements_alter()


How to get a custom field label in a specific language? In order to get the label of a field I just do :

$fii = field_info_instance('node', 'field_app_area', 'products');
$label = $fii['label'];

But it returns the label in the original language of the field, not the current user language.

I have seen some code here to get the translated label from the $content variable of a node template, but I don't have the template variables available.

So my question is either : how do I get the label translation or how do I get the $content (or similar) variable available without being on a template.

Turns out that using t(), doesn't work for translated field labels.

To get the translated field label text (in the current language), just use the i18n_field_translate_property function

  $field_instance = field_info_instance('node', 'field_application_area', 'products');
  $label = i18n_field_translate_property($field_instance, 'label');

Or, for a specific language :

  $label = i18n_field_translate_property($field_instance, 'label', 'fr');

Found on this related answer.


Custom module administration page template not working I've been trying to load a custom template for a custom module page in the administration section, but the template isn't being loaded. This is the code so far:

custom_theme.module

/**
 * Implements hook_menu().
 */
function module_custom_menu() {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    $items['admin/module-custom'] = array(
        'title' => 'Turnos',
        'description' => 'Custom module functionality',
        'position' => 'right',
        'weight' => -15,
        'page callback' => 'system_admin_menu_block_page',
        'access arguments' => array('administer site configuration'),
        'file' => 'system.admin.inc',
        'file path' => drupal_get_path('module', 'system'),
    );

    $items['admin/module-custom/availability'] = array(
        'title' => 'Captación de disponibilidad',
        'description' => 'Users availability functionality',
        'page callback' => 'user_availabity',
        'access arguments' => array('administer site configuration'),
        'type' => MENU_NORMAL_ITEM,
    );

    return $items;

}

/**
 * Implements hook_theme()
 */
function module_custom_theme($existing, $type, $theme, $path) {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    return array(
        'user_availability' => array(
            'variables' => array('users', NULL),
            'template' => 'module-custom-admin',
            'path' => $template_path
        )
    );

}

/**
 * Load user availability
 */
function user_availabity() {

    $users = entity_load('user');
    return theme('user_availabity', $users);

}

module-custom-admin.tpl.php

Template subtitle

    <?php foreach ($users as $key => $user) : ?>

            <?php print_r($user); ?>

    <?php endforeach; ?>

But the template's code isn't shown:

Thanks for any advice.

It is a well known issue of the hook_theme() function.

For successfully loading the template file, you have to follow the naming convention to rename the template name, which must be same as the theme key, with converting _ to -.

/**
 * Implements hook_theme()
 */
function module_custom_theme($existing, $type, $theme, $path) {

    $template_path = drupal_get_path('module', 'module_custom') . '/templates';

    return array(
        'user_availability' => array(
            'variables' => array('users', NULL),
            'template' => 'user-availability',
            'path' => $template_path
        )
    );

}


How might I create a "step-by-step process" content type? I'm thinking about creating a process manual for an intranet. Most (all?) of the processes have a very clear order, although the actual order may change from time to time. The plan is to have the subject matter experts, probably a half-dozen or so, enter and update the process pages. The users of the site need to be able to quickly review the processes while interacting with customers, often face-to-face.

Here's the options I've thought of:

Train the authors to use ordered lists. Pro: easiest for me. Con: relies on training non-technical people, could be hard to style for readability.
Organize each process into a book. Pro: uses something that's already there. Con: harder to enter, complicated to read.
Create a content type with a "step" field that could be entered unlimited times, and theme so as to show the order number. Pro: easy to see that each step is independent, can be reordered easily (?) Con: more work for me (I feel like there something else in this option that I'm missing, but I can't put my finger on it!)
Custom module, something like the Recipe module but w/out ingredients. At least I'm assuming the Recipe module has step-by-step directions. Pro: most customization for entry, learning experience. Con: a LOT more work for me, kinda out of my expertise.

From your experience, is there a clear winner among these options?

Is there an option I'm missing? (is there a module out there that already does this, for example? Googling this concept was a nightmare.)

Am I over-thinking this?

I don't know yet whether this project will be Drupal 6 or 7.

I agree with Craig Hyatt but I thought I'd expand a bit more.

Train the authors to use ordered lists - Like you said it's more effort for you to train users. Your times better spent developing the final product in my opinion.

Organize each process into a book - Why re-invent the wheel? It provides you with the basics of your requirements out of the box. Using this will give you the extra time spent developing something to work on the cons of using this, or better put you get to spend more time adding helpful stuff than building it from the ground up.

Create a content type with a "step" field - You mention that this could be more work for you but it's not a huge amount, using CCK and nodereference this could give you a bit more flexibility compared to the book route.

Custom module - There's no need to do this, the above two points will give you enough freedom to code around drupals inbuilt options.

The clear winner for me would be to create a content type and build around that. You can actually set up a content type to use book functionality as well which is what I'm currently doing for a large project. So in this case you get the best of both worlds.


How do you export configuration from configuration module I need to include the configuration that I track in configuration modules into my install profile or however I will allow so that it will be initialised on install. How do I do this?

Enable Configuration Management UI submodule

Goto yoursite.com/admin/config/system/configuration/migrate

There is links for Export & Import


How to execute rules action programatically Is it possible to execute a rule action upon form submission? I've created a rule and disabled it, so it'll be only called if it meets the condition I've set. Below is a sample code I've been using:-

function hook_form_FORM_ID_alter(&$form, &$form_state) {
  if ($form_state['values']['field_name'][LANGUAGE_NONE][0]['value'] == 1)
    rules_invoke_component('rules_uncheck_update_checkbox', $form_state['commerce_order']);
  }
}

Not sure what are the other options as I've been stuck to make it work. Please help. Thank you.

EDIT:

Rules export

{ "rules_uncheck_update_checkbox" : {
"LABEL" : "Uncheck checkbox",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entity" ],
"ON" : { "commerce_order_update" : [] },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_update_checkbox" } }
],
"DO" : [
  { "data_set" : { "data" : [ "commerce-order:field-update-checkbox" ], "value" : "0" } }
]
}
}

rules_invoke_component is used to invoke a Rules Component.

In your case, it seems like you should invoke a Rules Event, using rules_invoke_event.


Entity reference selection by view I have two content types, Location and Offer. The Offer type has an entity reference field that points to one or more Locations.

A user of my Merchant role may create Location and Offer nodes. When creating an offer, they need to select from the list of Location nodes that they created.

I created a view with an "Entity Reference Source" display to build the Merchant's list of Locations when creating Offers. I limited the Locations to this Merchant by a relationship between author (of the Location) and currently logged in user.

Now, I need Administrator users to be able to edit Offers. The problem is that the view creates a list of the Administrator's Locations instead of the author Merchant's Locations.

How can I supply a list of entities to the locations entity reference field that is the current user's Locations when an Offer is being created and the author's Locations when an Administrator edits?

You are probably looking for a way to pass a contextual filter from the current page to the entity selection view.

Currently an argument can sadly only be static.

However there is a patch that allows you to add an argument using a token provided by the current page you are on.

You can find the patch here: https://drupal.org/node/1699378#comment-6809760


How to get fields values in an override file? I am writing a field override tpl file, in which I want to sum up two INT fields to one INT field.
In the file I tried the code:

$sum = $field_one + $field_two;

The problem is that I get an a notice that Drupal doesn't know what are these variable ($field_one, $field_two). I tried using "field_get_item", but I didn't succeed. I guess I use it wrong..
Can someone help me get these two fields to my override .tpl file.

How can I get these fields and calculate?

Thanks.

If you look at the comment in the beginning of the template file you're overriding, you should notice that it lists the variables available for any override code.

For instance, in field.tpl.php (used as starting point for overrding field templates), you should see the following line inside that comment:

* - $element['#object']: The entity to which the field is attached.

This gives you the name of the global ($element['#object']) to examine to look for the values of the fields.

Now, you need to look "inside" this object to figure out how to access the values of these fields.  To do so, the Devel module is what you need, so install and enable this for your (test) site.

Then put the following near the top of your template override file:

<?php dpm($element['#object']); ?>

When you look at the page again as administrator (clear cache and reload if necessary), there should be a Krumo accordion in the message area that expands this object. Expanding it will tell you how to get to the value of each field present in the entity.  For instance, it may tell you that the value of field_one is $element['#object']->field_one['und'][0]['value'].

Now, you should be able to extract and add the fields, e.g.:

<?php
$field_one = $element['#object']->field_one['und'][0]['value'];
$field_two = $element['#object']->field_two['und'][0]['value'];
$sum = $field_one + $field_two;
?>

Disable Devel and delete the call to dpm() on a production site.


How can I get the current widgets name of a node? I'd like to know if it is possible to get the current widgets of a node ?

field_info_widget_types() shows all the widget

But I'd like to get the widgets the current page is using and not all of them :(

Is there a way to to it ?

Thanks

From the docs of field_info_widget_types() :

Returns information about field widgets from hook_field_widget_info().
Parameters:
$widget_type: (optional) A widget type name. If omitted, all widget types will be returned.

You might be leaving the parameter empty. Hence, it is returning all field widgets. Pass the name of the widget from the current node, to get the right information. You can use menu_get_object() to get the node object of the current page, and find the appropriate widget to pass to field_info_widget_types().


How do I include my library on the page? I have an Angular app I want to use as a Drupal 8 theme but when I try to attach it with a YAML file, Drupal doesn't register that any JavaScript is being added to the theme.

ng.libraries.yml

base:
  version: 8.x
  css:
    css/styles.09e76a721be8ced0c439.bundle.css: {}
  js:
    js/inline.6375acbd4540ff168f58.bundle.js: {}
    js/polyfills.62cd0a749311c6ac36ca.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}
    js/vendor.d8949c111a4a3560f92d.bundle.js: {}

However, when I reference the script locations directly in my template, it works fine:

html.html.twig

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Hand of Death</title>
    <link href="themes/ng/dist/styles.09e76a721be8ced0c439.bundle.css" rel="stylesheet" />
  </head>
  <body>
    <app-root></app-root>
    <script type="text/javascript" src="themes/ng/js/inline.cad96cf6be5b6cfb5176.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/polyfills.62cd0a749311c6ac36ca.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/vendor.d8949c111a4a3560f92d.bundle.js"></script>
    <script type="text/javascript" src="themes/ng/js/main.665799e3572bc9816ad1.bundle.js"></script>
  </body>
</html>

From what little I can make sense out of the docs, somewhere I'm going to have to call Drupal.behaviors.myBehavior, but that would not actually work in my situation.

Is there a way to get JavaScript to work without hardcoding it in the template?

EDIT: I've reverted this to the original so the corrections make sense to future users and went ahead and opened a new question with the most recent code.

So you defined a custom library that includes CSS and JavaScript. This is done by creating the ng.libraries.yml file and adding the base library definition.

Next, you need to tell Drupal to include this library and attach it to all the pages, if your ng theme is used for rendering the output. You can do so by adding a libraries section to your theme's ng.info.yml file:

libraries:
  - 'ng/base'

After clearing your caches, the library should be included.

Additionally, you may want to have a check for the syntax of the .libraries.yml file. CSS inclusion should follow the syntax:

css:
  theme:
    css/styles.09e76a721be8ced0c439.bundle.css: {}

Observe the theme part.

EDIT:

After you also added your html.html.twig template, another issue seems a missing js-bottom-placeholder tag. It will be replaced by any JavaScript that is not attached to the head region:

<js-bottom-placeholder token="{{ placeholder_token }}">


How do I alter webform values before submission? I am trying to add some values to a hidden field in my webform before submission. Is there any hooks to access webform submission in Drupal 8? I tried How do I modify a webform submission field right before it is saved? without luck.

The answer linked is mostly right, just a couple of updates to get it working. In a custom .module add:

use Drupal\Core\Form\FormStateInterface;

function MODULENAME_form_alter(&$form,$form_state, $form_id) {
  if ($form_id == 'FORMID') {
    $form['actions']['submit']['#validate'][] = 'MODULENAME_form_validate';
  }
}

function MODULENAME_form_validate($form, FormStateInterface $form_state) {
  $form_state->setValue('hidden_id', 'Value for Hidden field');
}


How to get acces to XML tag attributes via XPath parser settings? I need to parse XML attributes via Feeds Importer XPath parser

exitsting XML tag structure is:

<MunicipalUnion Id="2a1c7bdb-05ea-492f-9e1c-b3999f79dcbc" Name="Moscow" TypeMU="city"/>

If i write @Id, @Name, @TypeMU, result is:

Solution is:
using Xpath string() function

string(@Id)

string(@Name)

string(@TypeMU)


Memcache Slowing Down Drupal Running seige (load tester) without memcache enabled I see stats similar to this:

Transactions:                    560 hits
Availability:                 100.00 %
Elapsed time:                  59.42 secs
Data transferred:               6.25 MB
Response time:                  1.56 secs
Transaction rate:               9.42 trans/sec
Throughput:                     0.11 MB/sec
Concurrency:                   14.71
Successful transactions:         543
Failed transactions:               0
Longest transaction:           10.57
Shortest transaction:           0.00

Notice that I'm getting about 560 transactions in 60 seconds, 9.42 trans/sec.

When I enable memcache (using the PECL memcache module) and re-run siege I see much worse performance:

Transactions:                    133 hits
Availability:                 100.00 %
Elapsed time:                  59.94 secs
Data transferred:               1.34 MB
Response time:                  6.43 secs
Transaction rate:               2.22 trans/sec
Throughput:                     0.02 MB/sec
Concurrency:                   14.27
Successful transactions:         129
Failed transactions:               0
Longest transaction:           12.22
Shortest transaction:           0.00

Notice that I've decreased my performance significantly. I was only able to process 133 hits in 60 seconds and the throughput is 2.22 transactions per second.

I have memcache setup on its own dedicated system with 4GB of RAM and here are the parameters:  memcached -d -p 11211 -u memcached -m 2560 -c 2048 -P /var/run/memcached/memcached.pid

I noticed that if I go to /admin/reports/memcache I get the following PHP errors:

Notice: Undefined variable: stats in dmemcache_stats() (line 244 of /www/sites/all/modules/memcache/dmemcache.inc).
Warning: Invalid argument supplied for foreach() in dmemcache_stats() (line 244 of /www/sites/all/modules/memcache/dmemcache.inc).
Notice: Undefined variable: stats in dmemcache_stats() (line 263 of /www/sites/all/modules/memcache/dmemcache.inc).
There are no statistics being reported for this bin.

I'm not sure if that's related to the issue or not?

This is what I have in settings.php:

/**************************************************
 * MEMCACHE
 **************************************************/
// the path to the core cache file
include_once('./includes/cache.inc');
// the path to the memcache cache file
include_once('./sites/all/modules/memcache/memcache.inc');

$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array(
        'memcache.domain.local:11211' => 'cluster'
);

$conf['memcache_bins'] = array(
        'bin1' => 'cluster'
);

$conf['memcache_key_prefix'] = 's-drupal';

Why is memcache slowing down my site instead of speeding it up? Would switching to PECL memcached help?

The errors on the stats page are due to an unrelated issue with memcache reporting. I think the problem you have is with the conf setup. I believe it should be like this for a default set up where all tables are mapped to the same bin:

$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['memcache_servers'] = array(
    'memcache.domain.local:11211' => 'default'
);

$conf['memcache_key_prefix'] = 's-drupal';

If that doesn't do the trick you can explicitly code the mappings for each table:

$conf['memcache_bins'] = array(
  'cache' => 'default',
  'cache_filter' => 'default',
  'cache_menu' => 'default'
);

etc.


Why is my Rules Component not being scheduled accurately? My aim is to send an email to new students at certain weeks after admission. E.g week 28, week 32, week 45.

I set up components with action to send email.

I configured a rule with event: after saving new content type(student).

The content type has a field - date of admission.

I scheduled component evaluation based on the offset of 'date of admission'.

So for example:

Date of admission: 02/03/13 (March 2nd 2013)

Offset: 224 days

However when the rule is triggered and I go to admin/config/workflow/rules/schedule, I noticed that the scheduled date is 16/10/13 rather than 12/10/13.

Please how can I resolve this?

When scheduling a Rules Component, you specify a value within Scheduled evaluation date. One of the options to do so, is to specify Relative dates like "+1 day", as mentioned within the Rules UI:

  ... any other values in GMT known by the PHP strtotime() function (like "+1 day")

As per your "offset = 224 days", I'm assuming you used a value like "+224 days".

However since you want to schedule the Rules Component a certain number of weeks after admission (like "week 28, week 32, week 45."), try to specify Relative dates like "+28 weeks", "+32 weeks", "+45 weeks". That might help for the Rules Scheduler to show a more accurate date.


Navigation within html.tpl I want to be able to put my Navigation block within the html.tpl.php, as it isn't going to change across any of the pages and it just seems like a more efficient option.

I know that I can't render a block using regular regions - so how do I go about doing this?

I'm using Nice Menus for my Navigation.

Thanks.

Basically this involves moving a region to html.tpl.php

So first you need to create a region to go in html.tpl.php which will hold your menu (unless you're using an existing region). Then create a preprocess in your template.php file:

function THEMENAME_preprocess_html(&$variables) {
  if ($blocks = block_get_blocks_by_region('REGION_MACHINE_NAME')) {
    $variables['REGION_MACHINE_NAME'] = $blocks;
    $variables['REGION_MACHINE_NAME']['#theme_wrappers'] = array('region');
    $variables['REGION_MACHINE_NAME']['#region'] = 'REGION_MACHINE_NAME';
  }
}

You need to replace THEMENAME with the name of your theme. Also replace all instances of REGION_MACHINE_NAME with the machine name of your region. The machine name can be found in your theme's .info file. Then all you need to do is put:

print render($REGION_MACHINE_NAME);

in your html.tpl.php (of course replace $REGION_MACHINE_NAME with the name of your region, I've only caps'd it to make it visible, it should all be lowercase otherwise)


How to set readonly or locked a select webform field? I want to lock a prefilled select webform field but no option is provided by the UI.So I think to do that programmatically.

Actually I do in a hook_form_alter:

$form['submitted']['discipline_du_poste']['#attributes'] = array('readonly' => 'readonly');

and this doesn't effect...what's wrong ?

Not sure how much this is a helpful answer, but was looking for a recipe to do this and found this example using a simple little hook_form_alter (which happens to be for civicrm components in a webform but think the principle is what counts)

$form['submitted']['civicrm_2_contact_1_fieldset_fieldset']['civicrm_2_contact_1_relationship_relationship_type_id']['#disabled'] = TRUE;


Admin user is unable to login I've just changed the view of login form to Drupal default view. Now I am not able to log in as administrator.

I have tried to change the password using php .\scripts\password-hash.sh newpwd.  I got an hashed password, I used to update the password stored in the database with a SQL query, but still I am not able to log in. I have also cleared entries from flood table.

Any help will be appreciated.

Please check if you are using the correct username (you can see that
in the database).
Try to use the "Forgotten password" function to reset your password
Check the last entries of the watchdog table to see if you can get
more information from there
Check your server logs to see if you get any error there (under Linux
this would normally be somewhere under /var/logs).
Install drush and use that to very easily log in
(https://drushcommands.com/drush-7x/user/user-login/)


How can I print the number of the current pager in Views template? I have a node View with pager configured Paged output, full pager, Items per page：30

So the view lists only 30 nodes per page.
Now I would like to print the number of the current page and the total number of pages on views template page-my-view.tpl.php.

For example, "2 / 10" when the current page is the 2nd one and the total number of the pages is 10.

How can I do this?

Global: Result summary is what you're looking for.

Simply add it into your HEADER or FOOTER wherever you need and then you're requirement is done.

$view = new view();
$view->name = 'demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Demo';
$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'] = 'Demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$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'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Footer: Global: Result summary */
$handler->display->display_options['footer']['result']['id'] = 'result';
$handler->display->display_options['footer']['result']['table'] = 'views';
$handler->display->display_options['footer']['result']['field'] = 'result';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$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: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Author uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'node';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'Author UID';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

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

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';
$handler->display->display_options['inherit_exposed_filters'] = TRUE;


Solution for user account activation? By some chance would a module exist for this registration / user activation workflow?

I'm looking for a module the following functionality:

Each user when registering has a dropdown to select their sales representative
The sales rep will then get an email regarding this user's registration
Since this sales rep knows that they're a user they'll approve this user quicker than a single administrator

Essentially, the user has the ability then to delegate who approves their account improving account approval efficiency (the goal).

Also, could this functionality be accomplished with rules somehow?

The solution for this is three modules.

http://drupal.org/project/token_profile

and enabling the core module profile.

Add any custom fields for a sales rep. Then enable rules. Rules will take any tokenized field based on certain events.


multiple sites use one apache solr server I am a beginner of using Apache Solr. I made a mistake two weeks ago.
I link two of my sites to one Apache Solr server. One is dev site, another is live site. There are some different data between these two sites. But I forgot to set "read only" on dev site.

Right now, everything is messed up. The dev site data shows on live site. How can I fix this? I tried to fix, but still no luck.

My fix steps:

Download Apache Solr Multiple Search on my dev site.
Set Apache Solr Search index access as "Read only"
Reindex all queue on my live site
Wait two days
Check the live site, still messy

I really appreciate if anyone could help.

apachesolr_multisite allows you to tenant multiple Drupal sites in one Solr search core, allowing searching across sites, or on single sites, but it must be configured. Go to admin/config/search/apachesolr/settings, click "Edit" on the Solr search environment, and examine the settings at the bottom of the form:

These must be configured properly for your use case.


Salesforce Connection I am currently getting an error when trying to connect Drupal 8 with Salesforce. This will be the first time I am hooking into Salesforce from Drupal and I am not entirely sure what I am doing wrong. I am using the Salesforce Suite Module.
I get the following errors while creating a new authentication provider? (Not on a local environment so Salesforce can see the URL.)

Notice: Undefined property: Drupal\salesforce_jwt\Plugin\SalesforceAuthProvider\SalesforceJWTPlugin::$credentials in Drupal\salesforce\SalesforceAuthProviderPluginBase->getCredentials() (line 194 of modules/contrib/salesforce/src/SalesforceAuthProviderPluginBase.php).

Warning: openssl_sign(): supplied key param cannot be coerced into a private key in Firebase\JWT\JWT::sign() (line 209 of /home/client-name/vendor/firebase/php-jwt/src/JWT.php).

OpenSSL unable to sign data

Does anyone know where I could start looking or can provide insight into what these errors mean? I have been stuck on this a few days and I can't seem to find anything helpful yet in my research.
The undefined property makes me think that I may be missing a dependency; however, this is a complete guess.
Thank you in advance.

I have fixed my issue and am putting the answer here.
There were two issues that I needed to address:

The database was using RDS on AWS and I needed to enable the "log_bin_trust_function_creators" parameter group
Add TRIGGER privilege for database web user

I hope this helps someone else out there with a similar issue.


REST export for nested lists of content Ok here is my problem;

I have a list of boats. Each boat have a list of engines that can be fitted to it. Engine is not in anyway coupled with boat as a particular engine can be mounted to any kind of boat.

Boat is a content type, Engine is a content type. Boat has a field of multiple engines in it.

I want this to output in json like this:

[{
    "title":"boat_name",
    "engines":[{
                 "title":"engine_name",
                 "model":"model_nr"
               },{
                 "title":"engine_name2",
                 "model":"model_nr2"
               }]
}]

I've tried to accomplish this through the RESTful web service module by creating a REST export view, but there is no formatter that seem to give me json output. I've understood that you could accomplish this by using View Field View but in my case it would require the engine to have a reference to a specific boat, am I right? That is not really what I want.

Is there any other way I can accomplish this?

You can create a custom Normalizer to use and Views will respect that. Within that, you can create the output structure however you like.

Here is an example class, where "Collection" is the content type:

<?php

declare(strict_types = 1);

namespace Drupal\mymodule\Normalizer;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\node\NodeInterface;

/**
 * Class CollectionNormalizer.
 *
 * @package Drupal\mymodule\Normalizer
 */
class CollectionNormalizer extends ContentEntityNormalizer {

  /**
   * The interface or class that this Normalizer supports.
   *
   * @var string
   */
  protected $supportedInterfaceOrClass = [
    'Drupal\node\NodeInterface',
  ];

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function supportsNormalization($data, $format = NULL) {
    if (!is_object($data) || !$this->checkFormat($format)) {
      return FALSE;
    }

    if ($data instanceof NodeInterface && $data->getType() == 'collection') {
      return TRUE;
    }

    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $attributes = [];
    $attributes['id'] = $entity->id();
    $attributes['title'] = $entity->label();
    $attributes['summary'] = $entity->get('field_summary')->value;
    $attributes['card_type'] = $entity->get('field_directory_view')->value;
    $attributes['list_image'] = NULL;
    $attributes['url'] = Url::fromRoute('entity.node.canonical', ['node' => $attributes['id']])->toString();

    $media = $entity->get('field_featured_image')->getValue();

    if (!empty($media)) {
      $item = $this->entityTypeManager->getStorage('media')->load($media[0]['target_id']);
      $image = $item->get('image')->getValue();

      $attributes['list_image'] = [
        'src' => ImageStyle::load('collection_listing')
          ->buildUrl($item->image->entity->getFileUri()),
        'alt' => $image[0]['alt'],
      ];
    }

    return $attributes;
  }

}

You also have to declare it in your modules services.yml file:

  mymodule.collection_entity:
    class: Drupal\mymodule\Normalizer\CollectionNormalizer
    arguments: ['@entity_type.manager']
    tags:
      - { name: normalizer, priority: 10 }

You can inject whatever other services you need, used entityTypeManager as an example.

Views will use this instead of the default, so long as the priority is higher. IMO this is far easier than trying to use the Views UI to get the output you want from a REST Export display. You are free to construct the output in whatever way you wish.

So in your case, you would replace "Collection" with "Boat" and check that the content type is 'boat', then build the response as you need it.


Display additional fields from included content with Entity Reference field I'm building a site in Drupal 8 using a content type for products, and I want to show for each product, some "Related Products" that are set in an entity reference field called field_related_products.

Each related product wants to show the title and link (as the field works by standard), but also include the product image and price (defined in fields against each piece of content).

Is there a way to alter the output of the field to do this?

I've seen also that views might be a route to take, but can't seem to get contextual filters to work - the closest I've come is displaying all content that is included as a "related product" throughout the site, which feels a large portion of the way there, but whatever combination I try with contextual filters/default values, it just seems to remove all my results.

Thanks for any advice.

You can achieve this by setting a view mode (recommended: Teaser) in the node display for the entity reference field at /admin/structure/types/manage/[CONTENT_TYPE]/display, and then adding the price and picture fields to the Teaser display of the referenced entity.

If the referenced entity is also a node then it would have a similar path of /admin/structure/types/manage/[OTHER_CONTENT_TYPE]/display/teaser. The path would be different if it is not a node, but should be easily found for most custom entities through the UI under the commonly named entity page 'Manage Displays'. Once there view modes can be selected at the top of the page for editing them.


How to migrate core profile fields into the new profile fields in D7? Premises:

I´m trying to upgrade a big D6 site to D7.

I have the content profile module installed.

I have a few core profile fields that I need to keep.

The "profile" node that was created by the content profile module, has no fields in it. I just used in order to manage in a better way the theming and presentation of profiles.

I´ve installed Profile2 module. I´ve installed the profile page submodule that comes bundled with it.

My 2 problems:

1. I would like to export or convert all those core profile fields into the new entity fields in D7. How may I do that?

2. In the meanwhile (in case number 1 is just not possible at all), I´ve tried theming the profile2.tpl.php file, trying to print into it my old core profile fields.

I´ve followed the instructions to print those core profile fields, so I´ve harcoded this print check_plain($account->profile_nombre); into the template, but it doesn´t print the name of the user that´s inserted into the nombre field (core profile field). So, how may I theme the profile page?

I´ve watched this video tutorial also, about the profile2 module, but I´m still absolutely clueless on how to manage profiles in D7 when you already have a couple thousand users with core profile fields in it.

Please note that I´ve tried using the "migrate" module, and the "drupal 2 drupal" migration module, with no luck.

Thanks for your help and insight!

A good solution might be to use Feeds module (to import to fields) and Views Data Export Module (to export fields to the spreadsheet). The procedure would be:

  Setup a view that lists all of your users and displays all of the
  fields you want to migrate. Then add news display (data export) and
  choose CSV format.

  Use feeds to import the data to D7. Just map each exported field to a
  new field.

  This might seem complicated at first, but it's really simple and
  should work.

Thanks for your reply, take2. Thought it would be good to post it here.


Autopost is not working I want to autopost the contents in facebook.I installed Drupal for Facebook module and created Apps in facebook.

In this,the user can connect facebook.But the content doesn't get autopost.
I got an error like this

"Something went wrong while posting update to your facebook wall. The error has been captured by watchdog".

How to clear this error.

Your error says your application has been deleted. Go to https://developers.facebook.com and check your application under the "Apps" tab. If the app exists, check that your oauth details (on the drupal site) match. If the app doesn't exist, create an app (also under the "Apps" tab) and validate against that in your Drupal site's oauth settings.