Custom view sort plugin not working only when used in table sorting We have a view of committee memberships (= custom entity). The committee memberships hold references to the committee and the politician and have a field "role". In a view we want to output all committee memberships in a logical order: chairperson first, the vice chairperson, foreperson, spokesperson and member. As you can see alphabetical order is not suitable.
We defined a custom view sort plugin which is playing nice on simple views where the sorting is set in the views configuration. However on a table view when selecting the column for the sorting by role it is not called.
Examples:

https://www.abgeordnetenwatch.de/bundestag/19/ausschuesse/1-untersuchungsausschuss-terroranschlag-auf-dem-breitscheidplatz - the sorting is correct
https://www.abgeordnetenwatch.de/bundestag/19/ausschuesse/1-untersuchungsausschuss-terroranschlag-auf-dem-breitscheidplatz/tabelle#filterbar the committee members are sorted by last name by default (we will change this)... when you click on the last column heading "Rolle im Ausschuss" it should be the same order as the first example. But it is sorted by the key of the role stored in database. "Stellv. Mitglied" has the key "alternate_member" in database that is why these members come first in this table

We defined the plugin in the following way in a class extending EntityViewsData:
$data['committee_membership']['committee_role']['sort']['id'] = 'sort_committee_membership';

The plugin is that:
/**
 * Sort handler for sorting committee memberships by list key position.
 *
 * @ingroup views_sort_handlers
 *
 * @ViewsSort("sort_committee_membership")
 */
class SortCommitteeMembership extends SortPluginBase {

  public function query() {
    $this->ensureMyTable();
    $field_storage = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('committee_membership')[$this->field];
    $allowed_values = array_keys(options_allowed_values($field_storage));
    $formula = 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map(array(Database::getConnection(), 'quote'), $allowed_values)) . ')';

    $this->query->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_' . $this->field . '_keys');
  }

}

Is there something missing which is needed to implement when the sorting is exposed?!

The problem is that for click sorting it seems that not the view sort plugin is used but the field handler which holds a method clickSort
So here is the solution:
1.) I defined a custom field handler. This can be done in hook_views_data or hook_views_data_alter. I did it in my custom views EntityViewsData extending class:
$data['custom_entity']['committee_role']['field']['id'] = 'committee_role';

2.) Then I defined the field handler class where clickSort can be overwritten.
use Drupal\Core\Database\Database;
use Drupal\views\Plugin\views\field\EntityField;

/**
 * @ingroup views_field_handlers
 *
 * @ViewsField("committee_role")
 */
class CommitteeRole extends EntityField {

  public function clickSort($order) {
    // No column selected, can't continue.
    if (empty($this->options['click_sort_column'])) {
      return;
    }

    $this->ensureMyTable();
    $field_storage = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('committee_membership')[$this->field];
    $allowed_values = array_keys(options_allowed_values($field_storage));
    $formula = 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map(array(Database::getConnection(), 'quote'), $allowed_values)) . ')';

    $this->query->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_' . $this->field . '_keys');
  }
}

After clearing the caching the results in the table are sorted the same way as in the other view. Strange that there is an additional sorting logic in views when a table display is used and the sorting is done via column headers.


Is it possible to replace page arguments with new ones in a view exposed filter? I'm creating a views filter with the exposed form.

After its submitting a new page is loaded with arguments like these (I use the Acquia Dev desktop)

http://pal.dd:8083/en/cities?country_id=2&region_id=4

I want to make the string shorter, for example, like this

http://pal.dd:8083/en/cities?geo=2_4

And in the query() method transcribe this argument and get country and region value from it.

I'm wondering, is it possible to do it inside the view filter class?

I tried to manipulate with the values of the exposed form in the submitExposed function, but I didn't manage to achieve the positive result.

Has anybody run into it?

You can adjust the default Filter identifier for each Exposed Filter in its settings. The Description:

  Filter identifier
  _
  This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.

In your case you can chage the first one to geo and the other to _. That way you get the output:

cities?geo=2&_=4

although you'd probably name the second one to something more meaningful, like region:

cities?geo=2&region=4

For full control use the module Query Parameters To URL (Drupal 8 version Needs work).


Code for module weight does not work I have two modules about login forms. Want to give weight to them , but my code does not work. I put this in template.php, maybe I missed something. I restart mysql, but it does not help.

$weight = db_select('system', 's')
      ->fields('s', array('weight'))
      ->condition('name', '[commerce_checkout_redirect]', '=')
      ->execute()
      ->fetchField();

  // Set our module to a weight 1 heavier, so ours moves lower in execution order
 db_update('system')
    ->fields(array('weight' => $weight + 1))
    ->condition('name', '[redirect_after_login]', '=')
    ->execute();

Eliminate the square brackets from the query and it should work:

$weight = db_select('system', 's')
  ->fields('s', array('weight'))
  ->condition('name', 'commerce_checkout_redirect', '=')
  ->execute()
  ->fetchField();

// Set our module to a weight 1 heavier, so ours moves lower in execution order

 db_update('system')
    ->fields(array('weight' => $weight + 1))
    ->condition('name', 'redirect_after_login', '=')
    ->execute();


How to add some JavaScript functions before Ajax begins How do I add some JavaScript functions before Ajax begins, with FAPI?

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Upload',
  '#ajax' => array(
    'callback' => 'ajax_submit_key_dump'
  ),
);

"beforeSubmit" handler attached that way will be executed right before Ajax request:

(function ($) {
  Drupal.behaviors.ReplaceWithAnyTextYouWant = {
    attach: function (context, settings) {
      // 'edit-submit' is the element ID where you execute the #ajax.
      Drupal.ajax['edit-submit'].options.beforeSubmit = function(form_values, element_settings, options) {
      // If cancel is clicked, do not continue submitting.
      if (!confirm('Are you sure you want to continue?')) {
          return false;
      }
    }
  };
})(jQuery);

You could perform some pre-submit validation of the user input, and even cancel form submission by returning false

Here is a good example

'edit-submit' - is the element html ID of submit button with '#ajax' settings. 'edit-' prefix is attached to the key of your form array item containing triggering element (submit button in your case).
For $form['my-submit'] = array(...), html ID of the resulting button will: "edit-my-submit".

JS file with code shown above, could be attached to your form in form constructor:

$form['#attached']['js'][] = drupal_get_path('module', 'your_module') . '/js/file.js';


How to make custom blocks print unsanitized markup Goal: I like to create a block to display phone no and a link as shown below:

Structure > Block layout > custom block > Add custom block, added this:

When I go to my site, I see this:

How can I create a block based on my above goal?

Update 1

Full HTML shows no CKEditor

FULL HTML > Configure shows this:

Block:

My page still shows html code:

TWO solutions:

1.-in text formats, disable WYSYWIG in full-html format, you are looking HTML tags because of this.

2.-write your code in plain-text format, select 'plain-text' write code, when done, do choose full-html and save your block.

in other words, do not write code inside WYSYWIG.


How can I render a view in different languages during queue process, using PHP? I am putting views into emails using a Drupal 7 queue of user ids.

In the queue, I load the view and attempt to render it after switching $GLOBALS['language'] to the user's language, and then back.

However, only the first view is rendered with the correct language.

The rest are all English.

_switch_language($language);
$view = views_get_view($view_name, TRUE);

if (!is_object($view)) {
  _revert_language();
  return FALSE;
}

if (!empty($display_id)) {
  $view->set_display($display_id);
}

_impersonate_user($account);

$view->pre_execute();
$view->hide_admin_links = TRUE;
$output = $view->display_handler->execute();
$view->post_execute();

_revert_user();
_revert_language();

Language switching function:

function _switch_language($new_language = NULL) {
  global $language;
  $language_original = &drupal_static(__FUNCTION__);

  if (!isset($new_language)) {
    if (isset($language_original) && (!empty($language_original))) {
      $language = array_pop($language_original);
    }
  }
  else {
    $language_original[] = $language;
    if (is_string($new_language)) {
      $languages = language_list();
      if (isset($languages[$new_language])) {
        $language = $languages[$new_language];
      }
    }
  }

  return $language;
}

The user switching function is similar, but calls drupal_save_session() twice to disable and re-enable session saving.

Any ideas? Thanks. :-)

I do not yet understand why, but $view->preview($display_id, $args) allows the language-switching to work.

It is very similar to my view execution code above, but instead of calling execute() on $view->display_handler, I call preview() and that works as desired.

$view->pre_execute();
$view->hide_admin_links = TRUE;
$view->preview = TRUE;
$output = $view->display_handler->preview();
$view->post_execute();

I generate the view for each $user->language and insert that into the email.

Perhaps this will help someone else.


How to get the correct 'base hook' to override a template file in a custom module? How can I find the 'base hook' to override a template file using a custom module?

'node' and 'user' are pretty straightforward, but others can be a little more elusive.

Example code...

MYMODULE.module:

/**
 ** Implements hook_theme().
 **/
function MYMODULE_theme($existing, $type, $theme, $path) {
  return [
    'username' => [
      'template' => 'username',
      'base hook' => 'how do you get this?',
    ],
  ];
}

Look into the *.module file where the base hook is defined, in this case the User module. The base hook is the key of the template definition:

user.module:

/**
 * Implements hook_theme().
 */

function user_theme() {
  return [
    ...
    'username' => [
      'variables' => ['account' => NULL, 'attributes' => [], 'link_options' => []],
    ],
  ];
}

Then in your *.module file

mymodule.module

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'username__mymodule_template' => [
      'base hook' => 'username',
    ],
  ];
}

Start the name of your own hook  with the base hook and double underscores.


Add a class retrieved from a sibling field to responsive image I have a Profile paragraph type that has the following fields:

Profile Image [Responsive Image Field format]
Profile Headline [Plain Text]
Profile Description [Plain Text]
Rounded Profile Image [Boolean]

What I'm trying to do is that when the field_rounded_profile_image boolean is selected, that it will add the rounded-circle class to the image attributes of the field_profile_image field.

Currently, this is what the code for the image looks like when it is printed:

  <picture>
    <source srcset="/sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&amp;itok=WLlku9ED 1x, /sites/default/files/styles/profile_large/public/paragraphs/image/profile/image1.jpg?h=74e1741d&amp;itok=WLlku9ED 2x" media="all and (min-width: 992px)" type="image/jpeg">
    <source srcset="/sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&amp;itok=p2VQAa0P 1x, /sites/default/files/styles/profile_small/public/paragraphs/image/profile/image1.jpg?h=74e1741d&amp;itok=p2VQAa0P 2x" media="all and (min-width: 768px)" type="image/jpeg">

  </picture>

I'm trying to write a preprocess hook to do this but this part of my Drupal game is lacking so I was wondering if anyone could help me out.

I've tried something along the lines of the following to no avail:

// Note that me adding the __profile_card below does work due to another hook I have running to allow me to specify which paragraph type to target
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {
  if ($variables['content']['field_rounded_profile_image'][0]['#markup'] == "On") {
    $variables['content']['field_profile_image']['attributes']['class'][] = "rounded-circle";
  }
}

Any help on this would be great and I can provide any follow-up details if needed.

What I'd recommend is to simply preprocess the paragraph, get the "round image" Boolean, and use it to add a class to the paragraph. This should be just enough to style the responsive image accordingly.

/**
 * Implements template_preprocess_paragraph__PARAGRAPH_TYPE.
 */
function MYTHEME_preprocess_paragraph__profile_card(&$variables) {

  // Get paragraph.
  $paragraph = $variables['paragraph'];

  if (!$paragraph->get('field_rounded_profile_image')->isEmpty()) {

    // Get Boolean.
    $rounded = $paragraph-> field_rounded_profile_image->first()->getValue();

    if ($rounded['value'] == '1') {
      $variables['attributes']['class'][] = 'rounded-image';
    }
  }
}

And then via CSS (Sass) you'd do:

.paragraph-profile-card {
  &.rounded-image {
    .field-profile-image {
      // rounded image styles
      // ...
    }
  }
}


Get nid in views custom PHP argument i want to limit node reference (autocomplete widget) based on one of CCK field on current node. So, i made view to limit results and in argument->Provide default argument->PHP Code.
And write code like this:

$mynode = node_load(arg(1));
return $mynode->field_foo[0]['nid'];

But problem is in that arg(1) is not returning NID of current page but string 'autocomplete' (i guess it is name of function).
(Didn't had luck with menu_get_object() either)

So how can i get NID of current node other than using ARG() in views custom PHP argument?

Can i reference directly on CCK field (yes, as I sad it is on samo page as autocomplete text-field)?

Thanks for help.

UPDATE:
This is specific to autocomplete widget.

It works well with other widget types (select list, checkbox...)

If you want to have the current NID of the viewed page in your view, you should use the following:

In your view:
At the Arguments section you select "Node:nid", in the configuration of this argument at "Action to take if argument is not present:" you can choose "Provide default argument" after that you choose "Node ID from URL".

And there you have your NID in your view.


Add .active class to a menu link when other menu link is clicked I have following scenario:
Drupal 8.5.6, with a bootstrap subtheme.
There are 2 menus (I'll call them main menu and secondary menu).

The links in the main menu are geographic areas, I've managed to add the .active class to the link, based on the url with the help of this answer: https://drupal.stackexchange.com/a/191861/60589 with a preprocess function and tweaking the twig code.

The links in the secondary menu are related to each one of the links in the main menu, so when I click Area 1 in the main menu, a custom secondary menu will appear in this page.

The problem:
I want the main menu link to stay highlihted, when I click on a link of the secondary menu
The URLs look like this:

mysite/areas/area1 ==> the Area1 link in the main menu gets the active class

mysite/areas/area1/otherlink ==> the links in the secondary menu have this structure, I want the Area1 link in the main menu to keep the .active class.

The cited solution appears a little buggy, as it replaces all potentially existing classes of the menu items. But what makes it not suitable for your use case is, that it is intended to add the active class only, if the current path matches the menu link's URL path.

What you are looking for instead, is the menu items' "active trail". It is a flag set by the menu module on every menu item found when traversing the menu tree upwards, starting from the current active item up to the menu root.

With this information at hand, have a check for the default menu template. It features the menu item specific property in_active_trail:

  in_active_trail: TRUE if the link is in the active trail.

So you can easily add the active class to your currently active menu item and all its parents by using the following in your theme's menu.html.twig:

{%
  set link_classes = [
    item.in_active_trail ? 'active',
  ]
%}
{{ link(item.title, item.url, {'class': link_classes}) }}

A more complete example for a Bootstrap 4 navigation with menu.html.twig:

{#
/**
 * @file
 * Theme override to display a Bootstrap 4 menu.
 */
#}
{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('nav') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'nav-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {%
          set link_classes = [
            'nav-link',
            item.in_active_trail ? 'active',
          ]
        %}
        {{ link(item.title, item.url, {'class': link_classes}) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}


How to delete field programmitically using hook_update? We have a situation where in different environments we have to manually delete fields. Rather than manually doing that, we want to programmatically deploy the changes. The idea that is being is discussed is to use a custom module which calls the hook_field_delete_instance() hook.

The issue we are having is how to best pass in the content type machine name and the machine name for a single content type. We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Using the situation below, what is the best way to delete the two fields on the on the basic page only using the hook_field_delete_instance() on a custom module?

Situation:

We have two content types: article and basic page. We created several fields on the article content type that we ended up reusing on the basic page.

Article:

field_art_original_publish_date
field_art_country_tag
field_art_image

Basic Page:

field_art_image (reused from article content type)
field_art_country_tag (reused from article content type)

Update:

So now that i am thinking further on this, i would like 1 hook update for 1 field deletion so that if a hook update fails then i know which fields need attention.

Here is what i have come up with using what @Clive has suggested.

function mymodule_update_7001(&$sandox) {
     mymodule_delete_field('field_art_image', 'page' );
}

function mymodule_update_7002(&$sandox) {
    mymodule_delete_field('field_art_country_tag', 'page');
}

function mymodule_delete_field($field_mn, $ct_mn) {
    $entity_type = "node";

    $field_instance = field_info_instances($entity_type, $field_mn, $ct_mn);
    field_delete_instance($field_instance);

    //setting the batch size to a large number resolves my prior issues
    $batch_size = 20000;
    field_purge_batch($batch_size);
}

We are understanding that when we reused the field on a separate content type, we are essentially creating an alias on the current content type that points to the original content type holding the field name.

Not quite - each instance exists in its own right, unaffected by any other instance of the same field on another entity type/bundle. Removing it from one bundle (content type) won't touch it on another bundle, regardless of which one it was originally attached to.

You won't need hook_field_delete_instance() for this, just a combination of field_info_instance() and field_delete_instance() in an update hook. Something like this:

/**
 * Remove old fields from the Basic Page content type.
 */
function MYMODULE_update_7100() {
  $field_art_image = field_info_instance('node', 'field_art_image', 'page');
  field_delete_instance($field_art_image);

  $field_art_country_tag = field_info_instance('node', 'field_art_country_tag', 'page');
  field_delete_instance($field_art_country_tag);

  return 'Fields deleted, data will be cleared up on cron.';
}


How to tell if a view is cached from generated HTML output? I have a view on my page and I've cached it using Views caching. Is there a way to tell that the view is cached from the output or the headers? This question says that Drupal sets the header X-Drupal-Dynamic-Cache but I don't see that in my browser's inspector. I do see the header X-Generator:Drupal 7 (http://drupal.org) so that's nice.

It would be nice to see an HTML comment, like what the Boost module does.

The answer you linked to is wrong. X-Drupal-Dynamic-Cache only exists in Drupal 8. Beyond that, the answer itself is also wrong. Will comment there.

In Drupal 7, you can't tell that the view is cached based on output (HTML markup) or headers.


blockquote breaking in the middle When I post something with long blockquote, that's OK, but when this post appeared on front page, it's breaking is such way, that no one can guess that there are also a continuation of the post.

For example, the post: http://en.nuclear-plant.org/node/23

Front page: http://en.nuclear-plant.org/

How to solve this? How to give a hint to readers, how to make "Read more" label more visible?

I don't want to add <!--break--> to each post, because, I have very long quotations, and want to fold them.

In Drupal 7, the default is to use an excerpt (i.e. a trimmed value) of the full text as the summary. The summary is the text that is placed on the front page.

If I understand your question correctly, you do not want to use the default excerpt, because this confuses the reader.

Instead of this default, you can type in whatever you want as the summary to appear on the front page, e.g.:

  Here is a long and quite interesting quote about lorem ipsum dolor sit amet.  To read the full text, just click on the  Read more link below.

To add a hand-written summary, click in the "(Edit summary)" link just above the main body text field in the input form.  Leave this field blank to use the trimmed value of full text as the summary.


How drupal handles block['content']? I am trying to customize a module(quicktabs) for my need. In the hook_block_view, the block['content'] contains an associative array of the contents.
Is there an existing drupal call that renders the associative array in block['content']?

Yes: drupal_render()

Renders HTML given a structured array tree.
Recursively iterates over each of the array elements, generating HTML code.

There's much more explanation, and examples, on the docs page.
I'd advise also reading through Render Arrays in Drupal 7 to get a better idea of what that array represents.


Javascript Messages API Error 1- I tried to set an error message in Drupal 8 from javascript with the new Messages API using the following code:

const messages = new Drupal.Message();
messages.add('test message');

I get the following error on the console log:

drupal.js?v=8.8.5:13 Uncaught TypeError: Drupal.Message is not a constructor.

How can I include this API?

2- As I can see in message.es6.js, there is an option to set message type: error, warning and status. How to pass these params once I get the function working?

Reference Documentation: https://www.drupal.org/node/2930536

Thank you.

You need to make sure your library declares a dependency on core/drupal.message, e.g.

foo:
  js:
    js/foo.js: {}
  dependencies:
    - core/drupal.message

Once you've done that, you can choose the message type by including options:

const messages = new Drupal.Message();
messages.add('test message', { type: 'status' });


Call to undefined function Drupal\Component\Utility\imagecreate() I got this error on a server I setup and was confused:

  Error: Call to undefined function Drupal\Component\Utility\imagecreate() in Drupal\Component\Utility\Random->image() (line 282 of /var/lib/jenkins/src/grls/docroot/core/lib/Drupal/Component/Utility/Random.php

The imagecreate function is part of php's gd library. If a server has been set up manually it's possible it doesn't have the gd library.

First, figure out which version of php you are using, for example with this command:

dpkg -l | grep '^ii' | grep php

Look for a line like:

ii  php7.2     7.2.19-0ubuntu0.18.04.2           all          server-side, HTML-embedded scripting language (metapackage)

That indicates the server is using php7.2. To install gd library for php7.2 on a system managed with apt you need a command something like:

sudo apt install php7.2-gd

And then the error will be gone.


required modules to develop a ecommerce website I am beginning to create a new website which will serve as basically an Ecommerce website like display of products and sell products online and gift cards and all. Please let me know which are the module which i need basically and which are best suited for this.

For Drupal, it's Drupal Commerce that worth consideration now. I worked with it couple of months ago, it takes some time to get used to it, but once you get it, you can create a lots of things with contrib modules and other tools that you can't do without custom development with other CMS.

You will find lots of how-tos, contrib modules and other informations about Commerce http://www.drupalcommerce.org/

Also make sure to check out Commerce Kickstart, which is an installation profile for Drupal stores and it's coming with basic configurations like set up product - product display, and it contains all required modules and dependencies for Commerce http://drupal.org/project/commerce_kickstart


How to display current langage on top of the langage list in a content type I am using drupal 7.54 and I am a bit in trouble.

I have made a multilingual website based on entity translation.

I created a custom content type that users can create or edit nodes with. And that content type has a language field.

But in that dropdown field, English shows first in both languages. It confuses french users.
So I need to make the current language the first on the list of languages.
As an example I want the list to display like this

Français
Anglais

when viewing the site in French version. And :

English
French

when viewing the site in English.

Hopefully I explained the problem properly, I'll be very happy to know what to do.

I need help please.

If you edit your content type, you should have a Language settings tab, I guess you have on Default Language "Site's default" and not the current interface language.


Why adding '--create-db' to sql-sync command throws the access denied? The following command works without a problem:

drush sql-sync @alias1 @alias2

If I add "--create-db" I get:

ERROR 1044 (42000) at line 1: Access denied for user

Why might I be getting this error and what might I need to change? Do I need to add additional details to my alias file?

Also, is it correct that this is the best way to make sure that there aren't tables left over in @alias2 that have been removed from @alias1?

Try:

drush sql-sync @alias1 @alias2 --create-db --db-su=adminuser --db-su-pw=password

Substitute the appropriate username and password for your mysql admin user.  Note that if @alias2 is a remote alias on a shared server, it is possible that other users on that same server might be able to observe your mysql credentials if you use this command.  You might therefore prefer to use drush @alias2 sql-drop prior to sql-sync as an alternative method to dump your sql tables.

Of course, most of the time the remote alias will be the production db, and typically you will only sql-sync from production to dev, not the other way around, so the credentials leak is not usually a problem.


Default language not working properly I have a site with 2 languages: English and Spanish and Path prefix: en and es respectively. Then Spanish language is set to default (see image 1)

And the Language negotiation is set to: Path prefix with language fallback  (see image 2)

Everything works as expected but there is one problem: when the site is loaded it takes the English as default language. Then if I change language (with the Language Switcher) everything works fine.

To be clear, it the url is:

www.mysite.com (landing page is loaded in english) I need this to be in spanish

www.mysite.com/en/home (landing page is loaded in english)

www.mysite.com/es/home (landing page is loaded in spanish)

I can't fix this..Any help please?

goto: Home » Administration » Configuration » Regional and language » Languages.
select the 'DETECTION AND SELECTION' tab.
Un-check all except 'URL' and 'default'. Keep 'URL' on top of 'default'


How do I use hook_form_alter() to add CSS classes to a custom input field in user_register_form? I want to add a CSS class to the input element of a custom field in my user_register_form.

This is the field markup.

        Personal Best
        <input class="text-full form-text" id="edit-field-personal-best-und-0-value"
               name="field_personal_best[und][0][value]" value="" size="60" maxlength="255" type="text">

This is my implementation of hook_form_alter(), which doesn't work. Changing the submit button works, but adding a CSS class to that input element doesn't.

function em_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['edit-field-personal-best']['#attributes']['class'][] = 'timepicker hasDatepicker';
}}

How can I achieve this?

Looks like you're trying to use the HTML ID of the element you're interested in as the identifier in PHP - not quite how it works.

For a field API field, that will look more like:

$form['field_personal_best'][LANGUAGE_NONE][0]['value']['#attributes']['class'][] = 'foo';

Your mileage will probably vary there, have a read of Why is hook_form_alter() so messy? for some relevant information, and make sure you have the Devel module installed to help with debugging (dpm($form) will tell you pretty much everything you need to know).


Extra Space Below Footer in Drupal 7 I'm currently in the process of updating our current site from Drupal 6 to Drupal 7. Between the designer guy and myself, we have been banging our heads trying to figure out where the extra large chunk of space below our footer is coming from. We have added two new regions and three blocks below our main content and when enabling the blocks, the space appears. We have tried everything we can think of. Any help would be greatly appreciated. Thank you.

The site URL is http://prosifland.webhost.uits.arizona.edu/

This looks more like a css issue than a drupal issue.
I am not sure if you are looking for some drupal hooks to solve this problem. But adding this css will solve the issue.

 .region-links-region{
      overflow: hidden;
  }

If this does not work, you can try overflow: hidden !important;


Adding an address to a node's address field programmatically I am presenting a form to receive an address.  I want to take the data and add it to a node that has an address field (from the address field module).

Can someone point me in the right direction on how to do that?

I provided a code example using entity_metadata_wrapper() in this issue. As soon as I finish cleaning up the issue queue, I'll make a regular documentation page out of that. You can follow this issue to see when the documentation page gets published.


Drush 8 not working correctly on (LAMP) Ubuntu 16.04 I am running LAMP on Ubuntu 16.04.  I have a drupal 7 installation and I have installed drush 8.1.3 via Composer version 1.5.2. I believe there is bug in php7.2 causing the error as discussed on Github, however even after I applied the recommended fix which is to update the pear/console_table to the latest version instructed here, the problem still remains. I also followed the instructions on Super User to be absolutely sure that I have the most up to date version of pear installed as well (did not install PHPunit).  And, FYI in accordance with the drush installation documentation found here, I also made the proper changes to my .bashrc file as well (below).

Whenever I run drush status I receive the following error:

[UPDATE: This part of problem SOLVED by @GiorgosK answer below.  Other problems persist due to Drush not find mysql socket]

count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
count(): Parameter must be an array or an object that implements     [warning]
Countable Table.php:789
PHP executable         :  /usr/bin/php
PHP configuration      :  /etc/php/7.2/cli/php.ini
PHP OS                 :  Linux
Drush script           :  /home/webdevusr/vendor/drush/drush/drush.php
Drush version          :  8.1.13
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :

If I execute drush sql-connect

Unable to load class Drush\Sql\Sql                                  [error]
Drush\Sql\SqlException: Unable to find a matching SQL Class. Drush   [error]
cannot find your database connection details. in
/home/webdevusr/vendor/drush/drush/commands/sql/sql.drush.inc:541
Stack trace:
#0
/home/webdevusr/vendor/drush/drush/commands/sql/sql.drush.inc(221):
drush_sql_get_class()
#1 /home/webdevusr/vendor/drush/drush/includes/command.inc(422):
drush_sql_connect()
#2 /home/webdevusr/vendor/drush/drush/includes/command.inc(231):
_drush_invoke_hooks(Array, Array)
#3 /home/webdevusr/vendor/drush/drush/includes/command.inc(199):
drush_command()
#4
/home/webdevusr/vendor/drush/drush/lib/Drush/Boot/BaseBoot.php(67):
drush_dispatch(Array)
#5 /home/webdevusr/vendor/drush/drush/includes/preflight.inc(66):
Drush\Boot\BaseBoot->bootstrap_and_dispatch()
#6 /home/webdevusr/vendor/drush/drush/drush.php(12): drush_main()
#7 {main}

The contents of my ~/.bashrc file, are as follows:

export PATH="$HOME/.composer/vendor/bin:$PATH"

export PATH=/bin:/usr/local/bin:/usr/local/mysql/bin:$PATH

# Include Drush bash customizations.
if [ -f "/home/webdevusr/.drush/drush.bashrc" ] ; then
source /home/webdevusr/.drush/drush.bashrc
fi

# Include Drush completion.

if [ -f "/home/webdevusr/.drush/drush.complete.sh" ] ; then
source /home/webdevusr/.drush/drush.complete.sh
fi

# Include Drush prompt customizations.

if [ -f "/home/webdevusr/.drush/drush.prompt.sh" ] ; then
source /home/webdevusr/.drush/drush.prompt.sh
fi

The result of drush cc all executed from within my drupal installation folder is:

No Drupal site found, only 'drush' cache was cleared.

Anyone know how to get drush to working for my local (LAMP) Drupal 7 installations?

thx

Recently run into a similar problem on my local environment after an ubuntu update and php 7.2 became my default version.

make 7.1 or lower your default php version

I believe you should make php 7.1 the default or perhaps even a lower php version for Drupal 7 installation as not all modules are ready for php 7.2 (even some of Drupal 8 modules are not ready for php 7.2)

type this in your shell

$ sudo update-alternatives --config php

and this is what you will get

There are 4 choices for the alternative php (providing /usr/bin/php).

  Selection    Path             Priority   Status
------------------------------------------------------------
* 0            /usr/bin/php7.2   72        auto mode
  1            /usr/bin/php5.6   56        manual mode
  2            /usr/bin/php7.0   70        manual mode
  3            /usr/bin/php7.1   71        manual mode
  4            /usr/bin/php7.2   72        manual mode
Press <enter> to keep the current choice[*], or type selection number:

Choose the appropriate version

might need to update drush to a later version.

8.1.16 is out at this moment and might already have solved the problem you describe. Update using composer

alternatively you can try to setup drush without composer

# get drush latest 8 version from
# https://github.com/drush-ops/drush/releases
wget https://github.com/drush-ops/drush/releases/download/8.1.16/drush.phar

# make it executable
chmod +x drush.phar;

# move it to home directory or any other directory
mv drush.phar ~/drush;

# go to that directory
cd ~

# find out the path to the directory
pwd
# the output would look similar to this
# /home/your_user

# edit the following file
nano .bashrc
# or
# nano .bash_profile

# add this the end of the file
alias drush='/home/your_user/drush';

# use the alias you just setup
source ~/.bashrc;

might want to specify site directory when you invoke drush

as you drush might have a messed up setup/aliases

drush status -r /path/to/site/rootdir

doublecheck your settings.php

Does it include the correct database connections? Does the site actually run with those connection settings ?

Look in your logs for any problems

in my system I can see apache errors like this

tail -50 /var/log/apache2/error.log

You might discover that some apache packages are missing or disabled just an example lets say mod_rewrite is not enabled

sudo a2enmod rewrite
sudo service apache2 restart

or you might find that some package is missing like mysql-client

sudo apt-get install mysql-client


Adding validation to widget settings form I'm creating a new field in Drupal 8. I've created a class for the widget, extending WidgetBase and implementing WidgetInterface, and added the functions defaultSettings(), settingsForm() and settingsSummary().

I want/need to validate the element I'm adding in settingsForm(), but I can't seem to figure out how to add validation to this. I tried adding a function settingsFormValidate(), but that doesn't seem to be called. I also tried adding #element_validate to the element I'm adding in settingsForm(), but that also does not seem to be called.

Note that I'm not looking to validate the widget (that is shown to the user), I'm looking to validate the element added in settingsForm() for the widget, that is on the Manage Form Display tab, when adding the field to Entities/content types.

Does anyone know how or whether it's even possible to add validation to the widget settings form?

Once again, I've found the solution to my issue. Although I said that I had tried #element_validate in my original post, I must have messed something up, because that turned out to be the solution. Here is the code:

class SomeWidget extends WidgetBase implements WidgetInterface
{
  public function settingsForm(array $form, FormStateInterface $form_state)
  {
    $element['my_field'] = [
      '#type' => 'textfield',
      '#title' => t('My Field'),
      '#default_value' => $this->getSetting('my_field'),
      '#required' => TRUE,
      // Add your validation here
      '#element_validate' => [
        // settingsFormMyFieldValidate() is arbitrary. Choose something descriptive
        [$this, 'settingsFormMyFieldValidate'],
      ],
    ];

    return $element;
  }

  public function settingsFormMyFieldValidate($element, FormStateInterface $form_state)
  {
    $submitted_value = $form_state->getValue($element['#parents']);
    if($submitted_value != 'something it should equal')
    {
      $form_state->setError($element, t('You submitted a bad value'));
    }
  }
}


Display views block only on user profiles I created a views block that lists all the content a user has created. I just want this block to appear on the user's profile page, not anywhere else.

User profiles can NOT be found under www.mydomain.com/users/username but under www.mydomain.com/username, so there is not really a way to just display the block on any arg(0)-predefined path.

If I were using Profile2 (which I am NOT, as I haven't figured out a big advantage of Profile2 over the core profile module in combination with the field permissions module yet) I could simply add the contextual filter "Content: NID" and validate with content type "profile". However, my user profiles aren't nodes and so this can't be done.

Is there any way to resolve this issue without using Profile2? All my users will have one profile only and this is really the first time where I would need user profiles to be nodes.

If you want to display this block only if the path "username" you should use Context.

In the view you have to add the relation on "Author" and then you should have the filter criteria to show contents of the logged user.

With Context you can say "When I'm on the path X then display the block Y in the region Z".


How to fix the garbled text in my text editors? When editing my nodes all of my saved data is displayed garbled. This is the warning I get on my node/edit pages: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
The other odd part is that the contents of the database field and the contents of the output are correct. Just the contents of the text editor is garbled.
How can I fix this?

UPDATE: I have another content type that has a file field, and I have some pdfs loaded in those fields and those pdfs are the ones that are showing up in my text editor. Does anyone know why that would happen?

I had the exact same issue with aGov distro. I had to swapped from ckeditor module to WYSIWYG module + ckeditor lib.

That fixed the issue with ckeditor. However, today I got the garbled text again while having batched processes running which preventing them to complete. Thinking back, I realised the problem started when I installed Devel themer & simplehtmldom API (7.x-1.12). Uninstalling simplehtmldom fixed the issue for me.


Debug EntityFieldQuery? I have a module which is misbehaving. An EFQ is returing unexpected results, but I can't see why just by looking at the code. Is there a dpq() equivalent for EFQs? Other ways of debugging them?

It's a wee bit of a hack, but you could add a tag to any EntityFieldQuery you're interested in printing the query for, then implement hook_query_alter() to intercept it when it's a standard SelectQuery, then cast it to string for debugging:

function MYMODULE_query_alter($query) {
  if ($query->hasTag('efq_debug')) {
    dpm((string)$query);
  }
}

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node')
  ->addTag('efq_debug')
  ->execute();

It's a bit of a hack but does the trick. The output for the above is:

SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type
AS entity_type
FROM {node} node

Presumably this will also only work when using MySQL as the field storage system.


How to show Wordpress blog posts in Drupal's Search Api? We have a blog site on Wordpress that we want displayed in our search without having to create Drupal nodes for each blog post. We using the following below and were interested in seeing how we can do this as the Wordpress Migrate and Migrate has not provided a way to do this.

All we want to do is display the blog post on our search (which using Apache Solr Search Index) in such a way that we pull the blog post title, description and a direct link to the post.

There are 2 ways you can achive this :

[simple] Import the posts from wordpress rss with Feeds https://www.drupal.org/project/feeds
[more difficult] Crawl the Wordpress content and populate the Apache Solr index directly. You can use an open source crawler like Apache Nutch
The difficult part is that the external content is not managed by Drupal, only through Solr so you don't have many options to play with the indexed content in the Drupal site.


Set (add) group role using Rules when organic group membership is updated? Using Rules, I am trying to set a users group role anytime a new membership entity is updated, however it appears roles are not brought into scope for me to set data value nor "grant og role"

All I want is

Event: After updating an existing og membership

Action: Grant OG role: Licensee (or set data value role: Licensee or whatever og centric things it asks for)

You should note that group role is not a field or property in the og_membership entity. The og_membership entity contains the properties etid, entity_type, group_type, and gid. There are other properties, but those are the ones you are interested in. When a user is added to a group, the entity_type is user and the etid is the user id. When node content is added to a group, the entity_type is node and the etid is the node id. The og_membership entries are not updated very often, so I'm not sure why using the event "User has become a group member" isn't sufficient. Assuming you really do want to change a users group role when the og_membership is updated, then you need to verify via rule conditions that the og_membership group type is node and the og_membership entity_type is user. Then you can use the Grant OG Role action. The rule export would look something like this:

{ "rules_205092" : {
    "LABEL" : "205092",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "og_membership_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "og-membership:group" ], "type" : "node" } },
      { "entity_is_of_type" : { "entity" : [ "og-membership:entity" ], "type" : "user" } }
    ],
    "DO" : [
      { "og_grant_og_role" : {
          "account" : [ "og-membership:entity" ],
          "group" : [ "og-membership:group" ],
          "roles" : { "value" : { "licensee" : "licensee" } }
        }
      }
    ]
  }
}


Hook path in main menu not hold active trail In custom module names supply_area I've created custom path.

function supply_area_menu() {
    $items['supply-area'] = array(
        'title' => 'Supply area',
        'page callback' => 'supply_area_page',
        'type' => MENU_NORMAL_ITEM,
        'access callback' => true,
        'menu_name' => 'main-menu',
    );
    return $items;
}

Everything works perfectly except that even if I assign this path into main menu structure it does not hold menu structure so breadcrumbs looks like:
Home > Supply area and not Home > About > Supply area.
Is there something wrong with my hook_menu?

I am not sure what you are doing in a lot more areas of your system than described above, but doing the following on a d7 testbed here:

function MYMODULE_menu() {

  array $items;

  $items['about'] = array(
    'title' => 'About',
    'page callback' => 'MYMODULE_about_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  $items['supply-area'] = array(
    'title' => 'Supply area',
    'page callback' => 'MYMODULE_supply_area_page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'menu_name' => 'main-menu',
  );

  return $items;

}

function MYMODULE_about_page() {
  return 'What\'s it all about, Alfie?';
}

function MYMODULE_supply_area_page() {
  return 'Making Supplies';
}

...followed by clearing caches and then setting it up via the Menu UI:

...provides the following:

so I would check how you might be doing it slightly differently on your system.


Attach JavaScript and CSS assets when render entity using Views REST export Goal:

Have a REST endpoint which will deliver list of rendered entities.
Each row should contain a ready-to-use HTML.
All the necessary JavaScript and CSS files should be also included on the page.
P.S. I need this endpoint for lazy-loading of entities.

Given:

I have a Views display with REST export.
I render entities there using the rendered_entity field.

Problem:

JavaScript and CSS files, needed for rendering, are not attached on the page.
E.g. scripts for display of an image gallery, lazy-loading of images.

We came up with a new module: Ajax Assets Plus.

The module provides a new render which collects all the necessary libraries during rendering. It results in an array:

return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

We had to to override the AjaxResponseAttachmentsProcessor and AssetResolver classes.

Also we implemented the hook_js_settings_build() to collect all the libraries on the page, as ajaxPageState does not contain all the dependencies.


Panelizer: displaying node reference field I have an "Event" content type with a node reference field of type "Host".

"Host" content type has an "Affiliation" field.

I would like to display the event details though Panelizer, so that it would show not only the host name, but also their affiliation. How can I access a node reference field through panelizer?

My guess is that it should be done though the "Existing Node" option, but I might be wrong.

You'll have to create a custom formatter where you can control the output of the node reference. To create a custom formatter follow this tutorial: http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

After that in panels when you add the node reference you can choose the custom formatter you've created:


Looking for informaton on Drupal core security process, audits and benchmarking I'm looking for information on Drupal's security processes, any audits carried out, benchmarking against securty standards, what happens security-wise before a new Drupal release etc...

The most useful info i have found thus far is here:

http://drupalsecurityreport.org/

and here:

https://www.drupal.org/security-team

But it doesn't give much detail on internal processes or on accreditations etc.

Danny.

There are 2 websites you should look at, http://buytaert.net/greg-knaddison-and-drupal-security and http://crackingdrupal.com.


how to change value of submit button of comment form? I wanted to change the default value of submit button in comment form from "Save" to "Post". I wanted to do that using a module , not javascript. So I wrote the following code in my module.

 function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id){

     $form['actions']['submit'] = array(

      '#value' => t('Post Comments'),
     );
     }

But instead of changing the value of submit button, this module is making the submit button hidden. If I add return $form  , then the submit button displays but with the same default text "Save". Any suggestions please. Thank you.

You're replacing the entire element at the moment (which is why it doesn't show). You can change a specific property in the array like so:

$form['actions']['submit']['#value'] = t('Post Comments');

That way you're just setting the #value property, and not removing the other properties that already exist for the element.


How can I change the drupal form action based on Radio button selected? I have developed a custom form in my module. Now I have to change the form action based on radio button selected. Suppose if I have 3 radio buttons saying
1. ABC
2. DEF
3. XYZ

If i select ABC and submit form, my result should display on www.domainname.com/abc

Thanks.

You can change the Form action in submit function

    function your_form_name_submit($form,&$form_state){
          if($form_state['values']['radion_button_name'] == 'abc') {
         $form_state['redirect'] = url('path/to/redirect');
        }
    else{
       $form_state['redirect'] = url('path/to/redirect');
     }
}

hope this will help you!!


Theming html output of privatemsg 6.x-2.x module How can I theme the output of Privatemsg? I took look at http://api.worldempire.ch/api/privatemsg/privatemsg.theme.inc/group/theming/1, but I didn't understood how to use that.
I want to totally change the HTML output for the message list.

How do I use my custom date format in the messages? I guess the format_date() function would help me, but how do I use it correctly?

print format_date($messages_timestamp, 'custom', 'd=m=Y') returns "01.01.1970." What is that?

Ok, here is some information.

That list shows threads, not single messages. You can't change that, at least not with theming. The only thing you easily can do is enable the privatemsg_limits module and set the number of messages per thread to 1. That basically disables threading and each message will be sent as a new thread. Then they will be shown separetly on the list, but they will also be shown separately on the thread view page. Privatemsg views is currently only compatible with 6.x-1.x and looks rather unmaintained at this point.
You can configure the displayed columns and their order in the Privatemsg settings.
The theming functions are used to customize the content of single columns. For example, to show a different date format, you can override phptemplate_privatemsg_list_field__last_updated():

function phptemplate_privatemsg_list_field__thread_started($thread) {
  $field = array();
  $field['data'] = format_date($thread['thread_started'], 'custom', 'd.m.Y H:i');
  $field['class'] = 'privatemsg-list-date-started';
  return $field;
}

In 7.x, Privatemsg shows a different date format depending on the age of the message, that is done in privatemsg_format_date() if you want to backport that.
To change how the table looks, you should be able to that with just CSS. Privatemsg adds tons of classes to that table, including a seperate class for every column and classes for rows with new messages and soon for unreplied messages too.


Limit number of upload in Imagefield depending on a specific field On my website, members can pay for 3 different offers (Gold, Silver, Bronze). I would like to limit the number of pictures a member can upload, depending on the offer he picked.

I'm using Drupal's user_form and add an "Imagefield" field, with illimited upload.
Offers are 3 taxonomy terms, and all contain a field with the max number of images allowed.

I'm able to get the amount of images allowed, from the taxonomy term, but how would i go about applying that limit to the imagefield?

Thanks a lot!

This will need customising to your specific situation, but the basic idea is to add a validation handler to the node form and perform a check in there, e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_id') {
    $form['#validate'][] = 'MYMODULE_images_validate_limit';
  }
}

function MYMODULE_images_validate_limit($form, &$form_state) {
  $images_submitted = count($form_state['values']['field_image'][LANGUAGE_NONE]);

  if ($images_submitted > function_to_get_limit()) {
    form_set_error('field_image', t('Too many images'));
  }
}


Menu system - accepts extra args on path Awhile back, working in Drupal 6, I found an issue in which a valid path, say:

  example.com/real/page

would be served if the following did not exist:

  example.com/real/page/fake-arg

I thought it was occurring only with pages defined through Panels and Views, and managed to implement a rather complex check (run during hook_init()) for whether a panel should really be handling that path, and if not, call drupal_not_found().

However...

I just today realized that this same thing occurs with paths defined in Drupal core, e.g.

  user/7

gets served for

  user/7/blah

(This answer is what tipped me off: https://drupal.stackexchange.com/a/5080/834)

So evidently, this is happening by design (and through no fault of the CTools-related modules that instate pages through hook_menu()).

I haven't fully been able to dig into menu_get_item() to figure out how it's accepting the extra args, but my question is: does anyone know a way to get around this behavior and make these non-existent paths result in 404s?

I don't think you can do that in a general way, this is a behavior that's by design and many modules rely on this, so you would break their optional arguments. In fact, relying on this is currently the only way to support optional arguments without defining a menu router item for every possible combination.

If you want to do it for a specific page callback under your control, you could check if there are any arguments passed to your function with func_get_args() and if so, return a 404.

Note that this "feature" might be removed in 8.x, I've seen it mentioned in an issue.


How to create a user with custom fields? On my drupal site, using the User module, I have added extra fields to the user registration form such as 'Organization'. I notice that this has created a mysql database called 'user__field_organization'.

I am trying to write a custom module which involves creating new users.

At the moment my module creates a new user, with a username, password and email.
The code for this (which works fine) is:

$user_data = ['name' => 'John', 'mail' => 'email@me.co.uk', 'pass' => 'examplePassword','status' => 1,];

$this->user = $this->user_store->create($user_data);

(where $this->user_store = $etm->getStorage('user'); )

But I also need to update the extra fields such as Organization but can't work out how to do this.

I have looked at this question: How to programmatically create new user with custom fields?

And I have tried adding custom_field_organization or user__field_organization into $user_data but it doesn't work.

I have been trying to find out where in the User module a user is created once the registration form is submitted. If I could find that then I could copy what is done there.

You are close to the right solution. You have to add 'field_organization' => 'some_value' to your $user_data array.

They keys in the $user_data array is the field names. The field name is what comes after user__ in the table name. You can also see the field name in the UI where you add the fields (it’s also called machine name).


passing URL to Webform I am developing a site (Drupal 7, Omega sub-theme, panels & views). On every product page I have a link to the webform. I need the webform to register to which page the customer is referring. In other words, where is the link coming from, or what is URL of the last visited page?
Is there a specific drupal way of doing this?
Or any other way, for that matter?
Thanks!

On you link display something like this :

$current_path = current_path();
$current_path_alias = drupal_get_path_alias($current_path);
print url('my-webform', array('query' => array('from' => $current_path_alias )));

If you are on content/mynode, the link will display my-webform?from=content/mynode.
If you want just the unaliased path skip the use of dupal_get_path_alias()

$current_path = current_path();
print url('my-webform', array('query' => array('from' => $current_path)));

If you are on node/18, the link will display my-webform?from=node/18.


Building form and saving as a content type I have designed a site. In this site there is a content type for our experts. Also we need to design a form to employ more experts. We need people send form and admin see their forms, edit and then publish as our content type. Problem is, webform is not suitable for this. Is it possible using CCK as a webform? Is there another solution for this? Is it possible saving webform as a content type?

Thank You

What you need is the workflow module. You would create your content type with all of the same fields as your current webform but set it to default 'unpublished.'

Enable the workflow and create new workflow states for 'draft' and 'reviewed'. Set
your actions to mark it in draft when the node is created by the user and then allow your editors to approve and publish.


No sub theme folder inside bootstrap theme folder I just installed Bootstrap 3 theme in Drupal 7, but the subtheme folder is missing. I am new to Drupal and am following online tutorials but no result. All instructions direct me to a sub theme folder in themes>bootstrap> bootstrap-subtheme, but there is no such folder. I removed the theme and reinstalled but still no folder.

Have a look in the starterkits folder then choose between less or cdn.

For more information, have a look on files within docs folder


D6 - Trying to display variable_get()s in a block I am trying to display 4 variables in a custom block(created from my custom module). I am accessing the variables using variable_get('$myvariable', '0').

I am not able to display the array in the block "$content" - is my code not handling the renderable array properly?

 function neil_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
  return array(
    0 => array(
      'info' => t('Custom Neil Block'),
    ),
 );

case 'view':
    $subject = '';
    $content = '';
    switch ($delta) {
        case 0:

          $block_content = "";

          $block_content = array(
            'content'   =>  array(
                'blockvar_progress_so_far'          =>            variable_get('progress_so_far', '0'),
                'blockvar_number_of_projects'       => variable_get('number_of_projects', '0'),
                'blockvar_dollars_raised'           => variable_get('dollars_raised', '0'),
                'blockvar_number_children_impacted' => variable_get('number_children_impacted', '0'),

            ),
          );

          $content = $block_content;
          $subject = t('Subject in My Custom Block');
        break;
    }

    }
return $block;
break;

}
}

Instead of the "$block_content", I only see the following: "Array"

You need to return the output of the block content as a string, not an array.

...
case 'view':
  $subject = '';
  $content = '';
  switch ($delta) {
    case 0:
      $subject = t('Subject in My Custom Block');
      $content =
        'blockvar_progress_so_far = ' . variable_get('progress_so_far', '0') . '
' .
        'blockvar_number_of_projects = ' . variable_get('number_of_projects', '0') . '
' .
        'blockvar_dollars_raised = ' . variable_get('dollars_raised', '0') . '
' .
        'blockvar_number_children_impacted = ' . variable_get('number_children_impacted', '0');

      // Return values so they can be inserted into block
      return array(
        'subject' => $subject,
        'content' => $content,
      );
    break;
  }
...

See documentation on Drupal 6's hook_block() for a more detailed example.


Make certain nodes of group Private How can i make certain nodes of group Private in a Public Group irrespective of content types.
So lets say I have a Public group X which has Page as a content type. So i have 10 as contents of groups which is public.So I have to make 2 contents of the group Private such that it is only available to the group members.

Tks in adv,
-Vil

Enable Group Content Visibility field on Content Type. Using that field you can mark content under a group as public or private.

You need to enable OG ACCESS module to see those fields in admin/config/group/fields

Select the bundle as your content type in node section and select field Group Content Visibility from Fields Dropdown, click on Add field to add Group Content Visibility field for Content Type.


"Redirect Loop" when creating a multisite I know there are a few questions related to this one, yet I haven't been able to answer mine.

I want to develop 2 websites pointing to the same Drupal core files,

so :

drupal1.example.com should point /www/dev/sites/drupal1.example.com drupal2.example.com should point to /www/dev/sites/drupal2.example.com

I've created both subdomains to point to /www/dev/ folder.
I've put settings.php in drupal1.example.com and default.settings.php in drupal2.example.com
When I load drupal2.example.com, I get a "Redirect Loop" error.

Do you know what I'm doing wrong ?

Thanks!

ANSWER :

When there was no settings.php file in my sites/drupal2.example.com folder, it showed the drupal1.example.com website.

When there was a settings.php file in my sites/drupal2.example.com folder, it got me an infinite loop.

So I modified the settings.php in sites/drupal2.example.com folder to connect to a different empty databse, but then I got an error "Base table or view not found: 1146" then another error upon refresh "error: Class 'SelectQueryExtender' not found".

It seemed as though the installer had a hard time loading the 2nd instance of Drupal since there were no tables in the DB.

So I imported DB #1 into DB #2 and it worked.  I could change the theme in drupal2.example.com and I still had the old theme in drupal1.example.com.

The only downside is that I have to delete the content types, nodes, menus, etc ... in my drupal2 but I least it's working!

Assuming you have ServerName and ServerAlias properly defined in Apache, I suspect you have the default canonical URL redirects enabled in your .htaccess.  Make sure this stuff is all commented out:

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Also make sure you don't have any other Apache rules that are doing something similar, and that you don't have any modules (eg, Domain Access or Mobile Tools) or custom code that would do a redirect.


Custom html.tpl.php file is not getting picked up I have a page with a url alias of say /food/tacos

I have created html--food--tacos.tpl.php to include some javascript only on that page. I've used this method many times (on other sites) with no problems, but Drupal (7) doesn't seem to be picking it up this time.

I have cleared all caches.

Theme debug offers the following suggestions, none of which seem to recognize the path alias. I would prefer to use the alias as I may use this theme in multiple places where the node number would not be the same.

<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--node--3.tpl.php
   * html--node--%.tpl.php
   * html--node.tpl.php
   x html.tpl.php
-->
<!-- BEGIN OUTPUT from 'sites/all/themes/mytheme/html.tpl.php' -->

How can I get this working with the alias?

You have to add a theme hook suggestion (example from here):

function THEME_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}

Use this in code in your template.php file in the theme directory and, obviously, change it :)


How can I get the currently submitted form state in a block on the same page? How can I retrieve the currently submitted and validated form state?

Please assume the following scenario.

A page has a form on it created using the form API.
The data in the submitted form is transient. In other words it is not saved or stored in any way.

The form is created by a module I do not control and therefore I should not alter the codebase.

On the same page as the form is a block (mine) which displays data based on the form submission.

I want to get access to the validated data from the anonymous user submitted form from within the block plugin code.

The form does all the necessary validation of the user submitted data. I do not want to replicate this validation so I need to get access to the validated form_state so I can extracted the submitted values.

I cannot see a way to retrieve the form_state object from the current request.

How can this be done?

As with most things you are learning. The answer is often simpler than first thought.

To resolve my issue I was able to use hook_form_alter and implement my own submission handler.

From here I was able to disable the redirect to prevent the page reloading.

Once redirect was disabled then my block plugin was able to get access to the form and use the validated results within it.

My block build for demo purposes contained the following

public function build() {

  // Get the current form.
  $form = \Drupal::formBuilder()->getForm('Drupal\modulename\Form\moduleForm');

  return [
    '#markup' => "<pre>" . print_r($form, TRUE) . "</pre>",
  ];
}

The important point is \Drupal::formBuilder()->getForm('name') returns the cached form results and therefore does not require any further validation.

This can be verified by checking $form['#validated'] == 1.


Image not responsive in one content type. Can anyone help me resolve this? I'm hoping someone might be able to help me. Yesterday, i noticed that the main image on my photo gallery content stopped behaving responsively. For example: http://thesalinepost.com/photo-gallery/saline-sweeps-tecumseh-home-opening-doubleheader Now, the same image style is working correctly on article content http://thesalinepost.com/article/saline-rowers-kick-spring-season-spring-lake-michigan
And on it's working on announcement and events content.

Because you a style rule somewhere...

.node-openpublish-photo-gallery .field-name-field-op-main-image {
   width: 620px;
}

They appear to be different content types...

node-openpublish-photo-gallery (not working)

node-openpublish-article (working)


Trying to add a column of Mysql timestamp through hook_update I was trying to add the column of MYSQL Timestamp to the Database Table, the Query seems to be working correctly in mysql console.But when I execute the same in db_query() the following error is thrown.

  Failed: PDOException: SQLSTATE[42000]: Syntax error or access
  violation: 1067 Invalid default value for 'last_update_date': ALTER
  TABLE stores ADD last_update_date TIMESTAMP NOT NULL DEFAULT
  '0000-00-00 00:00:00';; Array ( ) in store_update_7100() (line 254 of
  /var/www/slocamo_app/sites/all/modules/store/store.install).

Is the Query.

ALTER TABLE  `stores` ADD  `last_update_date` TIMESTAMP NOT NULL DEFAULT  '0000-00-00 00:00:00');

While valid in SQL, there is no data type TIMESTAMP in the Drupal 7 database schema.

The list if valid data types is here.

This means that you cannot add this datatype  to your tables through any function that goes to the Drupal API (such as db_query).  Your SQL console is not subject to these limitations, and will allow it to be added.

So the short answer is: Drupal 7 will not let you do what you try to do.

Also, in case you're trying to add two auto-update timestamps, note the following limitation in MySQL:

  One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.


Can't install modules in a sub site --- Seeing Ajax error Background

I have a Drupal 7.38 folder subsite (i.e yoursitesname.com/test). The site was installed with softaculous, and has only few core modules enabled. When I come to install the last version of Views, or alternatively, References, I get this error:

You can see from the first screen that the error tells me to continue to the "errors page" and this is what I see when I continue

Already tried and didn't help

Some of the solutions were found in Google search:

Flushed all caches.
Installing from a downloaded file, instead of a link in Drupal.org.
giving 755 permissions to all the homefolder files (including .HTaccess and all files in sites/default folder).
Changing PHP version for main folder (i.e yoursitesname.com) from PHP 5.3.29 to PHP 5.5.26

Any suggestions?

Here is a list of items to check:

Clear all caches (it doesn't hurt, and occasionally helps solving various issues): if you get a WSOD while doing so, it indicates memory shortage.
Try running update.php (by typing an URL like http://www.yourdomain.com/update.php): if you get a Fatal error like "Allow memory size of ... bytes exhausted", it indicates memory shortage.
Verify if it is a memory shortage issue by increasing the memory a bit to check if there is any difference.

Assuming this is NOT a multi site, consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

ini_set('memory_limit', '100M');

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

If needed, refer to https://www.drupal.org/node/207036 for more details, eg if such 'ini_set' is not yet included in your settings.php file. As mentioned in that link: "Locate the PHP settings section and add that line at the end of that section".


Exclude a page from indexing on a per page basis I would like to be able to remove a page from search engines (external and drupal). I want to add a checkbox on the content type to be able to specify which page should or should not be indexed.

My plan is to check via the hook_node_save if the checkbox is checked, and if so, edit the robots.txt to add a Disallow via the provided url. If the box is unchecked, I remove it from the robots.txt

This is complicated though. Does anyone has a better solution ?

Thanks,

I recommend installing the Metatag module. Once installed you will have a checkbox: Prevent search engines from indexing this page located on every node under Meta tags -> Advanced.


Remove "add to cart button" when event date has passed I'm making a webshop that sells tickets for events. And I want that the "Add to cart" button isn't displayed when the event date has passed. But I'm struggling with the Rules module.

Can someone help me out?
I'm using ubercart

If you're using Drupal Commerce, this question seems to provide a step-by-step of what you're looking for.

How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields?

At the very least it should point you in the right direction and give you a better sense for how Rules integrates with Commerce.


Drush 8 raises an error while running 'drush runserver' I just installed Drush (globally) as described here: http://docs.drush.org/en/master/install/,
on Ubuntu 14.04 (PHP 5.5.9).

Then I created a new Drupal 8 web site and database with:

$ drush dl drupal --drupal-project-rename=example
$ drush si standard \
    --db-url='mysql://[db_user]:[db_pass]@localhost/[db_name]'
    --site-name=Example

When I run the built-in server within the project directory:

$ drush rs 8000

And I try to access http://localhost:8000, I get this error:

  PHP Warning: Unknown: failed to open stream: phar error: invalid url or non-existent phar phar:///usr/local/bin/drush/commands/runserver/d8-rs-router.php in Unknown on line 0
  PHP Fatal error:  Unknown: Failed opening required 'phar:///usr/local/bin/drush/commands/runserver/d8-rs-router.php' (include_path='.:/usr/share/php:/usr/share/pear') in Unknown on line 0

What's wrong?

I solved installing the last version of Drush via composer:

$ # Remove previous drush installation file
$ sudo rm /usr/local/bin/drush

$ # Install drush globally via composer
$ composer global require drush/drush
$ ln -s ~/.composer/vendor/bin/drush ~/bin/drush

Now it works.


How to hide Default values using Drupal Behaviour I have created a form using the web form module. In this form i have 3 field. Name, Email and Phone. I have set the default values for Name as Name , Email as E-mail and Phone as Phone (Done this using the form settings).

Now the scenario is, when the user clicks on the Name field , The default values has to go off. I tried this using jQuery but it didnt work. So i thought of using Drupal Behaviours with jQuery.

This is my code

(function (jQuery) {
 Drupal.behaviors.amendor = {
    jQuery('edit-submitted-phone').focus(function() {
      alert('Chekcing the values');
      if (jQuery('edit-submitted-phone').val() == 'edit-submitted-phone'.defaultValue) {
        jQuery('edit-submitted-phone').val('');
      }
    });

    jQuery('edit-submitted-phone').blur(function() {
      alert('setting the values');
      if (!jQuery('edit-submitted-phone').val()) {
        jQuery('edit-submitted-phone').val('edit-submitted-phone'.defaultValue);
      }
    });
  };
})(jQuery);

To start with, as you're namespacing jQuery you can use the $ instead of jQuery inside the (function (jQuery) { ... });

Secondly, you're not pointing to classes or ID's in your jQuery.  I'm pretty sure that edit-submitted-phone should be #edit-submitted-phone in every instance in your code.

If this doesn't work, then let me know and I'll see what else I can come up with.


domain access display content to ANONYMOUS USER I have create basic page that only displays on domain one and not the others which I want. The issue is that the page will only display when the user is log in and I want ANONYMOUS USER to see the content

Under the permissions the View published content has the  ANONYMOUS USER ticked
but I can't seem to find a way or why the content is not displaying until an authenticated user is logged in

Under admin/structure/domain/roles you have to checkbox guest -> all domains.


Can you create a view to display all files within a certain directory? I have a Node Type A that is referred to by a bunch of other nodes. Within the nodes that are referring to Node Type A, there are various and separate CCK file fields. I have configured all of these files to be saved in a directory that is named with the title of each Node Type A (with the FileField Paths module)...so all of the corresponding files for a Type A node are in one place. I need to create a view that displays all of the files from the referring nodes in a sortable table. The problem that I'm running into, is that I have to add each separate CCK file field from an assortment of different node types to the view, which generates empty fields in the rows ouput.

So can I build a view that pulls the files from a specific directory on the server?

Only tools I've seen dealing with showing file are more like this...

http://drupal.org/project/elfinder

http://drupal.org/project/webfm

http://drupal.org/project/manager

http://drupal.org/project/filebrowser

You can create a view of all attachments to nodes, but that's not what you want either.


Drupal commerce based recommendations engine I want a shop where experts join the shop and each expert recommends his favorite products.

Expert's user profile will show his recommended products.
Users can vote recommendations up and down, much like happens in amazon.
The product's page will show the recommendations for that product.
The expert will also be an affiliate.

Possible architecture:

Commnets may be themed to be recommendations, together with voting stars.
Affiliates may be added with the Post Affiliate Pro integration.

Questions:

From your experience, what are the best modules / drupal commerce extensions to support this scenario?
Is there another, internal affiliate solution?

Thanks

Amnon

I would not use comments to be recommendations but I would use nodes. This will give more flexibillity.

Here is a possible architecture:

I would use the flag module to let user flag (recommend) a product.
On flagging, I would use hook_flag to create a new node (content type: recommendation). This node would reference to the product. The new node would contain a body field that will contain the actual recommendation. Finally, I would attach the rate module to this node so that users will be able to vote on it.

As far as I know the flag 3.x module is now an entity, which means that you can attach fields to the flag. So, another possible architecture would be to use the flag itself for storing the recommendation. Have not tried this though but seems interesting.


Show a block only on the frontpage of the sub-domains I am using Drupal 7 for a site and I installed the Domain access module for maintaining the sub-domains. The slideshow block (created using the Views module) should be displayed on the sub-domains front page, but not on the main domain.

I tried the Domain block module, but it would require to manually set the block for each domain.

How can I make the block appear only on the front page of the sub-domains?

I recommend you to use context module for block displays with the domaincontext module extension.

  Domain Context module is an integration module for the Domain Access module and the Context module.

  The Domain Access module allows administrators to set specific
  settings for each of their domains that are using the same code base.
  The Context module allows you to assign blocks to regions (and more)
  given certain conditions that can be set in the Context admin.
  Currently when both modules are installed you have no interface that
  will allow you to trigger a context on a specific domain. This module
  adds a domain condition to the context administration so that you can
  trigger a context on a specific domain.


How to add and condition in Query I have to fetch nodes where it doesn't have both roles(6,7) in it,at the same time  exactly.

I don't want to show role 7 nodes, but it some times have role 6 attached to it also ,at that time i want to omit those nodes.

This is the query which i wrote for that

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result = $nids_result->execute()->fetchAll();

But this is fetching me all nodes including role 7 also,because role 6 is also some times available in the nodes.

How do I write and condition where it checks for both 6 and 7 roles are available and omit those nodes.Thanks in advance.

By default it is and condition

$nids_result = db_select('node', 'n');
$nids_result->join('users','u','n.uid = u.uid');
$nids_result->join('users_roles','ur','u.uid = ur.uid');
$nids_result->fields('n', array('nid'));
$nids_result->condition('ur.rid', 7, '<>');
$nids_result->condition('ur.rid', 6, '<>');

// if you have devel installed check this.
dpq($nids_result);
$nids_result = $nids_result->execute()->fetchAll();

debugging the query with dpq will tell yuo the exact query that you can run on phpmyadmin and can see what you are missing.

Updated:

if you need query like

SELECT n.nid AS nid
FROM
{node} n
INNER JOIN {users} u ON n.uid = u.uid
INNER JOIN {users_roles} ur ON u.uid = ur.uid
WHERE ( (ur.rid <> :db_condition_placeholder_0) OR( (ur.rid <> :db_condition_placeholder_1) AND (ur.rid <> :db_condition_placeholder_2) ))

Code will be :

   $nids_result = db_select('node', 'n');
   $nids_result->join('users','u','n.uid = u.uid');
   $nids_result->join('users_roles','ur','u.uid = ur.uid');
   $nids_result->fields('n', array('nid'));
   $db_or = db_or();
   $db_or->condition('ur.rid', 7, '<>');
   $db_or->condition(db_and()->condition('ur.rid', 7, '<>')->condition('ur.rid', 6, '<>'));
   $nids_result->condition($db_or);
   $src = $nids_result->__toString();
   dpm($src);


How are access permissions prioritized when multiple modules implement them? I have the Group module setup where I only allow view permission for group content to group members, so I have closed groups. But additionally, I want groups to also make some content public to non-members (but authenticated users) or to anonymous users even.

I have setup the Permissions by Term module for this where I made an "Additional view permissions" vocabulary that has two terms "all authenticated users" and "public". Those two terms I have granted permission to the respective roles. I had hoped that this would override the group permissions, but it doesn't. If I am not logged in, group content that has the "Additional view permissions" set to "public", still is not accessible to anonymous users.

I guess my question is: how does Drupal determine the priority of multiple modules arranging permissions for the same node, and can I influence this? In my case the group permissions seem to take priority, causing view permissions to be denied. But if it would first look at the permissions by term module, it would actually allow access.

Have a look at this feature request Allow other modules to alter gnode_node_access's forbidden result, especially this part of it:

  If the group node's gnode_node_access module doesn't find a reason to return neutral, or to grant access, it returns a AccessResult::forbidden(). This prevents any other module from granting access. ...

So to "determine the priority of multiple modules arranging permissions for the same node" (as in your question): if the Group module denies access, then there is no way for any other module to overrule that access.

Maybe not what you like to hear/read, but this is how access is handled via Group module.


Referencing an existing image in theme settings In a custom theme (Drupal 8.4.3) I would like to add a theme setting, where I can reference (not upload) an image to use as a background image. Like in a normal reference field, already uploaded images should be choosable; these images are stored in media entities.
How can I build such a theme setting? I only found information about Uploading images in theme settings.

I haven't been able to find an example of this, either, but here's a simple demo setting a reference to a media/image in theme settings (with the autocomplete widget):

use Drupal\Core\Form\FormStateInterface;

function THEME_form_system_theme_settings_alter(&$form, FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  $opts = [
    '#type'          => 'entity_autocomplete',
    '#title'         => t("Call to Action Background"),
    '#description'   => t("Default call to action background media image; may be overridden on individual elements."),
    '#target_type'   => 'media',
    '#selection_settings' => ['target_bundles' => ['image']],
  ];
  if ($default_id = theme_get_setting('call_to_action_background')) {
    // element stores an int ID, but default value has to be the loaded entity
    $image = \Drupal::entityTypeManager()->getStorage('media')->load($default_id);
    $opts['#default_value'] = $image;
  }
  $form['call_to_action_background'] = $opts;

}

To retrieve and render, use a THEME_preprocess hook with parameter &$variables:

$media_id = theme_get_setting('call_to_action_background');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'some_media_display_mode');

The render array is then available in twig:

{{ media_build }}


Get variables of a view? im trying to access some variables of my view but i fail terribly:
My modulefile looks like this:

$io= views_get_view('nameofmyview');
dpm($io);

Drupal tells me:

  Fatal error: Call to undefined function views_get_view()

What am i missing?

Thanks @clive for the hint

module_load_include('module','views','views');

does the trick!


Send email with profile2 fields with account email token in rules I am trying to send an email to users contains information they put into their profile2 fields when they registered on the website.

My problem is that their is no email field token available in rules and I was wondering if their is a way to expose the account email token so that I send emails to the user.

The rule I have setup is as follows and I have exported the rule which can be found below.

Event: After saving a new profile

Actions: Send HTML e-mail

{ "rules_email_banking_details" : {
    "LABEL" : "Email Banking Details",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "mimemail", "profile2" ],
    "ON" : { "profile2_insert" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "[site:name]",
          "to" : "[profile2:field_account_email]",
          "subject" : "Banking Details for accounts that you must make a  payment to.",
          "body" : "[profile2:field_name_of_your_bank]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If anybody has some advice that could help it would be much appreciated.

Your token will be - [profile2:user:mail]. It is available in your rule with the setup that you described. You might not see it in replacement patterns for the "to" field when you are using "direct input" mode, but if you switch to "data selection" mode - you'll be able to find that token much easier.


D8 Webforms Predefined Options How would you use/access D8 Webforms Predefined Options (such as days,months,gender, marital status,country etc,etc) in code, say in MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id). Where is the predefined options data stored ?

For example, for country codes options ["AF"=>"Afghanistan","AL"=>"Albania",....,"US"=>"United States",..] how would you get country name from country code.

Your aasistance will be greatly appreciated.

You can alter the options in this hook:

/**
 * Alter form options by id.
 *
 * @param array $options
 *   An associative array of options.
 * @param array $element
 *   The form element that the options is for.
 * @param string $options_id
 *   The form options id. Set to NULL if the options are custom.
 */
function hook_webform_options_alter(array &$options, array &$element, $options_id = NULL) {

See http://cgit.drupalcode.org/webform/tree/webform.api.php

The options are stored in the config entity webform_options, see http://cgit.drupalcode.org/webform/tree/src/Entity/WebformOptions.php


Is Drupal appropriate for what I want to do? I am building a simple portfolio site for a friend. The vast majority of the site will be static, but I'd like to implement a kind of news/mini-blog on the front page, just two divs where he can update the site with his latest news.

Is Drupal overkill for implementing this kind of thing? Moreover, how simple would it be to set up; I have no CMS experience whatsoever.

f you don't have any plans to expand the site in near future, then Drupal is an overkill.
The whole system is just too big for your purpose, and offers lots of functionality your friend won't ever need: permission system, roles, user profiles, content types, fields, forum, and comments. Especially as you don't have any CMS experience, Drupal will take the most time to setup, and you will need to learn a lot during the process.

I suggested WordPress because it is generally used for such websites by designers, takes less time to setup, and there are much more available themes and non-developer user tutorials. IMO, this would be the fastest option to setup.

Lastly, a custom CMS might be the best fit for this. If you don't have any ideas what to use, take a look at these frameworks: Codeigniter, Laravel or Yii.

Or, if you want to make it fun for you, use some micro framework: Flight (PHP 5.3+), or Slim (PHP 5.2/5.3). Pair it up with some tools/libraries for ORM/AR like Paris and Idiorm, RedBean, and/or an "unframework". If you want to get really fancy, add an MV* JS library like Backbone.


How to display a form in a panel page? My goal is to display a form in a page made with panels. The form will be between content panes.

The single page (made with page manager & panels) will be like below:

Content Pane
Form
Content Pane

How can I achieve that, and display the form in a page made with panels ?

Update 2-4-2014:
I found this article and created the following block that doesn't work (I am getting an error when trying to add that to panels). can sombody help make this thing work?

<?php
function my_answer_form_block_info() {
    $blocks = array();
     $blocks['my_answer_form'] = array(
            'info' => t('My-Answer-Form'),
            'cache' => DRUPAL_CACHE_GLOBAL,
    );

    return $blocks;
}

function my_answer_form_block_view($delta = '') {
    $block = array();
    switch($delta) {
            case 'my_answer_form':
                    $block['subject'] = t('My Answer Form');
                    $block['content'] = drupal_get_form('answer_node_form');
            break;
    }
     return $block;
}
  ?>

Note: Form ID is: "answer_node_form"

I am using the Answers Module. The form I want to put on the panel page is the Answer Form, that was created by the Answers Module. Is that a node form or a custom form?

If it is node form you could use Form Block. It will create form in block and you could add that in content panes.

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


Not able to reference Javascript functions inside jQuery wrapper I have custom module called interface, through which I'm adding a javascript file. This code is in plain old javascript, no jQuery, and has been working for me.

I now want to be able to add some jQuery functions to this code, I thought this would be possible since jQuery and javascript should be compatible with each other, right?

So here's a simplified example of what I'm doing inside the .js file:

(function ($) {
    Drupal.behaviors.interface = {
    attach: function()
    {
        function foofunction() {
        // execute some code
        }
    function WelcomeScreen()
    {
        Screen.apply( this );
        this.html = function(){
        return "

";
        };
this.activate = function(){
document.getElementById("main").innerHTML = "Test";
        };
        }

    }
    }
})(jQuery)

This code results in the following error in Chrome dev tools:

Uncaught ReferenceError: foofunction is not defined

My guess is that somehow the required jquery wrapper or the drupal behaviors wrapper are causing the functions to no longer be 'global'.

One obvious answer, I think, is rewriting everything in proper jQuery syntax. But I'm interested in how to make these javascript functions compatible with jQuery.

First off, onClick misses an = sign. Secondly, Chrome is right. From the point of view of the <a id="button"> element, the function is not visible even though it seems to be in scope of WelcomeScreen function. That's because it's not the function that invokes it, but the element on a page. Try onClick="Drupal.behaviors.interface.foofunction()". But better off - make it unobtrusive by removing the onClick attribute and saying at the document.ready level:

(function ($) {
    Drupal.behaviors.interface = {
    // code
    }

    $(function(){
      $('#button').live('click', Drupal.behaviors.interface.foofunction);
    });
})(jQuery)

Of course this is just a rudimentary suggestion, you might want to optimize the code further. If you're using jQuery 1.7+, you'd rather use .on() than .live().


How can I make a container resizable? I've the body field as container. When I add
'#resizable' to the field with hook_form_alter(), it is not getting resizable.

function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
    kint($form);
//      $form['body'] = [
//        '#resizable' => TRUE,
//      ];
  }
}

How can I make it resizable?

In the official documentation

says the following:

  "#resizable": Controls whether the text area is resizable. Allowed values are "none", "vertical", "horizontal", or "both" (defaults to "vertical").

in this documentation we can see, that this property "#resizable" is applicable only to textarea.

Then, you can try:

function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
    $form['body']['widget']['0']['#resizable']='horizontal';

    //or
    //$form['body']['widget']['0']['#attributes']["style"]="resize:vertical";

  }
}

if you change the text format in "restricted HTML" you will see

if you want to use the "both" parameter

function test_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_page_edit_form' || $form_id == 'node_page_form') {
      $form['body']['widget']['0']['#resizable']='both';

  }
}

if you change the text format in "restricted HTML" you will see: