Correct way to add language switcher to a menu I'm trying to add a language switcher to one of my menus using the hook_preprocess_page():

function <MODULE>_preprocess_page(&$variables) {
  // append language switcher to top_menu
  if(drupal_multilingual()) {
    global $language;
    include_once DRUPAL_ROOT . '/includes/language.inc';
    $info = language_types_info();

    $lang_types = language_types_configurable(FALSE);

    $path = drupal_is_front_page() ? '' : $_GET['q'];

    foreach($lang_types as $type) {
       $languages = language_negotiation_get_switch_links($type, $path);
       if(isset($languages->links)) {
         foreach($languages->links as $lang => $link) {
           if ($lang != $language->language) {
             $alias = drupal_get_path_alias($link['href']);
             $info = path_load(array('alias' => $alias));
             if(drupal_is_front_page()) {
                $alias = '';
             }
             $variables['page']['top_menu']['menu_block_2']['#content'][] = array(
                '#theme' => array('menu_link'),
                '#title' => $link['title'],
                '#href' => $alias,
                '#attributes' => array(),
                '#query' => array('language' => 'sv'),
                '#localized_options' => array('query' => $link['query']),
                '#below' => array(),
                '#original_link' => array(),
                '#bid' => array('module' => 'menu_block', 'delta' => 2)
             );
          }
        }
      }
    }
  }
}

I display the normal top menu in my page.tpl.php like this:

      <?php if(isset($page['top_menu'])): ?>

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

The above code works fine for my normal menu, but I also have a mobil menu which content I store in the following two variables:

function <THEME>_preprocess_page(&$variables) {
  $main_menu_tree = menu_tree_all_data('main-menu');
  $variables['main_menu_expanded'] = menu_tree_output($main_menu_tree);
  $top_menu_tree = menu_tree_all_data('menu-top-menu');
  $variables['top_menu_expanded'] = menu_tree_output($top_menu_tree);
}

Then in my page.tpl.php file I output the contents for my mobil menu like this:

  <?php print render($main_menu_expanded); ?>
  <?php print render($top_menu_expanded); ?>

The strange thing is that the language switcher isn't added to the mobile menu, while it turns up without any problems in the normal menu.

It's not strange it's a question of order.
You use theme_preprocess_page and module_preprocess_page.
theme_preprocess_page runs first, this mean you save your menu before you change it.
Easy option would be, to add your theme_preprocess_page part to your module_preprocess_page.
(Set it outside of the if(drupal_multilingual()) {} and it run even if the if return false)
Better option would be to create a module for your mobile menu,
and set it's weight so it run after your other module.

EDIT: Ignore the Part about the order this https://www.drupal.org/node/223430  confussed me so i thought about template_preprocess_hook not the theme_preprocess_hook.
The Problem is your call, you think you add the switcher to the menu. But you just add temp items. On your call for mobile you get the original  Menu (so no lang switch).
You could fix it by adding the lang fix to the menu and not temp.
You could extend your module so you would get the new Menu for your vars.


Redirect according to views filter input I have a view with two filters (country and city) on node (country) page. What I want is redirect to another node page according to user input (filter country). So if user viewing page node/uk and chooses USA in country filter and New York in city filter, drupal must redirect to page node/usa showing results for New York. View is using AJAX.
Tried using drupal_goto in views exposed form submit but this produces error Drupal.Views.Ajax.handleErrors is not a function in ajax_view.js. Help me please.

You can do it using hook_form_alter() on the exposed filter form.
It is very well explained in this post.
A drupal_goto() depending on the input entered should work.


Can you link an image field to a link field by 'Manage display'? I have a content type with two fields: image and link. I'd like the image to display linked to the link field. I'm happy to do that myself programmatically, I'm just wondering if there's a module that lets you do this directly from the Manage display screen (ie zero code).

Using Linked Field and Token module, you can easily do this by checking "Link this field", and entering the appropriate token of your Link field.

Here is an example:

Destination:

[node:field-test-link:url]

Title:

[node:field-test-link:title]


Cache clearing without drush I am using Drupal 8, and I am wondering how I can clear more caches than the button in admin/config/development/performance does.

I have had trouble with installing Drush, so I am looking for any alternative solutions.

Just execute core/rebuild.php.
As the documentation says, it rebuilds the cache even when Drupal doesn't work; it require a token you can generate with scripts/rebuild_token_calculator.sh, so you call it as http://example.com/core/rebuild.php?token=TOKEN_YOU_GET_FROM_THE_SCRIPT.


How to check for view mode in twig template? We have one field (field_tabs) that is used on Basic and Article content type. On the Basic page content type, it has a custom view mode (view_mode_vertical) and on the Article content type it has a different custom view mode (view_mode_horizontal).

Basic Page (default view mode) Manage Display

field_tabs (view mode = view_mode_vertical)
title
body

Article (default view Mode) Manage Display

field_tabs (view mode = view_mode_horizontal)
title
body

In a field.html.twig, how can we detect the view mode?

Our two options we explored was either a node template or field template (we went with field). We would like to do this in a way that we only need add the logic for detecting the view_mode in one place. In case we add a third or fourth view_mode, we can simply add another elseif (or switch case) to the code.

Sample Twig code we were looking for:

{% if view_mode == 'view_mode_vertical' %}

...

{% else %}

...

{% endif %}

In a field.html.twig, how can we detect the view mode?

In a field template there is no top level variable for the view mode like in the node template. You can create one and then your twig code should work:

{% set view_mode = element['#view_mode'] %}

Another option is to add a template name suggestion, see Field template for display mode.

Both are valid options. There are many projects heavily depending on Twig logic while other projects prefer PHP in preprocess and template name suggestion hooks.


Mail not going from SMTP I have configured the smtp for drupal , as said in this link https://www.drupal.org/project/smtp and my smtp module folder lies in /sites/all/modules/smtp and phpmailer library lies in /sites/all/libraries/phpmailer .
But am getting the following error on sending the test mail from the drupal admin SMTP authentication support .

2015-07-09 14:37:30 Connection: opening to ssl://smtp.gmail.com:465, timeout=300, options=array ( ) 2015-07-09 14:41:45 SMTP ERROR: Failed to connect to server: Network is unreachable (101) 2015-07-09 14:41:45 Connection: opening to ssl://:465, timeout=300, options=array ( ) 2015-07-09 14:41:45 SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed: Name or service not known (0) 2015-07-09 14:41:45 SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

And these are my smtp parameters ,

Any help is appreciated . Thanks .

Your host cannot reach smtp.gmail.com on port 465. It sounds like a network connectivity problem, not a Drupal problem. Run the command nc -zv smtp.gmail.com 465 to confirm.

You may need to talk your hosting provider if they have restrictions in place. My guess, if they are blocking it, is they are blocking SMTP access to GMail to prevent spam.


Views- Show a table of users with each column indicating whether or not a user has a role I am using Views Data Export to get data on my Drupal users into Excel.  My site has a large number of roles (Roles A - Z), and some of these are important for user statistics.

The view I use for data export is a table of fields.  I added Roles as follows:

This gives me something like RoleA, RoleC, RoleD, RoleI for each user.  This sort of data is difficult to manipulate in Excel.

What I would like to do instead is to have a column in the table for each important role that has 1 if the user has the role, or 0 if the user does not have the role.

In other words, my table looks like this now:

But I want it to look like this in Views:

Here's a solution using a simple module and a custom field template.

Overview

The view (obviously of the User Table) should only contain one field: User: Name. All of the other Role columns are generated by implementing HOOK_views_pre_view() with a loop for each defined role. The module also defines a custom function that compares the original output (comma-separated list of roles) and returns true if the list contains the current column's role.

The custom views field template simply calls the custom function for each column that corresponds to a role.

This solution will automatically scale if you add/delete roles and adjust if you rename/reorder roles etc.

Module File

You'll obviously need an info file too. I chose to name the module views_urt (User Role Table) - but you can name it whatever you want or include these functions in an existing custom module if you choose.

<?php
/**
 * Implements HOOK_views_pre_view().
 *
 * Adds a field to the User Roles view for each role defined.
 */
function views_urt_views_pre_view(&$view) {
  if ($view->name == 'user_roles') {
    $roles = views_urt_roles();
    $count = count($roles);
    for($i=0;$i<$count;$i++) {
      $view->display['default']->handler->options['fields']['rid_' . $i]['id'] = 'rid_' . $i;
      $view->display['default']->handler->options['fields']['rid_' . $i]['table'] = 'users_roles';
      $view->display['default']->handler->options['fields']['rid_' . $i]['field'] = 'rid';
      $view->display['default']->handler->options['fields']['rid_' . $i]['label'] = $roles[$i];

    }
  }
}

/**
 * Determines if a comma-seperated list of roles contains the role of the
 * current column.
 *
 * @param $pos integer
 *   The column corresponding to the $field->position value in the view.
 * @param $user_roles string
 *   Comma seperated list of Roles (haystack)
 * @return bool
 */
function views_urt_has_role($pos, $user_roles) {
  $pos = ($pos -1);
  $user_roles = explode(',', $user_roles);
  $defined_roles = views_urt_roles();
  foreach ($user_roles as $user_role) {
    if (trim($user_role) == $defined_roles[$pos]) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Helper function that returns an array of roles exluding "Anonymous" and
 * "Authenticated" user.
 *
 * @return array
 *   An array of roles.
 */
function views_urt_roles() {
  $roles = user_roles();
  array_shift($roles);
  array_shift($roles);
  return $roles;
}

Views Field Template File

This template should be picked up by all of the fields in this view for all of the displays. So, since my view is named user_roles, this template is named views-view-field--user-roles.tpl.php.

<?php
if ($field->field_alias == 'users_name') {
  print $output;
}
else {
  // We're assuming that this view only has one field (User: Name). All other
  // fields are generated by the HOOK_views_pre_view() function in the
  // `views_urt.module` and those should be passed through the
  // `views_urt_has_role` function which determines if the $output
  // (comma-seperated roles per user) contains the column role.
  print views_urt_has_role($field->position, $output);
}
?>

Sample Output


What's the correct way to install Drupal with Composer if I want to work on core issues? I want to install a local Drupal site in such a way that Drupal core is a git repository so I can work on patches.

Just doing a git clone doesn't work, because I also need tools such as Drush, and installing those in a git clone of core changes the composer.json file that belongs to core.

What's the correct way of doing this?

I am not sure if there really is a correct, or best way.  All of the core devs I have interacted with have their own setup that works best for them.

My general setup is

directory per remote branch: right now I have drupal-8.8.x, drupal 8.9.x, and drupal 9.0.x
git branch for each patch that is in the issue-comment form: 3113284-02, 3113284-04)

I do this because I have a bunch of shell scripts for installing, cleaning, diffing, generating patches, running tests, etc.  All of these scripts get ignored.

As far as drush goes, I keep a global install and checkout a tag periodically.  I then have a .envrc in each branch directory to $PATH everything correctly.  This prevents changes to composer.json.

However, there are some things you can try. A while ago, running tests locally with certain PHP versions meant updating phpunit via a post-composer script.  You then had to restore composer.json and composer.lock before running a git diff ... to generate a patch/interdiff.  You can do the something similar with drush:

git pull origin/8.8.x
composer require drush/drush:^10
git checkout composer.json composer.lock

The above approach is on my short-list for updates to my scripts.


How do I use .htaccess to trigger mod_rewrites before D7's Clean URLs take over? I am migrating from olddjango.com to newdrupal.com, and need a way to alter the URLs from the old style into the a format we've chosen for the new Drupal application.

In addition to rewriting them, I want the final "corrective" rule to redirect, to register the 301.  The structure of the URL has a marker that I'm using as a RewriteCond, it is the last thing I change before the redirect (so the URI won't get rewritten unless it is from the old site).

I've written a small number of mod rewrite rules, which work well enough in http://htaccess.madewithlove.be/

If I put them in my /etc/httpd/conf/httpd.conf they work smashingly... but that isn't a viable option. (it theoretically COULD be... but only as a last resort)

However, when I put them in /.htaccess, they do absolutely nothing...

I put them at the top of the file, before anything else, I put them at the bottom... and in the middle.  I tried with and without "RewriteBase /"...

I'm obviously missing something, or the nature of D7 disallows pre-empting the machinations of Clean URL.  I've found at least one person saying it was possible, but no one saying there were any special tricks involved, or actual documentation... so I'm just trying to get an answer committed to the interwebs one way or the other.

This is the final rule of my section of rewrites:

RewriteCond %{REQUEST_URI} ^/?gbnk/?.* [NC]
  RewriteRule ^/?gbnk/?(.*) $1 [NC,R=301,L]

Personally, I would see if the Redirect module works for your needs.  Is it basically a UI interface for making 301 redirects.  Off the top of my head, though, I don't recall if it will work with patterns.

If that doesn't work, then your best bet is to put them in the .htaccess right after the

# RewriteBase /

line.

Just remember that mod_rewrite will continue to process rules unless you use the L flag.  You also want to explicitly give the response code with the R flag.  Something like this should work

# RewriteBase /

RewriteRule ^some/path/(.*) /other/place/$1 [R=301,L]
RewriteRule ^another/hierarchy/(.*) /different/thing/$1 [R=301,L]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

Keep in mind that rewrites can be frustratingly hard to debug, but logging can help.  Also make sure you are using rewrites and not redirects.  Mixing mod_rewrite and mod_alias in same .htaccess will cause all sorts of grief because of process order.


Unique Fields with the ability to be a reference to multiple records I wonder to know is it possible to have an unique field (let consider a text filed), when we input a data into it firstly it check the table if it doesn't exist add a record, if it find a record refer to it?

i.e.: I have a field in my content type to store telephone number whenever I want to add a new node, after entering the data into the telephone field if the number was stored in my database instead of creating a new record in the table I just reference to the number

My aim is to have a contact list of some users that submit a form but I don't want duplication (just unique phone number and name)

I would envision this as

Create a rule that post a node each time the form from anonymous user is submitted.
Create a condition before creating a node - the condition will loop through all entered node telephone numbers if they found that the user has already entered the data don't do anything other wise post the node with phone, name and email information.


drupal 7 date field stores todays date even when user hasnt entered a value I don't want it to! :-)

I'm using custom forms implementing a date field, then saving values manually to a node later. I could add an extra step preventing the value from being saved to the node, but I won't have the necessary info available to calculate whether to do this if it's an 'edit'.

Any ideas? I just dont want to save a value if the users doesnt enter anything. Seem's simple enough to me... :-S

By Form API reference you need to manually set '#default_value' to prevent it from defaulting to today. So just add:

'#default_value' => NULL,

to your field's array to prevent it.


Ajax based commenting system In Drupal 7 I'm facing one problem, I'm going to implement a comment system in that way that it should work as chatting systems. I've a content type Article, at the end there is a comment box where users can leave comments.

If I add a comment to the article it should be showed in every user's browser if they are viewing it, and at the same time they can debate/talk about that article without refreshing the page.

It will be real time commenting.

We have solved this issue with two modules

Ajax Comments

  Provides ajax comments to Drupal sites (commenting like a social networking sites: Facebook, Google+, vk.com etc).

Block Refresh

  Block Refresh allows an administrator to configure a block to refresh it's content via 3 different methods: automatically via a timer (eg every 30 seconds) , manually via a 'refresh' link, and once on page load.

You can view the real sample at http://beinghuman.org/.


Passing arguments with special characters I want to pass a token into my custom module via the URL, like so:

http://example.com/myurl?token=ffjei4T93F/ggF0PImZxlDWSR8JYHaPmkkjLSUVSKkr

Drupal has issues with passing tokens using clean URLs:

https://www.drupal.org/node/118072

...and because my token has a '/' forward slash in it it breaks if I use arg(1) to get the token.

What to do?

For Drupal 7, use drupal_get_query_parameters().

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_get_query_parameters/7.x


How can I exclude the link for the current page when I have a list of links in Views? I'm using Drupal 7 with Panels and Views.

I've configured a view to list several links to different panels.  This view is displayed as a content pane on each of the respective panels to allow for easy navigation.  However, this means that the link to each page is shown on that page as a link, which is unsightly and confusing.

Within Views, is there a way to configure the filters, etc. to hide or (best case) rewrite the link so that it is shown as plaintext rather than a link if it is pointing to the page being shown?

I had a similar problem with displaying node revision links on a node page, views would display the link to the current node being displayed. To fix this I edited the views template file and checked myself whether the link pointed to the current page or not and only displayed a link if it wasn't to the current node.


How do you transfer ownership of a Drupal contrib module to someone else? I own the S3FS and Date iCal Drupal contrib modules, though I abandoned development on them quite a while ago, due to moving all my work to another platform. However, I am still on the record as the "owner" of these modules, despite there being other maintainers who have taken over.

There's no obvious way to remove myself as owner. I can't uncheck any of my permissions from the Maintainers listing. There doesn't appear to be any UI that lets me designate an existing maintainer as the new owner.

What do I do?

You can either:

Open an issue on the Drupal.org project ownership queue, asking to make the new project owner a user on drupal.org that you know be willing to become the new project owner
Open an issue on the same queue, asking to make the new project owner the maintainer who did more commits or who was more active in following and answering the project issues
Open an issue in the same queue, stating you are seeking for a new project owner, using Needs maintainers as Component value

Once you open the issue queue, the procedure will be handled by Drupal.org site moderators.
As alternative, you could simply set the Maintenance status field of the project to Seeking new maintainer and (eventually) the Development status to No further development. Users who need the project, and who are able to develop code for a project, seeing you set that status, could ask to be the new project owner or maintainer, if they are interested.
Finally, if you think you won't maintain anymore a project hosted on drupal.org and you won't use Drupal, you could delete your account on drupal.org. Authenticated user are now able to delete their account on drupal.org, for any reason they could have.


AJAX calls in CTools Content Type Plugin? I'm building a CTools Panels Content Type (i.e., that thing you insert into panels when adding content, not a type of node) and I am trying to use a form item's #ajax attribute to set some default values. See code below.

This is all inside of the content type's my_module_content_type_edit_form($form, &$form_state) call, by the way.

  $form['link_type'] = array(
    '#type' => 'radios',
    '#title' => t('Link Type'),
    '#ajax' => array(
      'callback' => 'my_module_set_target'
    ),
    '#default_value' => empty($conf['link_type']) ? '_blank' : $conf['link_type'],
    '#options' => array('none'=>t('No Link'), 'internal'=>t('Internal Link'), 'external'=>t('External Link'), 'document'=>t('Document Link')),
  );

My callback is the following.

function my_module_set_target($form, $form_state) {
  watchdog("Test", "Testing callback", array(), WATCHDOG_ALERT);
  $form['link_target']['#default_value'] = '_parent';

  return $form['link_target']['#default_value'];
}

Regardless of whether the return I'm suggesting would actually work, watchdog() doesn't even work.

I know CTools does some weird stuff with AJAX, but it can't be that weird. Do you have any idea on how I'd do what I'm wanting to do?

Thanks!

Alternatively: How do I set a default value based on the value of a previous form option?

I figured out how to do this, but it's a bit hacky -- you create new form fields for each dependency fork. You can then merge the values together in hook_content_type_edit_form_submit(), using whichever one corresponds to the value chosen for the component that initially forked everything.

I'm leaving the question open because I (and, frankly, every programmer I'm working with) is really wanting a good way to use AJAX inside these Panel content type edit forms.

Update: It appears you can't do stuff with #attached, either.

$form['link'][$i] = array(
  '#type' => 'fieldset',
  '#title' => t('Link #@num', array('@num' => $i)),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#attached' => array(
    'js' => array(
      'alert("Yay.");', 'inline'
    ),
  )
);

Short answer: you should use #ajax['path'].

Long answer:

Having a ajax callback does not help as ctools creates it's forms differently afaik. The callback done by system/ajax cannot find the complete form definition thus cannot find an element to process the ajax request for. Using #ajax[path] just triggers a menu item.

You can check for yourself by dumping the form when using #ajax[callback]

function ajax_form_callback() {
  list($form, $form_state) = ajax_get_form();
  drupal_process_form($form['#form_id'], $form, $form_state);

I've modified the simplecontext_content_type_edit_form by adding the user autocomplete widget and your field which both work :)

function simplecontext_content_type_edit_form($form, &$form_state) {
  $conf = $form_state['conf'];

  $form['owner_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#default_value' => 'admin',
    '#autocomplete_path' => 'user/autocomplete',
    '#size' => '6',
    '#maxlength' => '60',
    '#description' => '$description',
  );

  $form['link_type'] = array(
    '#type' => 'radios',
    '#title' => t('Link Type'),
    '#ajax' => array(
      'path' => 'my_module_set_target'
    ),
    '#default_value' => empty($conf['link_type']) ? '_blank' : $conf['link_type'],
    '#options' => array('none' => t('No Link'), 'internal' => t('Internal Link'), 'external' => t('External Link'), 'document' => t('Document Link')),
  );
...

As you now use #ajax path you need to add a menu item as I did like

<?php

function my_module_menu() {
  $items = array(
    'my_module_set_target' => array(
      'title' => 'AJAX Example',
      'page callback' => 'my_module_set_target',
      'access callback' => TRUE,
      'expanded' => TRUE,
    )
  );
  return $items;
}

function my_module_set_target() {
  drupal_json_output( array('data' => "ABC"));
}

A nittpick about #attached[js]: the inline js should be key => value like:

'#attached' => array(
  'js' => array(
    'alert("Yay.");' => 'inline',
  ),
),

I've used Firebug to check for the resulting value not the resulted effect. So I hope this helps to fix your problem.


How to programmatically set a node field as empty? I have some nodes of a content type with following fields:

title
body
image

I want to programmatically (!important) set the body field as empty (to make it like it was never set with any value).

This is what I have done:

$this_node = node_load($nid);
$this_node->body = array(); //to set it as an empty field
node_save($this_node);

After executing this, the node is not saved. Instead, in db_log following error is loged:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '104418'
for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created,
changed, comment, promote, sticky, tnid, translate, uuid) VALUES
(*******placeholders & their values*******) in drupal_write_record()
(line 7170 of /var/www/rotary.local/docroot/includes/common.inc).

Is there someting I am missing? How I can set the body field as empty?

NOTE:

I don't want to use field_attach_update for caching purposes.

To remove the value from you field you should do like this before saving it:

$this_node->body[$this_node->language] = array();


Customizable labels in custom fields For a new website I have a list of products with specs, but most of the time the specs are different for each product, because there are a lot of types of products.

Right now I just have a new field for every type of spec, but I want the client to be able to do this themselves.
Is there a module that enables me to customize the label for each field?

So let's say the client can add a field, fill in the label and value himself?

You can use 'Field collection' in your content type for products, In your  field collection field keep one field as label and other for the value. This approach will suit your needs


Create a route to show a node with a custom display/view mode In Drupal 8, it is easy to add display/view modes. Let say I created the tech display mode and I set it up for the film content type.

Now, I would like to create a route for it and access it as local task of entity.node.canonical.

How can I achieve this?

In Drupal 8 there are two display modes: view mode and form mode.

You can define the view mode in a route using the _entity_view key.

  _entity_view: The value is entity_type.view_mode. Will find an entity in the path and render it in the given view mode. E.g. _entity_view:
  node.teaser will return the render array of the {node} in teaser mode.


Drupal 7 dynamic dropdown list options An illegal choice has been detected I have created a node type of Advertisement which holds all the information for adding new advertations to the website, including categories.

there are 3 levels of categories and i need to make a seperate box for them. The content type which i created through the GUI of drupal already has a term reference select box for category, sub category, and level 3 category..
So i made a module and implemented hook_form_alter and i added the #ajax attributefunction

<?php
adverts_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'advertisement_node_form') {
      $topLevelTermArray = array('_none' => ' - Select a value -');
      $topLevelTerms = array(5275, 5245, 5299, 5341, 5702, 5681, 5826, 5555, 6039, 5592, 5776, 5994, 6027, 5451, 5852, 6016, 5496, 5475, 6049);
      foreach($topLevelTerms AS $value) {
        $term = taxonomy_term_load($value);
        $topLevelTermArray[$term->tid] = $term->name;
      }
      $form['field_specific_category']['und']['#prefix'] = '
';
      $form['field_specific_category']['und']['#suffix'] = '
';
      $form['field_sub_category']['und']['#ajax'] = array(
        'callback' => 'ajax_sub_category_callback',
        'wrapper' => 'field_specific_category_replace',
      );
      $form['field_sub_category']['und']['#prefix'] = '
';
      $form['field_sub_category']['und']['#suffix'] = '
';
      $form['field_sub_category']['und']['#options'] = array('_none' => t('- Please select a category -'));
      $form['field_specific_category']['und']['#options'] = array('_none' => t('- Please select a sub category -'));
      $form['field_category']['und']['#options'] = $topLevelTermArray;
      $form['field_category']['und']['#ajax'] = array(
        'callback' => 'ajax_category_callback',
        'wrapper' => 'field_sub_category_replace',
      );
  }
}
?>

And 2 callback functions

function ajax_category_callback($form, $form_state) {
  $subCats = array();
  $tree = taxonomy_get_tree(5, $form_state['values']['field_category']['und'][0]['tid']);
  foreach($tree AS $term) {
    $subCats[$term->tid] = $term->name;
  }
  $element = $form['field_sub_category']['und'];
  $mainCatTerm = taxonomy_term_load($form_state['values']['field_category']['und'][0]['tid']);
  $element['#title'] = t('Sub categories for @cat.', array('@cat' => $mainCatTerm->name));
  $element['#options'] = $subCats;

  return $element;
}

function ajax_sub_category_callback($form, $form_state) {
  $subCats = array();
  $tree = taxonomy_get_tree(5, $form_state['values']['field_sub_category']['und'][0]['tid']);
  //var_dump($form_state['values']['field_sub_category']['und'][0]['tid']);
  foreach($tree AS $term) {
    $subCats[$term->tid] = $term->name;
  }
  $element = $form['field_specific_category']['und'];
  if(empty($tree)) {
    $element['#options'] = array('_none' => '- No specific category -');
  } else {
    $mainCatTerm = taxonomy_term_load($form_state['values']['field_sub_category']['und'][0]['tid']);
    $element['#title'] = t('Sub categories for @cat.', array('@cat' => $mainCatTerm->name));
    $element['#options'] = $subCats;
  }
  return $element;
}

But when i go to node/advertisement/edit and i select a category and sub category is show's:

An illegal choice has been detected. Please contact the site administrator.

How can i get that error too dissapear?

The value you are submitting was not present during the page or form loading time.

If you populate some values using ajax which was not present in initial page loads and try to submit the form, then Drupal will not allow you to submit the form. It will always shows "An illegal choice has been detected" message.


Workbench Delete or Unpublish Multiple Nodes I have recently installed work bench, when we view all contents there is no option to select multiple nodes and apply delete or unpublish action on them. I need to edit each node and then delete each node separately. Please suggest any solution.

I cloned the ie. needs-review view

and added field "views bulk operations: Content", marked a few possible actions,

rearranged the fields so bulk ops are first col as one expects

and that's it.


how to print sql query of view in runtime I would like to see view's sql query that is executed in runtime. I found this method in google, hook_views_pre_execute, but I am really beginner in drupal. Where I have to apply this method, when I put this method as project_views_pre_execute in template.php, nothing is shown and I don't know why, is it needed to write it in custom module?

Any suggestion is greatly appreciated.

The Devel module provides a SQL query log for debugging/performance testing. You can enable this under Configuration > Development > Devel settings (/admin/config/development/devel) and by setting Display query log option.

Once enabled, the bottom of the page will contain all SQL queries executed in page rendering. For your needs, you'll need to look for views_plugin_query_default::execute function calls (the where column) to see the SQL query executed for your view.


How to hide the filename in drupal 7 files and add link to icon? I would like to know how to hide the filename in Drupal 7 files and add a link to an icon? The default style is awful I would like to change that.
I am looking for the simplest solution because I just know basic HTML and CSS.
Maybe I can use some module to do that? If somebody can explain me step by step how to do it will be great.

Ran across your question looking for the same answer... This is what I found. I'm at best a novice with Drupal, so I need easy solutions.

There is this module: https://www.drupal.org/project/file_field_icons

There are also some more options/notes here using CSS: How to change File field icons (without changing core)?


Can't get template suggestions to be recognized I am using D7. I have declared a custom template facet-item.tpl.php in a module named dsfacet. My code goes as follows:

/**
 * Implements hook_theme().
 */
function dsfacet_theme($existing, $type, $theme, $path) {
  return array(
    'facet_item' => array(
      'variables' => array('facet_name' => NULL, 'facet_values' => array()),
      'template' => 'facet-item',
    ),
  );
}

This custom template is invoked from another template with the following code:

<?php foreach ($facets as $name => $values): ?>
<?php print theme('facet_item', array('facet_name' => $name, 'facet_values' => $values)); ?>
<?php endforeach; ?>

Everything works great so far, but I'd like my theme to use more specialized templates based on the facet name.

So here's what I did:

1) I declared a template suggestion based on the facet name:

/**
 * Implements template_preprocess_HOOK for facet-item.tpl.php.
 * Adds template suggestions.
 */
function template_preprocess_facet_item(&$variables) {
  $variables['theme_hook_suggestions'][] = 'facet_item__' . $variables['facet_name'];
}

2) I changed the theme invocation to take into account the facet name:

<?php print theme('facet_item__' . $name, array('facet_name' => $name, 'facet_values' => $values, 'node' => $node)); ?>

3) I created some templates based on facet names:

facet-item--address.tpl.php
facet-item--phone.tpl.php
...

I then cleared the cache but... nothing happens. Only the main template facet-item.tpl.php is used. After a few hours spent on this, I'm at my wit's end. Any ideas?

(I've tried hard-coding the facet name everywhere to make sure it wasn't a problem with my variables... I've also tried every possible permutation of singe/double dashes/underscores...)

It took me a bit to figure this out and what I came up with is that the issue appears to be that Drupal's Theme System will only look for dynamic templates if they are in an actual theme, not in with a module.

So, you can do one of two things, the first one obviously being to copy all of your facet-item templates into your theme directory and call it a day after clearing caches for Drupal to pick them up.

Or... you could get creative like the Views Module does and create theme registry hooks for each of the template files like so:

function dsfacet_theme($existing, $type, $theme, $path) {

  $hooks=array();
  $modulepath = drupal_get_path('module', 'dsfacet');

  $hooks['facet_item']= array(
    'variables' => array('facet_name' => NULL, 'facet_values' => array()),
    'pattern' => 'facet_item__',
    'template' => 'facet-item',
    'path' => $modulepath . '/tpl/facet-items',
  );

  $hooks += drupal_find_theme_templates($hooks, '.tpl.php', $hooks['facet_item']['path']);
  // $hooks += _views_find_module_templates($hooks, $hooks['facet_item']['path']);

  return $hooks;

}

which if you have Views installed will actually use Views' _views_find_module_templates() function to do all the work for you. (it basically goes through the directory passed to it and looks for template files and creates $hooks['facet_name__foo'] for each one it finds.) If you don't have or want Views installed, you can just copy it out of views.module and include and rename it accordingly in your own module.

ADDITION/CORRECTION:  DUH; YOU CAN USE drupal_find_theme_templates() just as easily without worry about using/including Views' similiar private implementation.

And now if you have put all your facet-item templates under your module in their own directory structure (mostly so the find template function doesn't find any other templates and spin its wheels doing extra work) and cleared caches, you should now see all of your templates.


Custom views, css syntax I need some help to customize my events list with Drupal 7. I am a newbie to Drupal, css and php, but I am used to programming. I guess I need some help with css syntax here.
What I want is an event list from an event calendar with customized format of the titles, which link to the respective event. I got to the point where I can tell the Views structure in Drupal that I want a customized html format for that field and where I can enter a name for a new css class. Now I take it, that I can edit the theme's css file to format the titles. Embarrassingly, I don't get the code right, my experience with css is not sufficient. Can someone help me, please?

I entered "pretty-event-title" as new css class, the resulting page's source code looks like this:

 Test event
]

"Test event" shows up as blue link of 100% font size. I'd like to change size and especially the color (size was just fine by using h3 tags or something in the view).

How would the css snippet look I have to put into my css file?

Any help appreciated!
Best,
Verena

You can add something like this to your theme style.css file

.pretty-event-title a{
  font-size: 14px;
  color: red;
}

More info: http://www.w3schools.com/css/


I have logged out and the login block is missing,how do I login back? I had created a block that has replaced the default block on the frontpage i.e. the login block and I have logged out of the site so how do I log in back?

I have tried:

sitename/user/login
sitename/?q=user
sitename/?q=admin
sitename/subdirectory/?q=user

All it shows is "Page not found" or "Access Denied"
Is there any other way I could log in back to my site?

And I'm using Drupal 8

You can get the one time login url with drush command: drush uli;


How to use daterange field programmatically? I activated the Datetime Range core module and it works inside a content type, from the BO, but I want to use it in a custom form. I tried :

  $form['training_interval'] = [
    '#type' => 'daterange',
    '#required' => TRUE,
    // '#default_value' => 'TODO',
  ];

and also daterange_default, datetime_range and any value which could have been relevant giving the module code, but nothing is displayed. I must confess I feel silly...

If you programatically need to set a datetime range field when creating a node in a custom form submit handler for example, you need to to fill two values:
The start date value and the end date end_value.
$node = \Drupal\node\Entity\Node::create([
  'type' => $type,
  'title' => $title,
  'field_dates' => [
    'value'=> '2018-02-02T12:12:12',
    'end_value' => '2018-05-05T12:12:12'
  ],
]);
$node->save();


Showing only one feed from different URLs I am using the Drupal 7 core module feed aggregator to list rss feeds from different websites.
I am able to show 5 feeds in a block provided by the module itself as well as using views too(aggregator term type).
I want to show only one recent feed from different URLs which are provided by me in the aggregator module config. Right now it is showing 5 feeds from only two URLs.
It should come as:

*Most recent Feed from 1st URL

*Most recent Feed from 2nd URL

*Most recent Feed from 3rd URL

*Most recent Feed from 4th URL

*Most recent Feed from 5th URL

Can anyone please tell me how do I do that?

Your best option is to create an attachment display for each feed which selects just the most recent feed and combine them into a block display.


if statement with content of a form I searched a lot without success, i hope i can find the right answer for me.

I want to make a simple bet system, without any real money. At the time of the registration the user get x fakecredits. I decide to use the comment system to check how much the user wants to bet, so i added a field called bet to comment form.

What i want to do now is very simple as logic:

if (Bet < User Money){
 submit content;
}else{
 don't submit;
}

i already made a view that shows user money. i only need the if statement. I also created a module with module_form_alter, but i don't know what to put then.

Thanks in advance

Drupal version 7.x

Sounds like something to put in the field or form validation.

$form['#validate'][] = 'form_validate';

or

$form['your_field']['#element_validate'] => array('_field_callback_validate'),


Verify source of url call In hook menu, there is a url that is used to be called by some gps device to register its lcoation in the database.
Let say the url is
sitename.com/gps/location/123.123/456.456

But I want to make this url, so only authenticated devices/sources can call this.

How should we achieve this. May be we can use hash token, but I am not sure how to use this to verify the source which is calling the url.

Here is the code inside the hook_menu

$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access arguments' => array('access content'),
);

Any help?

$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access callback' => 'custom_is_allowed_location',
  'access arguments' => array(2, 3),
);

function custom_is_allowed_location($arg1, $arg2) {
   //IF LOCATION IS XXXXX THEN ALLOWED
   if($arg1 == xxxx && $arg2 == xxxx) {
       return TRUE;
   }
   return FALSE;
}


Issue with "Content: Has taxonomy terms (with depth)" with a content type with a repeated taxonomy I have and issue with the view filter "Content: Has taxonomy terms (with depth)".
In my view I'm filtering a content type who as two fields represented by the same taxonomy, and that view filter (Content: Has taxonomy terms (with depth)), do the filter of the union of all the values in the two fields of the same taxonomy. For example:

Taxonomy "Subjects":

deparment1

subject11
subject12
...
subject1n

deparment2

subject21
subject22
...
subject2n

deparment3

subject31
subject32
...
subject3n

Custom type: Annual enrollment

Fields:

...

Subjects enrolled on first period (reference to term Subjects and multivalue)

Subjects enrolled on second period (reference to term Subjects and multivalue)

...

View: Filter for enrollments

...

Content: Has taxonomy terms (with depth)(exposed)

...

For example, in this case, that filter (associated with a Taxonomy and not a content type field) will filter the results for the departments in both subjects enrolled on first and second period, and what I want is that the filter only affects one field (in my real case, I need two of these filters, one for each field).

My problem was that the view filter Content: Has taxonomy terms (with depth) search in the taxonomy_index table instead of a field of the content type, so I ended duplicating the Simple hierarchical select module (SHS) who's behavior is equal to the Content: Has taxonomy terms (with depth), and editing the query it does.


Checking for string in variable fails in twig I'm working on a twig template for use with a commerce product. Each product has a term applied to it like "Green Ball", "Yellow Ball", "Red Block", and "Purple Block".

I'm trying to take the variable that holds the term, check if it has a string in it, and then use that as the basis for a label. For example if its a Green Ball it would say "Order Ball" and if it was "Red Block" it would say "Order Block".

I'm marking this up based on examples but it always returns false.

{% if 'Ball' in product.field_myproduct_type|field_value %} Order Ball {% endif %}
{% if 'Block' in product.field_myproduct_type|field_value %} Order Block {% endif %}

I've both tried outputting the variable on its own to confirm the variable is correct and also tried replacing the variable from the conditional with a string to make sure the conditional is the proper syntax and both work as expected. I just can't seem to check in the variable.

I'm doing this from within a twig template that is a variant on commerce-product.twig

Via kint and a bunch of trial and error I identified the right way to do this:

{% if 'Ball' in product.field_myproduct_type.0['#plain_text'] %} Order Ball {% endif %}
{% if 'Block' in product.field_myproduct_type.0['#plain_text'] %} Order Block {% endif %}

Thank you 100pic for your assistance.


How can I change the "Edit" tab name to something more meaningful? I would like to change the Edit tab from Edit to Edit Client.  The content type is Client.

I tried using the following code in the bartik.theme file in the web/core/themes directory (running drupal 8.5.4).

function bartik_preprocess_menu_local_task(&$variables) {
  if (isset($variables['element']['#link']['title']) && $variables['element']['#link']['title'] == 'Edit') {
    $node = \Drupal::request()->attributes->get('node');
    if ($node && $node->getType() == 'client') {
      $variables['link']['#title'] = t('Edit Client');
    }
  }
}

Use hook_menu_local_tasks_alter see the docs. You can get a dynamic title combining tokens and the translation API.


how can I change the site name For some reason, I'm not able to change the name of this site.  I try to change the name to 'Test Name', as shown in this screenprint:

But after I save the page, the name is repopulated with the previous title.

It is an old drupal site with many years of modules and various admins working on it, so anything's possible. It does have Pathauto installed, but I can't see any place where that is overriding the site title.

Any thoughts?

Look in settings.php; I expect someone set $conf['site_name'] = 'Test name'.  Anything hard-coded there cannot be overridden.


Is there a easier way to disable and enable module for module development? I'm finding that every small change I make to the hooks I have to disable and re-enable a module. Is there a easy way to do this than having to go through to the module menu, uncheck the module, click save configuration and wait for a while, then recheck the module, and click save configuration again?

For quick disabling and re-enabling of modules, try drush dre module1, module2.

This is a Devel command, so you need to have that installed, and enabled.
You just need to be sure you put them in the right order according to their relative dependencies; should module1 be dependent on module2, it wouldn't work.


Multiple currencies in commerce kickstart How to make different prices for one product.I want to display product price in both currency that is euro/$ without any currency selector.

Commerce Multicurrency may help you, see this screencast form Commerce Guys.


How to hide VBO multipage selector in a view I want to hide / disable the VBO multipage selector above the table in my view but I don't find where to do it.

Anyone has an idea?

EDIT:
I am using the "VBO Export" module and my view is related to a media.
Here is a screenshot of the field : "Global: Views bulk operations"

on your views, it should be a field "Content: Node operations bulk form"

if you want totaly remove VBO, hide or remove the field, but if you want to hide specified action use " Only selected actions"


wget or curl executables not found. Curl activated but not working As I know so far Drush has some limitation on Windows. I need however, to get it working, and I have activated the curl module in php.ini. All you need is to uncomment the line:

extension=php_curl.dll

Now, I run phpinfo.php and it seems curl is activated, but I still get the console error:

  wget or curl executables not found.

I have restarted the Apache server several times but still no way out.

Is anyone able to help me up?

The problem was with the php.exe path in drush.bat

The solution is to properly edit it. In my case ( I use xampp ) here is the path:

@echo off
REM See http://drupal.org/node/506448 for more information.
@c:\xampp\php\php.exe "%~dp0drush.php" %*


Missing image file previews with Media I'm not sure if that was me messing around with Media, or is it Media's fault by de*fault*.
I'm using that module mainly for its ability to re-use uploaded media, but for some reason I cannot get the images real preview. What is the crucial setting to have an image file display its preview in the library and in the content type editor?

I must say with more and more experience using Drupal, I'm still perplexed when it comes to configuring Media file types and display options. Seems like one could fall into an endless loop when trying to manage files' display options.

Are you saying that the thumbnail images for file uploads aren't displaying (a broken image icon the browser)?

If so, depending on how you installed Drupal ... drupal (well your webserver) needs to own the /sites/default/files/styles directory, or else drupal cannot create thumbnails for preview on-the-fly.

This is a known Issue: theme_image_style_preview() and image_requirements() should check whether style directories are writable.


Redirect, change or replace the "user/register" link How to redirect, change or replace the "user/register" link
to another registration page, such as "civicrm/contribute/transact&reset=1&id=1"?

Why? Because our "Drupal users" are (paid) members, they have to choose a membership type, they get informed about the corresponding fee (and how to pay offline) and have to provide additional member information (postal address, day of birth,...). All this is handled by a civiMember page, which creates also a Drupal user (user name and password), blocked at the beginning (changed to active as soon as payment is received).
We probably have to keep the Drupal user login block, for registered users (paid members) to login.

The easiest solution I think here is just redirect it at the Apache (.htaccess) level with a rewrite rule:

RewriteRule ^user/register$ /civicrm/contribute/transact&reset=1&id=1 [NC,L,R=301]


Taxonomy Terms node count of different content type Hi I have a issue for which I searched everywhere but not getting any solution,

I have two content types Store and Deals with the following fields
Store is having the fields
1.Store-title
2.Logo
3.Categories--> Added as a taxonomy term field.
4.Outlets

When I am adding a node of type store I am selecting the corresponding category terms with it and saving.

Other content type Deal having the fields
1.Title
2.Store-title---> This field is of content type Store and is added here as a node reference.
3.Outlets

When I am adding a node of type deal I am selecting a store here( In deals content type, store-title is added as a node-reference), and selecting its outlets.

Issue:
I need a counter on the category terms, the counter should be based on  number of deals added to that particular store node on respective categories.

Hope you understand the issue,
I have seen the issue of same type where node counter is displayed but they show the count of nodes of the same content type where that taxonomy term is added like here http://www.brightwebsitedesign.com/how-to-use-views-aggregator-to-create-taxonomy-term-count-block,
But I have a bit different,  taxonomy is added to stores, but I need the count of deals( another content type) on the taxonomy term.
If you still need more clarification please let me know.

This is very urgent
Any help would be much appreciated!

You can achieve this with help of an additional relation. If you are following view creation from the post mentioned by you

After selecting ' Taxonomy term: Content with term ' add another relation and choose the node referenced field - reverse and choose Require this relationship. (in your case 2.Store-title---> This field is of content type Store and is added here as a node reference)

Now you will get your count of deals


Multilingual article should display 404 when a translation is not available I setup Drupal 8 with 2 languages English & Arabic.
Now when an article (English for eg.) does not have a translation (in Arabic) and the user switches the language from the menu. The page loads in Arabic and the article loads in English.
I need to return a 404 or something different.

Any advise would be helpful.

It can not be done using core or contrib
To present 404 page not found (bad UX)
You could do something like this in your own module MODULENAME.module file
function MODULENAME_entity_view(array &$build,
  \Drupal\Core\Entity\EntityInterface $entity,
  \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $ent_lang = $entity->langcode->value;
    if($view_mode == "full" && $lang != $ent_lang){
      throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
    }
}

but once you go to the not found page the language switcher will not be able to take you back to the translated page though
To Hide untranslated languages in language switcher
There is a core issue about this and solutions are worked out but until it is solved you could create your own module
/**
 * @file
 * Hide language switcher links for untranslated languages on an entity.
 */
use Drupal\Core\Entity\ContentEntityInterface;

/**
 * Implements hook_language_switch_links_alter().
 */
function MODULENAME_language_switch_links_alter(array &$links, $type, $path) {
  if ($entity = MODULENAME_get_page_entity()) {
    $new_links = array();
    foreach ($links as $lang_code => $link) {
      try {
        if ($entity->getTranslation($lang_code)->access('view')) {
          $new_links[$lang_code] = $link;
        }
      }
      catch (\InvalidArgumentException $e) {
        // This language is untranslated so do not add it to the links.
      }

    }
    $links = $new_links;

    // If we're left with less than 2 links, then there's nothing to switch.
    // Hide the language switcher.
    if (count($links) < 2) {
      $links = array();
    }
  }
}

/**
 * Retrieve the current page entity.
 *
 * @return Drupal\Core\Entity\ContentEntityInterface
 *   The retrieved entity, or FALSE if none found.
 */
function MODULENAME_get_page_entity() {
  $params = \Drupal::routeMatch()->getParameters()->all();
  $entity = reset($params);
  if ($entity instanceof ContentEntityInterface) {
    return $entity;
  }
  return FALSE;
}

Above solution is taken from this post
To Hide untranslated menu items
You can use menu_multilingual which gives option when you create/edit a menu block to hide untraslated items.


Show workflow transition bar in all states I've created a custom workflow using the workflow module with the transitions listed below and I've noticed that when going to the view page of a node the workflow 'bar' that lets you transition a node between states only appears when it's set for review.

From what I can gather this is because only when it's in the review state is it considered moderated content which is also why it appears on the "Moderated Content" view. What I'd like is to have that appear no matter the moderation state it is in. How could I accomplish this?

States

Draft
Review
Published

Transitions

Draft || Review || Published > Draft
Review > Published
Draft > Review

I worked out what the issue is, you can only see that bar when you're looking at the Latest Version of a node (using the "Latest Version" tab) not when viewing the latest published version of the node (using the "View" tab).

So this is now resolved by checking if they have access to the "Latest Version" tab of a node (basically checking that exists) and sending them to that if it does, otherwise sending them to the "View" tab. The code below does it and is called from hook_node_insert & hook_node_update in my custom module .module file.

function send_user_to_view_page_after_save(NodeInterface $node) {
  $nid = (string) $node->id();

  if (!is_null($nid)) {
    $alias = Drupal::service('path.alias_manager')->getAliasByPath("/node/{$nid}");
    $url_service = new Url("entity.node.latest_version", ["node" => $nid], []);

    if ($url_service->access() === TRUE) {
      $response = new RedirectResponse("/node/{$nid}/latest");
      $response->send();
    }

    $response = new RedirectResponse($alias);
    $response->send();
  }
}


Checking for an Acquia Environment variable Trying to check for an Acquia cloud environment variable in my twig template, but its not working in Dev or in Production.

Similar question is answered here, but I still can't get the twig syntax right: Is there a way to get (and use) an environment variable in my Twig template?

This is a snippet from the page.html.twig file.

{% if AH_SITE_ENVIRONMENT == 'prod' %}
  // Javascript Analytics Code
{% else %}
  <!-- env is {{ AH_SITE_ENVIRONMENT }} -->
{% endif %}

The other question mentioned having passed that variable from a preprocess function to the template first. I guess that can be done using PHP's getenv then. Let me just try that out.

Yep, that works.

/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {
  $variables['my_environment'] = getenv('AH_SITE_ENVIRONMENT');
}

Then continue in page.tpl.php.

{% if my_environment == "prod" %}
  // Javascript Analytics Code
{% else %}
  <!-- env is {{ my_environment }} -->
{% endif %}


How to access private page (views page) with authentification in the URL? All the pages of my site are private (by role). I have nodes and views pages.
I want to access to a views page with an external link. But, If the visitor isn't logged, this visitor can't access to the page.

Is there a solution to specify a token or the login / pass in the URL to automaticaly access to the page?

Try reading about these projects:

Auto Login URL
Auto Login URL Tokens
Token authentication
Login one time
One-time login
urllogin

They're not all usable but you can get inspired by their different features and how they implement them so you can solve it for your own problem.


Some Database Tables Have dr_ prefix Hello ive been messing about with drupa for 8 years now and im still YET to get a website to go live :( After about 10 reinstalls of my new website idea i was just about to go live and then i had a wee look in the database and ive noticed a load of tables prefixed dr_

I know some softulicious installs add this db prefix.

My site works well enough but the tables prefixed as per attached are  worry to me. Should they be a worry to me?

Can i fix it easily enough?

Thanks

ps all my other db tables are unprefixed which is the desired effect. All help appreciated as im close to startingmy site again from scratch :(

My electricity is about to get cut off for 12hrs so cant reply till then.

This can sometimes happen if you are using softaculous installer (or similar one-click installer provided by your web host). Perhaps you installed several instances of Drupal using the same database name, and just left the 'dr_' prefix in place for one by accident.

If I were you, I wouldn't worry too much about it. Having the additional tables there won't cause any problems with your Drupal installation (the one using the non-prefixed tables), and the 'dr_' prefixed tables won't increase in size as time goes on.

You should be able to safely leave them as they are, or, if you want to, remove them using phpMyAdmin to permanently delete (drop) the tables prefixed with 'dr_'.


remove tabindex -1 from views accordion the view accordion is automatically assinging a tabindex -1 to header field.  like this :

<a href="#how_to_become_a_grantee-block-0" tabindex="-1">

how can I remove that tabindex -1 ? thank you

it sounds like you want to modify the source contributed module :(.

You just write some custom CSS in your theme to target the item. In your theme.info file:

scripts[]=my_theme_overrides.js

Then in your javascript file you write the following, as an example (untested, should work, you may need to tweak it.):

/* in my_theme_overrides.js */
(function ($) {
  $("#how_to_become_a_grantee-block-0").removeAttr("tabindex");
})(jQuery);


Receiving Error message on every attempt to add or remove content. Is this normal? New to drupal & collaborating on a project. Error message reads "Error ; The website encountered an unexpected error. Please try again later." I've been getting that error message for 4 days in a row. Wondering if there is actually a site issue (with Drupal) or if there's something I can do to fix this.

Just add this code to your index.php file just after the php opening tag.

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Then try to reproduce the scenario. You will see the exact error on web page and if you clear about error then definitely you can solve it.


Ajax slideshow for D7? I am looking for some kind of Ajax-based slideshow/banner module for D7 for a changeable front-page photo banner. Unfortunately neither Views Slideshow Ajax nor Ajax Slideshow have been ported to D7 yet. I have several megabytes of photo content and would like to load each image on demand, not load them all at once (which is, as I understand, how most of the slideshow modules work). Right now I am just using a view that returns a randomly-chosen image, but I'd rather have it cyclable by the user with arrows or by a timer.

Are there any existing D7 modules that do something like this? There are so many slideshow, banner, and gallery modules: I may have missed the one I need.

The Views Slideshow module relies on the Cycle library, if I'm correct. It supports AJAX / progressive loading in it's current version as seen here:

http://malsup.com/jquery/cycle2/demo/progressive.php

In my experience, a lot of Drupal modules make the integration of library options unneccessarily complex:
So you could just generate the necessary code via views instead and load the lib yourself via template. Most current slideshow scripts support AJAX loading, so you can choose one that suits you.


Can't use super user account I have a Drupal 6 installation, and wanted to make some changes for the client. However, this fails, because as soon as I log in with the super user account it says:

  Access Denied: You don't have sufficient permissions to access this page

So I can't even log in using the super user account (uid 1). The password is already reset several times. The cache tables and session tables are emptied. What can I do?

I hada look into my watchdog table. It said the sessions table was corrupted and needed to be repaired. So I did it, and after that I could login with the super user again. Thanks everybody for helping out, but it was something different this time.


How to create a sequence of nodes to work as a "tour" through a site? I can think of different ways, like creating a View with all nodes available and sort them with DraggableViews so I have a tree, and then adding a Next/Prev buttons if the user wants to see the site not as individual nodes, but as a Tour, being taken from the first node to the last one in a specific order.

Anyone has any better, less of a hassle, ideas?

Custom Pagers

  Custom Pagers allows administrators to define context-sensitive
  previous/next pagers for any node type. The list of nodes to be cycled
  through is generated by a user-selectable view, and each pager can be
  displayed above or below the node body or in a sidebar block. This
  makes it possible to duplicate the paging functions of forum.module
  and book.module, as well as more complex stuff like comic strip
  navigation. Requires token.module and views.module.

and Nodequeue

  The Nodequeue module allows users to collect nodes in an arbitrarily
  ordered list.


Highlight View parent menu item on node page and rebuild breadcrumb If you are new to Drupal, as I am, you surely asked yourself once about "How can I highlight parent Views menu item even if I am on a child node? And how can I keep a correct breadcrumb if I use one?"... That's why I wanted to share a little clue in here.

My situation:

I have a content-type named "Testimonial". I created a View for my testimonial's nodes, with a menu item "Témoignages" in a secondary menu on the left of my page (called "Ressources").

First problem: the menu

/!\ This menu displays only on the pages whose menu item is present in the menu. For example, "Marchés publics en Wallonie", "Aides publiques en Wallonie", "Témoignages" (= Testimonials), ...

When I am the the View page, with the list of my testimonial's nodes, the menu item is highlighted automatically by Drupal. Nice.

But when I click on a node and access the full view page, the "Ressources" menu disappears. This behaviour is normal for all other menu item's children pages. But I want to make an exception for the testimonials.

Second problem: the breadcrumb

Breadcrumb on Views page:

Breadcrumb on testimonials node page:

My final question:

How can I keep the menu block in testimonials node pages (only) and make the menu item "Témoignages" highlighted? And how can I keep a correct breadcrumb in the same time?

To display the "Ressources" menu in a testimonial node page, Drupal should believe that we are actually on the "Témoignages" Views page. Plus, it will highlight automatically the good menu item.

But, we also need a correct breadcrumb. That's why we have to save in a variable the "true nature of the page" (a node) before letting know to Drupal that we are on a view.

That's that we do here:

function pwe_testimonial_node_view($node, $view_mode, $langcode) {
  // When we are on a Testimonial node page
  if($node->type == "testimonial" && $view_mode == "full") {
    // We save the true nature of the page
    $_SESSION['pwe_testimonial_active_trail'] = serialize(menu_get_active_trail());
    $_GET['pwe_node_id'] = $node->nid;
    // And set the active menu item as "Témoignages"
    menu_set_active_item("testimonial");
  } else {
    // If we are not on a Testimonial node page,
    // we unset the custom variable.
    if(isset($_SESSION['pwe_testimonial_active_trail'])) {
      unset($_SESSION['pwe_testimonial_active_trail']);
    }
  }
}

To rebuild the true breadcrumb, we use the variable saved in previous function.

function pwe_testimonial_menu_breadcrumb_alter(&$active_trail, $item) {
  if($item && $item['path'] == "testimonial") {
    if($_GET['pwe_node_id']) {
      if(isset($_SESSION['pwe_testimonial_active_trail'])) {
        unset($_SESSION['pwe_testimonial_active_trail']);
      }
    }
    if(isset($_SESSION['pwe_testimonial_active_trail'])) {
      $original_active_trail = unserialize($_SESSION['pwe_testimonial_active_trail']);
      if(is_array($original_active_trail)) {
        $total = count($active_trail);
        $active_trail[$total] = $item;
      }
    }
  }
}

That's all. I hope this little Q&A sharing knowledge will help someone in the future.


how to implement a data receiver service in Drupal I have a Drupal site which will host a flash application. The application will be inserted in a node body (or as an attachment, not sure yet). I would like this application to send some data to Drupal (e.g. a game progress and score) using Javascript.

What I achieved so far is the ability to have the game score displayed in a Javascript alert  window in Json format. Next step would be to send it to Drupal and I want to save it to a table. I don't know how to do the "Send it to Drupal" part. What is the right way to do it, so it's hacker-proof etc?

If you do it the JS part, Drupal part will be quite easy.

Create module with form that handle data transfer to Drupal and submit this form via Ajax https://drupal.org/node/752056

It can be helpful too: Match JSON POST data with custom node fields


Is entittyfieldquery result can be loaded into select list? Trying to populate select list in VBO action form (basically could be anyform) and using enityfieldquery to get list. By this methods $result object contains node arrays.

Can this array can be loaded into select list directly? or we need to apply node_load_multiple on $results array.

Reason why I am asking is, there are many field and for the select list, only title and nid is enough right?

Are there any workaround for this?

Can this array can be loaded into select list directly? or we need to apply node_load_multiple on $results array.

A FAPI select list expects an Array with id and title. An entityfieldquery returns only a list of IDs unless you get creative. Typically you perform extra work to load fields you want to show as text in your select field. You can do this via SQL, node_load a view resultset ... whatever means you're comfortable with.

EDIT

Well I didnt say you have to use node load. There are various extensions to EFQ that let you use community created EFQ classes:

The most recent is https://www.drupal.org/sandbox/mikeytown2/2209909
A slightly older less pretty module is https://www.drupal.org/project/efq_extra_field


"Unable to send e-mail" Error in drupal 7 Just now I migrated my website to server machine. I noticed that website is not able to send any email. It is showing "Unable to send e-mail" error.

Below is the screenshot of the error-

I can see some directory permissions error in status report at admin/reports/status. Are these related to each other?

It's very likely that your new server does not allow mail to be sent from the web service.   This could be because it blocks the SMTP port, or because it doesn't allow PHP to use mail().  You should be able to contact their tech support to ask.  If not,  you can try uploading your own PHP script that uses the mail() function and see what errors it gives you.

IMO, this is a good thing... web servers shouldn't be sending emails for a variety of reasons.

I would recommend using something like this:  https://drupal.org/project/smtp

It will let you send email through a real email account, of course you'll have to make sure there's not a block on the port it uses.


How to get bundle label from entity How do I get the human-readable label of a bundle from a loaded entity.

Lets say I want to get the label of a node of bundle my_article which is "My awesome article"

// Load a node
$node = Drupal::entityManager()->getStorage('node')->load(4);

print $node->bundle(); // prints the machine-readable name. e.g. 'my_article'.

print $node->getEntityType()->getBundleLabel(); // prints 'content type'.

I am only able to get the machine-readable name of the bundle or the Label of entity ("content type", "taxonomy term", etc), but how do I get the Label of the bundle?

P.S. I would prefer it to not use deprecated classes/functions

I can't see anything direct, loading the node type entity itself is an option though:

$bundle_label = \Drupal::entityTypeManager()
  ->getStorage('node_type')
  ->load($node->bundle())
  ->label();

Or as Berdir pointed out in the comments, there's a quicker way through the entity reference field:

$bundle_label = $node->type->entity->label();


Node reference field auto complete in views I have content type master program and slave program.

Slave program have node reference field with master program

I created a view for filter and show the slave program list

For node reference field it is showing as dropdown

but I want to display as autocomplete textfield.

I searched view_auto_complete and node_reference_autocomplete modules

I dont know how to implement these

Can any one help me ?

Views Autocomplete Filter done the tricks.

Add autocomplete functionality to the views filter text fields.


How to create a collapsible Webform form? I'd like to make a webform collapsed by default, and have a Sentence/paragraph at top of the page with a checkbox next to it. Upon ticking the checkbox I would like the webform to be displayed.

Similar to Form 2 - Adding Fieldsets on this site: http://dev.sencha.com/deploy/ext-4.0.0/examples/form/dynamic.html

How would I go about doing this?

Okay, the easy way would be to go through FORMS API http://drupal.org/node/37775

You may also look into MultiStep module once you are done with the FORM API overview.

Below are some links that you can follow:-

http://www.youtube.com/watch?v=EgGhUN2zKw4
http://randyfay.com/states
Search youtube/drupalize.me/buildamodule.com for more Form API tutorials.
http://tedbow.com/content/drupal/webform-conditional-demo-form

Please go through Form Api first.


How to update Blob data in users table? I am trying to update data filed in users table.

Please suggest a way how to update this field data with help of query or need to follow some other approach ?

$old_user_id = 123;
$new_user_id = 456;

$account_old = user_load($old_user_id);
$account_new = user_load($new_user_id);

if ($account_old && $account_new && !empty($account_old->data['uc_stripe_customer_id'])) {
  user_save($account_new, array('data' => array('uc_stripe_customer_id' => $account_old->data['uc_stripe_customer_id'])));
}

Thanks!

It's a serialised PHP array.

You would, in my humble opinion, be nuts to try to parse this with SQL.

Use PHP to unserialize, make your changes, serialize it again, and write the result to the database.


Background images using Breakpoints and Picture I want to serve my background images by breakpoints.  I can't seem to find an out of the box way to do this using the Breakpoints and Picture modules, which I'm using for some node images.

Has anyone implemented this using Picture/Breakpoints?

My solution was to use Group Background Image with the patch that you can get here. This allows background images, through the integration of the Picture and Breakpoints modules. The configuration is super easy, and you can change existing div field groups into background images in a split second.


How to disable profile2 types? I have some types provided by the Profile 2 module that I want to disable, but not delete.

How can I accomplish this?

As far as I know the only way would be to disable permissions for viewing or editing the profiles for specific user roles. Those roles won't be able to see them.

There are a few "things" that can be disabled (without deleting them) in Drupal - Views and Panels are some of them.


Editing Panels in Admin Theme I would like to edit my Panels (Panel Layout and Panel Content) in the administration theme, however when I click on the tab to go to panel layout (node/%node/panel_layout), it always opens in my default theme.

Is there a way to have it use my admin theme for panels?

You could write a small custom module and use hook_admin_paths():

function MYMODULE_admin_paths() {
  return array(
    'node/*/panel_layout' => TRUE
  );
}

This will instruct Drupal to treat paths that match the pattern as admin pages, including rendering them with the admin theme.


If linking entities with a multi-value entity reference field, what about properties of the association? In this thread I need a link from base table to join table
it was suggested that it is better in Drupal to join two entities with a multi-value entity reference field than to use a relational style join table to join them (assuming many to many relationship).  But, what about the case where there is a property of the association.  E.g., stories win awards, but each award is or may be granted every year.  So, in a relational design, one would use a join table to link a particular story with the award it had won and put the year into the association.  What is the Drupal Way to do this with a multi-value entity reference field?

OK, here is a simplified diagram of the relationship between Story and Award showing the property on the association.

First, there is no Drupal way. Drupal is flexible and the same result can be achieved in many ways. If you feel comfortable using join tables, go for it. In the other thread OP wanted to use a relation between entities in View, what entity references offer out of the box, where a join table would not. Therefor that was suggested.

For a situation where a relation needs to have properties on its own, you might want to look into the Relation module. It provides a relation between two entities, but the relation can have properties (fields) on its own (such as as year).

I just don't know how stable the module is for Drupal 8, but it works great in Drupal 7.

Update after the question of Asy:

The entity principle in Drupal 8 is similar to 7, so it would not change the answer much, except that the relation module for Drupal 8 is not yet finished. The problem with this specific question is that the answer is spread over 3 different posts. The combined essense is: nodes are pretty 'resource heavy' entities, as they invoke access checks, path aliasing, etc. Using them just to attach a property to a 'relation' works, but consumes more resources than a system that was designed to do just this (the Relation module, which for instance avoids the node access check and path aliasing on the in-between node). Especially when combining 3 nodes with 2 fields, this becomes SQL heavy too. Nothing SQL can't handle, just don't do it too often. So in the end is all depends on the application. If this is not a page that gets much views, you might not even notice it.

A better alternative (but I did not test nor benchmark this) might be to create a custom entity using the ECK (Entity Construction Kit). These entities are presumably lighter than nodes. Combined with Drupal 8's default entity referencing and something like Inline Entity Form to fill the field on the relation could make quite a nice interface.

In the end however you still need to join like this:

Node > entity reference field > ECK entity > entity reference field > node
  v                                  v                                  v
fields                            fields                             fields

Where the relation module (if finished) would offer something that probably looks more like this:

Node > relation > node
  v       v         v
fields  fields    fields


How to display menu block but deny adding a new instance? I have a menu which has a block provided by the system automatically.
This menu has links that come from a module which defines the menu(config).
This menu block can be seen(ie. the block is visible) but it shouldn't be possible to attach another instance of this menu nor put links into it via UI. I do not want the admin so see this menu block in the list of available blocks on the block library page.

So far I have been able to tweak things so that some specific menus are not available for user to put links into or even see them in the menu listing(I have custom list builder for this + some form alterations in place). But when it comes to blocks the issue is that on some places Drupal checks plugin definitions(which are cached so I cannot distinguish if the user is on the "manage blocks" page or somewhere else or if the user has specific permissions and such) and in other places it uses the block entities.

So my question is how can I hide a block from the block library but keep the block displayed when attached to a region? If I remove the plugin definition the bloc kwon' be displayed since the plugin will be non existing. This works in other cases that I have but not int this one.

I think this relates to https://www.drupal.org/node/1975064 but I need to fix this ASAP.

So at the end my solution in regard to blocks was to create route access check for the block.admin_add route to prevent attaching unwanted blocks, override the controller for the block.admin_library route by extending the original one and removing unwanted blocks from the list, implementing hook_block_access to prevent certain operations on certain blocks and hook_block_filter to remove some blocks completely.


Can Drush make include username, password and settings in one file? I hear some talk about Drush make and features.

But not sure how to use them in combination.

Is there a way to have a Drupal site install with ALL settings, including install procedure (enter database name, site name, username ect...)

Include what modules to enable, set user permissions.

I know that Drush can do some of that.

But is it possible to have it ALL done within the drush.make file, can I add standard drush commands to that?

The responsibilities of Drush make involve downloading the files that make up your site.  Site initialization can be done in an installation profile, which is selected at installation time, or perhaps in a script that you run to set up your site.

For Drupal 8, configuration can be imported via the drush config-import command.  In Drupal 7, there are many options for managing configuration.  A lot of people (perhaps the majority) use features, but I prefer ctools bonus export.  Here is an example script I use to set up a test site for behat tests.

If you are just starting out, you might want to consider using Composer instead of Drush Make.


How to use % arguments in Easy Breadcrumbs "Paths to replace with custom breadcrumbs" I am trying to give a more logical breadcrumb flow to the Drupal Commerce 2 checkout path, as Commerce doesn't support breadcrumbs in the checkout process.

When not displaying the current page in Easy Breadcrumb, Drupal Commerce 2 by default it gives you a trail like this Home > Checkout after progressing from the /Cart page to the /Checkout page. This redundantly brings you back to the checkout page that you are already on.

The logical flow here when excluding your current page from the crumb, should be Home > Cart when you have proceeded to the /Checkout page from the /Cart page.

This Breadcrumb can be easily set in easy breadcrumbs Paths to replace with custom breadcrumbs as seen in the picture:

But the problem is that the order number is placed in the URL, so you would need to replace the actual order number (5 in this example) with % argument something like /checkout/%/order_information :: Cart|/cart

Is it possible to somehow accept % arguments in the URL's in "Paths to replace custom breadcrumbs"?

There is a patch here in progress to allow wild cards in breadcrumbs:

https://www.drupal.org/project/easy_breadcrumb/issues/3051106


Select entity to display using drop down list My problem is that I want to add a drop down list to a node that selects an entity from that node based on its name, and display it.
I am wondering if there is a module that does that; if there isn't, what the best approach is.

So far, I can only think of creating a custom node template to display the entities using JavaScript.

Unless I am mistaken, the Entity reference module won't work in my case; if it does, please clarify.

I have 4 tables in a single node; each table represents a week in a month. I want just a simple drop down list to select which week to display, and display that week's table.

Checkout the Entity reference module.

  Provides a field type that can reference arbitrary entities.


How do I place a multigroup in another multigroup? Is there any workaround to be able to place a multigroup inside another multigroup using CCK?

This is what CCK tells me when I try to do it:

  You cannot place any kind of group inside a multigroup.

In Drupal 7, CCK Multigroup is succeeded by Field Collection, which can be used to nest collections within collections.

In Drupal 6 however, you already have your answer. You cannot place any kind of group inside a multigroup, due to the way the information is stored in the database.


Place text below exposed filter I have a Drupal view where I would like to enter some text in between 'Exposed Filter' and 'Content' sections. What is the safest of doing this? Attached image shows exact location I need text inserted.

Thanks

You need to create a custom template for your view.

Go to /sites/all/themes/YourTheme/templates folder

create a file called views-view--[view-name]--[machine-name].tpl.php

  For example if you view name is "Hello World" and machine name is "block_1"

  It would be: views-view--hello-world--block-1.tpl.php

Inside your custom template file put:

<?php

/**
 * @file
 * Main view template.
 *
 * Variables available:
 * - $classes_array: An array of classes determined in
 *   template_preprocess_views_view(). Default classes are:
 *     .view
 *     .view-[css_name]
 *     .view-id-[view_name]
 *     .view-display-id-[display_name]
 *     .view-dom-id-[dom_id]
 * - $classes: A string version of $classes_array for use in the class attribute
 * - $css_name: A css-safe version of the view name.
 * - $css_class: The user-specified classes names, if any
 * - $header: The view header
 * - $footer: The view footer
 * - $rows: The results of the view query, if any
 * - $empty: The empty text to display if the view is empty
 * - $pager: The pager next/prev links to display, if any
 * - $exposed: Exposed widget form/info to display
 * - $feed_icon: Feed icon to display, if any
 * - $more: A link to view more, if any
 *
 * @ingroup views_templates
 */
?>
<div class="<?php print $classes; ?>">
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <?php print $title; ?>
  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php if ($header): ?>

      <?php print $header; ?>

  <?php endif; ?>

  <?php if ($exposed): ?>

      <?php print $exposed; ?>

  <?php endif; ?>

  HERE <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

  <?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

  <?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

  <?php if ($attachment_after): ?>

      <?php print $attachment_after; ?>

  <?php endif; ?>

  <?php if ($more): ?>
    <?php print $more; ?>
  <?php endif; ?>

  <?php if ($footer): ?>

      <?php print $footer; ?>

  <?php endif; ?>

  <?php if ($feed_icon): ?>

      <?php print $feed_icon; ?>

  <?php endif; ?>

<?php /* class view */ ?>

  Note: The above code is an exact copy of views-view.tpl.php located in the /sites/all/modules/views/theme folder. I just added
  the HERE <<<<<<<<<<<<<<< part after the exposed filter php.

Don't forget to clear/flush the cache to see changes.


Why theme scripts.js is not working, how to attach it I started learning Drupal 8 and encountered problem when I wanted to use scripts.js file globally. I am just testing out code to change background color and write something to console, but script file is not working. source/scripts.js is minified to build/scripts.js which is included in libraries.yml and global is included in info.yml. What am I doing wrong? Maybe I don't understand new Drupal 8 Javascript API?

libraries.yml

  global:
  version: VERSION
  css:
    base:
      css/base/base.css: {}
    layout:
      css/layout/layout.css: {}
    component:
      css/components/components.css: {}
    theme:
      css/theme/theme.css: {}
      css/theme/print.css: { media: print }
  js:
    js/modernizr.js: {}
    js/build/scripts.js: {}
  dependencies:
    - core/drupal
    - core/jquery

info.yml

libraries:
  - core/normalize
  - offer42/global

source/scripts.js

(function (Drupal, $, window) {

  // To understand behaviors, see https://www.drupal.org/node/2269515
  Drupal.behaviors.offer42 = {
    attach: function (context, settings) {

      $(context).find('.block-offer42-branding')(function () {
          $(this).css('background-color', '#000');
          console.log("workinh");
      });

      // Execute code once the DOM is ready. $(document).ready() not required within Drupal.behaviors.

      $(window).load(function () {
        // Execute code once the window is fully loaded
      });

      $(window).resize(function () {
        // Execute code when the window is resized.
      });

      $(window).scroll(function () {
        // Execute code when the window scrolls.
      });

    }
  };

} (Drupal, jQuery, this));

What you're trying to do is not valid jQuery code. You missed the .each part.

So use $(context).find('.block-offer42-branding').each(function () {


Resource interpreted as Image but transferred with MIME type text/html I've been embedding an image with my page using item type form control in Drupal 7 Forms API.Below are my codes:

function myid_user_page_form(){
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );

    $form['id']['myid'] = array(
        '#type' => 'item',
        '#markup' =>
            '

'
    );
    return $form;
}

My image doesnt show up and is broken eventhough the path is correct and file permissions are set properly.

What Shall I Do? Below is the error:

Resource interpreted as Image but transferred with MIME type text/html: "http://localhost/drupal-7.34/user/7/images/id-background.jpg".

Below is a screen capture of my page.

Image path is incorrect. It will pick the path of image as http://current_path/images/id-background.jpg.

global $base_url;
$path = $base_url . drupal_get_path('module', 'mymodule') . '/images/id-background.jpg'; // considering the image is placed in your custom module's image directory
$form['id']['myid'] = array(
  '#type' => 'item',
  '#markup' => '

'
);


using form_state->set() inside ajax callback but cannot get the value back outside the callback I want to add some arbitrary variable to store it in the form_state and use it again so in one of my ajax callback functions I set a property named var:

public function MyFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = array('1'=>'one','2'=>'two');
$form_state->set('var', $terms);
....
}

it works and the storage array of the form_state has var element

unfortunately when trying to get the var back inside another callback function it returns null.
actually with debugging the storage array of the form_state is empty

public function MyOtherFunctionCallback(array &$form, FormStateInterface &$form_state) {
....
$terms = $form_state->get('var');
....
}

As 4k4 mentioned, you cannot change the form state inside an ajax callback function.

You can, however, change it in the ajax button submit function.

$form['ajax_button']['#submit'][] = [static::class, 'ajaxButtonSubmit'];

public static function ajaxButtonSubmit($form, $form_state) {
  //...
}


Does hook_install() get called before or after configuration yml files are loaded? In Drupal 8, during module install, is hook_install() called before or after loading the .yml files in config/install?

I've across a module that's using both (which seems like a bad idea on its own) and I'm trying to run down the cause of an inconsistency in the configuration right after the module is installed.

When Drupal install a module, first it installs the default configuration of the module, then it invokes its hook_install(). This is evident from ModuleInstaller::install(), which contains the following code.

  // Install default configuration of the module.
  $config_installer = \Drupal::service('config.installer');
  if ($sync_status) {
    $config_installer
    ->setSyncing(TRUE)
      ->setSourceStorage($source_storage);
  }
  \Drupal::service('config.installer')->installDefaultConfig('module', $module);

  // If the module has no current updates, but has some that were
  // previously removed, set the version to the value of
  // hook_update_last_removed().
  if ($last_removed = $this->moduleHandler->invoke($module, 'update_last_removed')) {
    $version = max($version, $last_removed);
  }
  drupal_set_installed_schema_version($module, $version);

  // Ensure that all post_update functions are registered already.
  /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
  $post_update_registry = \Drupal::service('update.post_update_registry');
  $post_update_registry->registerInvokedUpdates($post_update_registry->getModuleUpdateFunctions($module));

  // Record the fact that it was installed.
  $modules_installed[] = $module;

  // Drupal's stream wrappers needs to be re-registered in case a
  // module-provided stream wrapper is used later in the same request. In
  // particular, this happens when installing Drupal via Drush, as the
  // 'translations' stream wrapper is provided by Interface Translation
  // module and is later used to import translations.
  \Drupal::service('stream_wrapper_manager')->register();

  // Update the theme registry to include it.
  drupal_theme_rebuild();

  // Modules can alter theme info, so refresh theme data.
  // @todo ThemeHandler cannot be injected into ModuleHandler, since that
  //   causes a circular service dependency.
  // @see https://www.drupal.org/node/2208429
  \Drupal::service('theme_handler')->refreshInfo();

  // In order to make uninstalling transactional if anything uses routes.
  \Drupal::getContainer()->set('router.route_provider.old', \Drupal::service('router.route_provider'));
  \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.lazy_builder'));

  // Allow the module to perform install tasks.
  $this->moduleHandler->invoke($module, 'install');

The first lines I quoted are for installing the default configuration, while the last one is for invoking hook_install().


Redirect to entity ID after entity create form submit with AJAX I have an AJAX entity create form and I want to redirect to that entity ID after I submit the form and create the entity, I know I can't use goto() because it's AJAX. I have the hook form alter for that entity already for some other customization of the form.

You should not use drupal_goto() for form redirects. You should set the redirect in the form state.

function mymodule_myform_submit($form, &$form_state) {
  // other code
  $form_state['redirect'] = 'path';
}

Ctools provides a way to do a redirect in an AJAX callback, a function called ctools_ajax_command_redirect.

I found an example of someone using this function in a form callback that is AJAX:

function mymodule_custom_ajax_form_submit($form, &$form_state) {
  //Close lightbox and redirect to the current page
  $path = $_SESSION['current_path'];
  ctools_include('ajax');
  ctools_add_js('ajax-responder');
  $commands[] = ctools_ajax_command_redirect($path);
  print ajax_render($commands);
  exit;
}

So, in your case, you would need to know the entity id in the submit handler, and you can get the uri with entity_uri, which you can pass as the $path and that should work. Just load the entity object, and pass it to entity_uri. It should return 'myentity/(id)' ex 'node/123', which you can redirect to.


Followed the How can I link an image of a jCarousel to a certain link? page but need further help I followed the instructions on linking hyperlinks in jcarousel found here:
How can I link an image of a jCarousel to a certain link?

The problem is that I don't have the Formatter drop down field in my view.

Attached is a screenshot of what I see.

These are the choice I have when adding a link to the view. It appears to be the same link as what is in the original instruction:

The field 'link' you have added is configured as a simple Text field from Content type field manager.

You need to choose Field Type as 'Link' while creating it. Then only you can find those options in views.

My suggestion would be to create a new field 'link' and add it to views.

Let me know if you still find issues. :)


Exposing fields for a search in Views I can add a filter for node:title and node:body, but then there's two separate search fields for the content. I also have some other exposed filters (checkboxes), but I need rather than two search fields to have just one normal search field. Any ideas on how to do this?

Here's the same issue on d.org.
In short: it's better to enable Search: search terms filter (Drupal core search module needs to be enabled too).


Right side overlay panel Solution quickie,

I want to create a right-hand side sliding overlay panel for my drupal site.  I have been googling and testing solutions for hours. The exact effect that I want can be found here.  The jQuery Mobile overlay panel.

Of course, this script is not working with drupal and bootstrap 3 theme.

Question(s):  Does anyone know a way to make this script work with drupal 7 and bootstrap 3?

The closest substitute that I can find is the Mobile Menu Module (MMenu) module, but it appears to be for navigation purposes only.  I need to add a FAQ with animated expanding divs.  The documentation is unclear if this possible with MMenu.  Can anyone tell me if it is possible?

If I am barking up the wrong tree with jQuery Panel and MMenu is there a better solution? Simple, right hand side overlay panel.

Much appreciate, any suggestions.

I believe in owning the silliness, when you're being silly.  I answered my own question in the process of posting the question.

Using MMenu module, I simply took my animated divs and put them in a block and loaded the block as content for mmenu.  The js scripts work and the content looks great, only one last hurdle.  But I will do that is an actual question if I can't find a solution.