How can I keep logs of all outgoing emails? I am using SMTP Authentication Support module to send emails with drupal 8.When I see watcdog mail-log from admin it shows only emails sent for registration or password reset, that is also with single line like registration email send to... I did not found any logs related to email sent me for orders status. I have installed devel_mail_logger to keep logs but than I did not received those email which are listed in devel_mail_logger log list, any suggestion how can I keep all email logs with content & errors(if any).

Try to use https://www.drupal.org/project/mail_safety I using it with swiftmailer module (configured with SMTP) and it works. You can configure it for store all outgoing emails.


How do I put this custom CSS and JavaScript into a certain block? I'm having a hard time getting this:
http://dev.chrisruno.com/sahshe/quiz/
To go into a block in this node:
http://sahshe.chrisruno.com/?q=node/22#

I've successfully included the two Javascript files I need, but I can't figure out how to apply the css to ONLY what is inside the block.  I've only gotten as far as including the CSS file in my theme's .info file, but that makes the whole site look crazy.

In very broad strokes, in your module's block() or block_view() hook, you would do something like this:

 drupal_add_js(....);   // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7
 drupal_add_css(....);  // see http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_css/7

and to have the CSS apply only to that block, look at what Drupal's block theme functions wrap the block with, and then using one of those ids or classes, cascade your CSS accordingly, eg, instead of:

.content {
  ....
}

use:

#BLOCK-ID .content {
   ....
}

or:

.BLOCK-CLASS .content {
   ....
}

Of course, you would return as the block's content either the HTML or a renderable array of it.


Uninstalling an entity "BaseFieldDefinition" on module uninstall I'm attempting to create my first module, which doesn't do much. I'm looking to:

Add a couple of extra fields to a menu item.
Save them in to the menu_link_content_data table.
Access them within theme templates.
Remove the items from the menu_link_content_data table when the module is uninstalled.

I've managed (after A LOT of reading through the awful docs) to get 1-3 completed, but 4 is giving me issues.

Does anyone know how to do this?

I've tried the following in my_module.module file:

function detailed_menu_uninstall() {
  // Deletes the field storage for the 'detailed_menu_heading' base field.
  $definition = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('menu_link_content')['detailed_menu_heading'];
  \Drupal::service('field_storage_definition.listener')->onFieldStorageDefinitionDelete($definition);
}

Where detailed_menu_heading is the name of the table that was added to the menu_link_content_data table (using HOOK_entity_base_field_info(), with $fields['detailed_menu_heading'] = BaseFieldDefinition::create()). But it doesn't seem to work.

If anyone could give some advice (while I still have a few homer-esque strands of hair left), that would be awesome!

Okay,

After a few more hours of head scratching and hair pulling, I think I've found (or so it would seem) the answer... I'm writing this for myself, as well as anyone else who might stumble across it by route of the all-mighty Google.

From what I can gather, the EntityManager Service has been split up in to several parts. As a result, the bit we're interested in lies within the Entity Field Manager service / class.

We can use this to grab the definition (which I believe is Drupal for - the set of instructions that provide relevant information about an entity [or part thereof]) of our custom entity field.

Now that we have a Drupal readable way of referencing the entity field we're interested in manipulating, we need to actually manipulate it.

Soo... There are a few ways to do this, but I believe the best way is to make use of Drupal's Field Definition Listener service, that seems to do the job we're after. What this listener will do is handle getting rid of all the places that the entity field has been buried away within Drupal itself. From the sounds of the service name it should be using the event dispatcher system somewhere, somehow; although, looking at the source I can't find anywhere that actually does this? (this is in contrast to field_storage_definition.listener, which does dispatch an event, but didn't seem to work, and would white screen with an SQL error, complaining that it can't find the given field when used...)

With these two pieces of the puzzle, it's just a case of putting them together to get the functionality working correctly.

I ended up with:

function detailed_menu_uninstall() {

  // Grabs the entity Field Manager service.
  $entityFieldManager = Drupal::service('entity_field.manager');

  // Grabs the Field Definition listener.
  $fieldDefinitionListener = \Drupal::service('field_definition.listener');

  // Ensures(?) that the field storage for the 'detailed_menu_heading' base field is deleted
  // properly when the module is uninstalled.
  $definition = $entityFieldManager->getFieldStorageDefinitions('menu_link_content')['detailed_menu_heading'];
  $fieldDefinitionListener->onFieldDefinitionDelete($definition);
}

One thing to note is that if I add more definitions to be installed, and consequently uninstalled in this hook, they don't actually need to be put in the uninstall hook, and I'm not sure why... It's as if Drupal just needs a nudge to be told that some things need to be removed from the entity properly, and Drupal does the rest to check what that is? I'm really not sure.


Getting a subset of items: Is it better to user PagerDefault and limit, or get'em'all and array_splice? I want to pull some number of nodes out of the database for rendering and display.  There are several ways to do this, two of which would be:

do a db_select(...)->extend('PagerDefault'); and add a ->limit()
clause to specify the number of items to be returned.
do the db_select() without the PagerDefault, and use
array_slice to get the desired number of items.

Any advice on the relative advantages of these, especially from a performance perspective?  I've done a few informal tests that suggest about a 100% penalty for using PagerDefault, but I wouldn't want to claim these are definitive.  Any recommendations?

Use range() instead:

db_select(...)->range(0, 10);


User tabular data entry to build a budget worksheet? I am trying to build a budget worksheet where users can enter their budget information and save that until the next time they need to update it.  Each user will only have access to their budget sheet.

I spent approximately 16 hours on trying to get Sheetnode and PHPExcel to work, but that is really buggy in my humble opinion (may also be my lack of knowledge).

I'm not really looking for a "how-to" but rather someone point me in another direction where I could possibly find success.  I don't really know what keywords to search in google for what I need to do, but I keep stumbling upon webform, which is a nice module, but does not do what I need at all.

You could try https://drupal.org/project/tablefield or https://drupal.org/project/slickgrid
From module page:

The Slickgrid module is an implementation of Michael Leibman's jquery slickgrid plugin, a lightening fast JavaScript grid/spreadsheet.
It defines a slickgrid view style, so all data can be output as an editable grid.
This module will only work with Slickgrid 2.1.

These do not provide spreadsheet functionality, but you would probably implement the summation or whatever calculation is necessary.


In Drupal 7, how do I allow users to see their own unpublished content? This Drupal page says that for Drupal 7 to allow users to view their own unpublished content to check "view own unpublished content" in permissions.

I have this checked, yet when someone clicks on 'admin/content' it says permission denied.  Of course I don't want to give them permissions related to admin content.

Currently I have the override node options module enabled, and when a user unpublishes their content, they can no longer get back to it to continue editing and then publish it.

I cannot use the 'view unpublished' module as many threads suggest as it gives an entire role access to all unpublished content related to that role.

What I am leaning towards is a view. Currently I have a very good working block that allows people to view their PUBLISHED content while on their profile page. I cloned this and simply switched the filter "published: yes" to "published: no" and it won't work. I tried setting the view permission to view own unpublished content, and it will not work.

Is 'view own unpublished content' broken in D7? Drupal core says I should be able to allow users to view their own unpublished content. How can I do this without all this hakery and dependency on a 3rd party modules?

view own unpublished content permission allows just that - to see /node/%nid even if it is unpublished. Test it, I'm sure it will work.

If you want your users to be able to list their content, well, that's other topic. Easiest way is to use Views to create listings filtered by authors, with filters like is_published or author == current_user).


JS error when using AddThis field displayed in a view I keep getting this error:

ReferenceError: jQuery is not defined }(jQuery));

when using an addthis field displayed in a view.

Anyone has a clue what could be going on here?

AddThis includes it's javascript in the footer. It could be possible that, in your case, you have to add addThis in the header.

You can do this by changing this line of code in the addthis.php:

AddThis.php line 274 comment:

'scope' => 'footer’,

Hopes this help you out!


My custom preprocess function works as soon as the cache is cleared, then stops working I have a custom Drupal 6 module, with a custom theme function. I have implemented hook_theme in my mymodule.module (main module file) as follows:

function mymodule_theme() {
  return array(
    'mymodule_template_regions'   => array(
      'arguments' => array('template' => array()),
      'file'      => 'mymodule.theme.inc',
      'path'      => drupal_get_path('module', 'mymodule') . '/templates',
      'template'  => 'mymodule-template-regions',
    ),
  );
}

I have implemented mymodule_preprocess_mymodule_template_regions() in a file called mymodule.theme.inc, in the main module folder.

I have placed mymodule-template-regions.tpl.php in the templates subfolder inside my main module folder.

This all works fine when the cache is cleared. As soon as the page is refreshed after the initial cache clear, it stops working.

The offending line is line 696 of theme.inc in Drupal Core version 6.19, which states:

if (function_exists($preprocess_function)) {
  call_user_func_array($preprocess_function, $args);
}

When the cache is cleared, the mymodule_preprocess_mymodule_template_regions function exists, so it gets called because the 'if' statement yields TRUE. However, on each subsequent page request, the function does not exist. I presume this is because, for whatever reason, mymodule.theme.inc is not being included.

This is where my knowledge of Drupal breaks down, as I'm unaware of what else is going on here and how to track down why the function is not being included. It looks like the theme registry is still aware of mymodule_preprocess_mymodule_template_regions, but that it's simply not being called because it's not included.

Drupal is looking to include the following file:

drupal_get_path('module', 'mymodule') . '/templates' . '/mymodule.theme.inc'

but, you say that you've put it in the main module folder, here:

drupal_get_path('module', 'mymodule') . '/mymodule.theme.inc'

So Drupal isn't going to include the file on subsequent calls to the theme function. So, you might want to move your include.

You can see this from how your hook_theme is processed in: _theme_process_registry


Type of drupal cache to be cleared on new hook implementation If I implement a new hook which cache type(like menu, css+js, etc) should I clear for the changes to take effect?

If you look at the module_implements() function, it uses the following code to reset the hook cache:

cache_set('module_implements', array(), 'cache_bootstrap');
drupal_static_reset('module_hook_info');
drupal_static_reset('drupal_alter');
cache_clear_all('hook_info', 'cache_bootstrap');

You can just use the same code to do it yourself.


Module Structure question from perspective of PHP dev I'm new to drupal, and am unsure how to aproach writing a module. My uni is moving to drupal, and I'm working on getting a courses module to display information about courses at the uni.

List of things I need to implement

A list of courses in a specific subject that can be put in many places on the site, with differnt subjects
Search page

I think I understand how to do this one, at least

List of courses based on search parameters
List sections in a specifc course and term

I've figured out how to make custom pages and pass data around in the url by follwoing the drupal menu example. From here, I could just custom write everything, and return straight html, and it seems like that would work, but not be the "correct" way to do it in drupal.

The data will be available in an API of sort, I don't know much about it yet. NOrmally I would just make a data class that had sample data in it, and deal with the data later, but it seems like this won't work in drupal.

Should I be aproaching this by trying to get the views module to do the views for my module? It seems like this would be the correct way to do it, but the query is stupidly complex SQL, and the output can't just be a list.

Also, where is a good tutorial on how I should be using content types? It seems like I should be using that effectively as a data class, that somehow gets passed to a view(possibly the views module, maybe just a view I write myself for a page), which renders it, but I haven't been able to figure it out.

Sorry that there is no concrete answer for this, I just really need pointers on how to aprocah drupal modules.

Content Types and /or entities would be the way to go about this.  Content types you can think of as objects that are fieldable.  So for example your course would have fields that would represent an objects property.  All content types are node and accessed similarly and can be distinguished by a node id (nid).  Content types automatically integrate into views.

Views can be used to display your data on the courses and they can be filtered by using exposed filters, or filtered by using contextual filters (arguments from the URL).  Content types are automatically usable in views along with their fields

Entity references are the backbone of relationships in drupal.  In an object sense you can have a one to one, one to many relationships with other objects or content types.  So your course may have sections and what not so in drupal you would create a content type of both Course and Section and then reference them using the entity references module.  See entity reference module which must have the entity api module

Taxonomy is a way to tag stuff so if you want to tag a course a certain subject you could use a field that is a taxonomy reference.


Views grid output is top-to-bottom, not left-to-right? I have a view outputting a grid of fields sorted by title, however the sorting is not what I expected:

What i'm getting:

A  D  G

B  E  H

C  F  I

What I want:

A  B  C

D  E  F

G  H  I

I am pretty sure you need to change the display of your grid from horizontal to vertical or vice-versa. You may also have to play with the "fill up single line setting".


Getting warning message in statistics module Below is the warning message. I'm getting this message sometimes and I'm using Drupal 6.

  user warning: Table './ri5_r3/accesslog' is marked as crashed and
  should be repaired query: DELETE FROM accesslog WHERE timestamp <
  1376371846 in
  /home/ri5/public_html/modules/statistics/statistics.module
  on line 189.

not sure what to do, what is the proper way to solve this issue ?

Doing this in phpMyAdmin solved my problem.

  Login to phpMyAdmin
  Choose the affected database. If you only have one database, it
  should choose it by default so you don't need to do anything.
  In the main panel, you should see a list of your database tables.
  Check the boxes by the tables that need repair.
  At the bottom of the window just below the list of tables, there is
  a drop down menu. Choose "Repair Table"

This should fix your table, and let you access it again. Now that it is fixed... it's a good idea to make that database backup!

taken from this source


SQLite Backup-Restore Backup and Migrate is great as a backup system and thus allows some sort of versioning. This enables  me to roll back easily when developing and testing small sites which I tend to develop in a live environment.Migrating a dev version to a live site is also quite easy this way.

Backup and Migrate does not work for SQLLite, however. I assume the best would be to put the site in maintenance mode, and copy the .ht.sqlite as a backup ... restoring should then be the same in reverse.

Am I on the right track?

I suggest the use of the Read only mode module, it places your site in the maintenance mode, but your visitors can still view the site without enter or change content.

Then make a copy of your database and get out of the maintenance mode.


How to change the value of the publishing status checkbox to false by default? I want that checkbox to be unchecked by default, because currently it's always checked.

And I want this result:

The structure of my content is as follows:

Simply edit your content type's default publishing options under example.com/admin/structure/types/manage/MYCONTENTTYPE (Structure > Content types > MYCONTENTTYPE > Edit).


How to use a hyphen instead of an underscore when using the content type as a Views argument? (Hackable URLs) I have a classifieds site where I would like to list items at a URL structure like this:

classifieds/for-rent/apartments/title-of-my-ad.

That structure is broken down like this (views-page)/(content-type-argument)/(taxonomy-term-arg)/(node-title)

What I want to happen is this: If someone removes  then all nodes will be listed that are apartments, which were created with the 'for rent' content type; If someone remove apartments (the tax arg) then all 'for rent' items, regardless of taxonomy, are listed.

See what I am getting at?

My problem is that the content type argument has to be written with an underscore instead of a hyphen before it will work. I want to use a hyphen. It's not as ugly, plus Google specifically recommends hyphens in the url instead of an underscore, and I want to keep google happy.

so, given the above example,

classifieds/for_rent/etc/etc <= works fine.

classifieds/for-rent/etc/etc <= does not work.

How do I use the hypenated form as the argument? Is there a way to do this in views? Is there a way to write something in the .htaccess file so that when an argument is received with a hyphen the url is passed with an underscore behind the scenes?

Thanks!

If you have only six types, the quickest solution may be to create 6 page displays for your view, eg, one might be:

classifieds/for-rent/%/%

and then override the filter on this display and add node type for_rent.  Then create another page view, say:

classifieds/for-sale/%/%

and filter that page display on node of type for_sale, another:

classifieds/personals/%/%

etc for personals.

ADDITION:

You could create a menu item and do this yourself, eg:

function YOURMODULE_menu() {

  $items=array();

  // any other menu items here

  $items['classifieds/%/%/%'] = array(
    'title' => 'YOUR TITLE',
    'page callback' => 'YOURMODULE_classifieds',
    'page arguments' => array(1,2,3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function YOURMODULE_classifieds($type, $tax, $title) {

  $type=str_replace('-', '_', $type);

  return views_embed_view(NAME_OF_YOUR_VIEW, NAME_OF_DISPLAY, $type, $tax, $title);

}

Now, this was just typed in off the top of my head so there may be subtle issues here, but the basic point is to create a menu item that responds to:

classifieds/SOMETHINGWITHADASHINIT/bar/baz

that gets the dash turned into an underscore for Drupal's internal name of the type.  So, you could "just" create a block display in your view and remove all of View's paths and call it manually like the above.  That, or ask that Views have a "transform underscores into dashes" checkbox like the "transform spaces to dashes" it has for taxonomy terms (which it might already have in D7 :)


getting autocomplete working I honestly did, what this and this tutorial told me, but somehow my autocomplete textfields still fire an ajax error. but to be more specific: the ajax error gives a 200 http response and a status OK, but no answer-text.

my setup is:

$form['field_new_verein_location_'.$i] = array(
    '#type' => 'textfield',
    '#title' => t('Neuer Verein Ort'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#description' => t('description'),
    '#autocomplete_path' => 'dsregion/autocomplete'
);

function ds_regions_menu(){
    $items['dsregion/autocomplete']=array(
      'title' => 'location auto complete',
      'page callback' => '_dsregion/autocomplete',
      'access arguments' => array('access region autocomplete'),
      'type' => MENU_CALLBACK
    );
    return $items;
}

function _dsregion_autocomplete($string) {
    $matches = array();
    $result = db_select('ds_plz_ort','o')
      ->fields('o',array('ort'))
      ->condition('ort','%'.db_like($string).'%','LIKE')
      ->range(0,10)
      ->execute()
      ->fetchAllKeyed();

    foreach($result as $row){
      $matches[$row->ort]=check_plain($row->ort);
    }
  drupal_json_output($matches);
}

You have a slight error in your page callback property for the menu item. You've got a string resembling a path in there instead of the name of the callback function.

Just change

'page callback' => '_dsregion/autocomplete'

to

'page callback' => '_dsregion_autocomplete'

Then clear Drupal's caches and you should be good to go.


Add link that performs database function I am building a tableselect. What I want is to have last row be a link that when clicked performs a CRUD using the row ID as input. The goal is to have a "delete" link that removes that row from the database. Or an add link that does the reverse.

I am looking at the example of the admin/content, which creates links like I need at the end of its table. But because this works on Nodes and I am working on database rows (in a custom table), this doesn't seem to really apply.

Are there any good tutorials/examples on something like this. I've found a few that helped me create the table, but this functionality I can't seem to find.

EDIT: And after reading through my own question again, I realized the business logic here wouldn't work... sorry for getting ahead of myself.

There are two separate things to take care here, one is dealing with the database table, you will find all the functions you need to use for CRUD operations on databases here.

The other issue is dealing with the table showed on the browser page, if you want to operate with tables your best bet (IMHO) is to use Ctools, install  it and enable the Ctools Ajax example submodule, there you will find exactly what you want, a link that removes the file.

Hope this helps.


Search API group by issue with views I have a content type thats is called course which has a field that is a reference to a taxonomy called category.

My specification tells to build a search where users can search for the course title, category and other fields that the course type has. The search functions like intended and everything works great except the display view. Here is my setup:

Drupal 8.5
Search Api with DB / Solr Backend. (tried both)

So to come back: each course can have multiple categorys to be in which means that the view has to be grouped by the category. If I do that my view displays this:

Category 1 Name

Course 1
Course 2

Category 1 Name, Category 2 Name

Course 3

Category 2 Name

Course 4
Course 5

Category 3 Name, Category 2 Name

Course 6

Category 3 Name

Course 7
Course 8
Course 9

As you can see courses that belong to multiple categorys are not listed underneath the respected category instead they are seperated by a comma. My goal is this:

Category 1 Name

Course 1
Course 2
Course 3

Category 2 Name

Course 3
Course 4
Course 5
Course 6

Category 3 Name

Course 6
Course 7
Course 8
Course 9

such behaivor is easy to do if you dont use search api and want just to display a normal view. I have already read this issue but it seems my goal is not possible.

I'm asking now here if something has changed or if its possible to get this done with writing custom code? Maybe tell search api to return every result and display them with custom code grouped by the categorys? Can anyone point me to the right direction?

Group by your Category taxonomy and select to Use rendered output to group rows, then in your Filter criteria for your taxonomy turn on autocomplete of the category terms.

Add View

View Settings: Show Content of type Course sorted by Newest first
Page Settings: Create a page selected
Page Display Settings: Display format Unformatted list of fields

note: you may not want to use the pager.

Edit new View

Advanced:

Relationships: add Relate nodes to taxonomy terms with Vocabularies {Taxonomy} selected and Require this relationship selected
Use aggregation: Selected

Fields: add content: ID, Content: Title, Content: {Taxonomy}

Content: ID: Exclude from display selected, Thousands marker: -None-
Content: ID Aggregation settings: Aggregation type: Count DISTINCT
Content: Title: Formatter Plain text and Link to the Content selected
Content: {Taxonomy}: Exclude from display selected

Format:

Format settings: Grouping field Nr.1 Content: {Taxonomy} and Use rendered output to group rows selected

Filter Criteria: add Content: Title and Content: {taxonomy}

Content: Title: Expose this filter to visitors, to allow them to change it selected and Operator Contains
Content: {Taxonomy}: Expose this filter to visitors, to allow them to change it selected and Operator Is one of
Content: {Taxonomy} settings: Vocabulary {Taxonomy} and Selection type Autocomplete

Sort Criteria: Content: {Taxonomy} (asc), Content: Title (asc), Content: Authored on (desc)

Note: the preview will not display the Grouping titles, but this dose appear on the page.


Is there any way to capture only the updates from "drush cex"? I did a cex to "reset" my config being exported. I then made a bunch of changes to a bundle. Now when I do a new cex I see only the yml files containing my most recent changes. Is there any way to capture JUST these files (into a new folder)?
If I specify a --destination; it dumps my entire config there. Not what I want.

Take a look at Config partial export module

It is able to export to a tarball only modified configuration files.

For available commands in drush:
drush cpex --help


Database query with like condition Currently I am using the following query to select the data from database

$result = db_query("select data from {config} where name like '%IPPOOL_POOL%' ");
while ($row = $result->fetchObject()) {
  $ips=$row->value;
}

But this generated an error like

  Undefined property: stdClass::$value

Please help me to implement same in Drupal 8.

According to  Drupal db_like doc page

Get a database connection injected into your service from the
container and call escapeLike() on it.

For example,
$injected_database->escapeLike($string);

Try something like:
$database = \Drupal::database();
$result = $database->select('table_name', 't')
    ->fields('t', ['field_1', 'field_2'])
    ->condition('field_1', "%" . $database->escapeLike($string) . "%", 'LIKE')
    ->execute()
    ->fetchAll();

Read Database api in Drupal 8 for a better understanding of database query in drupal 8.


How to display the rendered entity of the "compact" display of the user account in the profile? I have a site with Drupal 8 and I want to customize the templates of my pages.

I use the Profile module.

How to display the rendered entity of the "compact" display of the user account in the profile ?

This is the template to customize the profile page.

{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}

      {{ ??? RENDERED ENTITY USER COMPACT ??? }}

UPDATE

      {{ profile.type.entity.label }}

      {{ drupal_entity('user', profile.uid.target_id, 'compact') }}

      {{ profile.getOwner().name.value }}

      {{ content.field_personnel_sexe }}

      {{ content.field_personnel_naissance }}

      {{ content.field_personnel_adresse }}

         Envoyer un message

      Voir son profil

If I understand your question correctly, you want to change the view mode when a user's profile page is displayed. I recommend to put this kind of logic in a module, not in your theme. One way to do this, is by implementing the hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context):

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() == 'user') {
    $view_mode = 'compact';
  }
}


Upload multiple files through a single file dialog? In a Webform, I want to let the user upload multiple files via one call of the file dialog. I found the following modules.

Webform Multiple File Upload
Webform Multiple File

With either of them, I cannot open the file dialog once and select all the files. Instead, I need to open the file dialog again for every file.

Is there a way to allow file uploads in one go for Webform forms?

Can you try Multiupload Filefield Widget and or Multiupload Imagefield Widget

I think those modules can help you.


How to add Google fonts locally At the moment, I have this in my template.php

drupal_add_css('https://fonts.googleapis.com/css?family=Short+Stack',array('type' => 'external'));

I now have the .woff is the theme's folder. What's the proper way to add it?

Use the google-webfonts-helper or a similar tool to download all possible font formats (only *.woff won't be enough regarding cross-browser compatibility).
Store the font files somewhere in your theme, maybe in a subfolder called /fonts.
Use @font-face in your CSS to load the fonts as described in this brilliant CSS-Tricks article: Using @font-face

@font-face {
  font-family: 'MyWebFont';
  src: url('../fonts/webfont.eot'); /* IE9 Compat Modes */
  src: url('../fonts/webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('../fonts/webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('../fonts/webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('../fonts/webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('../fonts/webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', SomeFallbackFont, sans-serif;
}


Translated dates in Views I have a View which outputs the node creation date. But the site is multilingual. The problem is that I cannot choose a custom date format, as the Views just accepts one of a list. If I use a custom PHP format like j F Y (day month year in friendly format), I have prepositions, for example, in Spanish, that I cannot use: it should read "18 de Enero de 2015" instead of "18 Enero 2015" and if I put "j \d\e F Y", this will show a "de" which should not be present in other languages, like English.

Is there some module to just translate dates to multilanguage human friendly dates ? As I said, trying with Regions, Date Formats, Custom Date Format, etc., I cannot achieve what I need. If I use other formats, I have the extra time displayed, which I don't want, etc. etc.

You can create as many alternate date formats as you like. See this page for help: https://www.drupal.org/node/1600786


add booking feature in drupal commerce In drupal commerce, I would like to add booking feature if the product is not available for now. If the product is not available for now, I want to allow user to make booking of this product, I also want to reply email to user as soon as the product is available. Does drupal commerce support for booking? Any suggestion, pls!

Thanks

You can try these modules :
Commerce Waitlist
 or Commerce Stock Notifications
They allow send notifications if product available again. As for possibility for user to reserve product in stock: without custom module such feature,I think, cannot be realized.


hook_views_query_alter creating additional OR statements I am  attempting to add some "OR" statements to my Drupal view (to accomodate a grouping of taxonomy terms).

I am able to replace a tid one for one without an issue using the following code:

function customedm_views_query_alter(&$view, &$query) {
      if ($view->name == 'course_catalog') {
            dpm($query);
            foreach($query->where[1]['conditions'] as &$condition){
                if ($condition['value'] == 422){
                    $condition['value'] = 311;
                }
            }
        }
}

The problem is, I need to replace this value with several values (311,316,and 326)

I've tried replacing the $conditions variable with the proper or statement e.g.:

$condition = "WHERE field_data_field_course_subject.field_course_subject_tid = '311' OR field_data_field_course_subject.field_course_subject_tid = '326'";

Or creating a second $query->where[] array with the seemingly appropriate entries into the array:

function customedm_views_query_alter(&$view, &$query) {
      if ($view->name == 'course_catalog') {
            dpm($query);
            foreach($query->where[1]['conditions'] as &$condition){
                if ($condition['value'] == 422){
                    $newconditions = array(
                    conditions => array(
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 311,
                            operator => '='
                            ),
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 326,
                            operator => '='
                            ),
                        array(
                            field => 'field_data_field_course_subject.field_course_subject_tid',
                            value => 316,
                            operator => '='
                            )
                        ),
                        args => array(),
                        type => "OR"
                    );
                    $query->where[] = $newconditions;
                }
            }
        }
}

Neither of these approaches seem to product the desired outcome (though I was able to verify that the array creating approach created the appropriate fields in $view->query... can someone show me how I can add OR statements to my query using this hook?

Thanks to iLLin I was able to figure out an acceptable answer to this question by using the in operator, and replacing the entire array for the condition.

function customedm_views_query_alter(&$view, &$query) {
  if ($view->name == 'course_catalog') {
        foreach($query->where[1]['conditions'] as &$condition){
            if ($condition['value'] == 422){
                $newvalue = array(
                    field => 'field_data_field_course_subject.field_course_subject_tid',
                    value => array(311, 316, 326, 321),
                    operator => 'in'
                );

                $condition = $newvalue;
            }
        }
    }
}


D6: Create a new template for a specific url of node type page I'm trying to create a completely different template for a page I have set up at:

http://www.example.com/my_page

I thought I just added a new node tpl page (node-my_page.tpl.php), but that doesn't appear to be working. What's the trick?

What you're looking for are template suggestions. If you want to change the page layout (regions, general html) use template suggestions for page.tpl.php. OTOH, if you want to change the node layout (the .node div and whatever is within), use template suggestion for node.tpl.php.


Why does Drupal display node titles at the page level instead of the node level? I'm doing some work with 'Extra Fields' and keep tripping up on the fact that Drupal tends to display the title of a node at the page level when viewing the full node page. It seems to be that it makes more sense to always display the title at the node level. Is there a reason I'm not seeing that makes it better to display it at the page level instead?

Not every page is a node. It's really as simple as that; if node pages' titles were displayed on the node level but other pages' titles were displayed at the page level it makes things inconsistent and more difficult to maintain, document, predict, etc.


How to define frontend theme (non-admin) for a given node tab route? In my custom module I want to define a new tab associated with nodes. I have my own custom route file with the required definitions and a Links file to make sure the new route will be displayed as a node tab.

Everything works as planned, except that... The content of my custom page is wrapped in admin theme, not the website frontend theme.

I have found other threads where people ask the opposite question: 'how to enforce admin theme'? In those situations, it looks like that by setting '_admin_route: TRUE' on the route file will do the trick. More on this here:

How to set admin theme for a route?

I thought I would be able to achieve what I want by setting '_admin_route: FALSE', but it doesn't work. Frontend theme doesn't show, admin theme still kicks in.

This is my modulename.route.yml file:

modulename.node.custom_tab:
  path: '/node/{node}/custom-tab'
  defaults:
    _title: 'Custom tab Content'
    _controller: '\Drupal\bti\Controller\MyTabController::pageContent'
  options:
    _node_operation_route: TRUE
    _admin_route: FALSE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'access content'
    _custom_access: '\Drupal\bti\Controller\MyTabController::access'

And this is my modulename.links.task.yml file:

entity.node.custom_tab:
  route_name: modulename.node.custom_tab
  base_route: entity.node.canonical
  title: 'Custom tab'
  weight: 50
  options:
    attributes:
      class:
        - 'my-custom-class'

So, to sum up: how can I make the new custom page in a node tab be displayed with theme defined for the frontend, not the admin theme? Thank you!

Edit 1

Is it possible that what I am looking for is the attribute '_theme' inside 'options'? It is marked as TODO here: https://www.drupal.org/docs/8/api/routing-system/structure-of-routes.

The _node_operation_route option respect the Use the administration theme when editing or creating content, if you want to explicitly disable admin theme for this node-related page don't use _node_operation_route

The _node_operation_route option overrides _admin_route https://api.drupal.org/api/drupal/core%21modules%21node%21src%21EventSubscriber%21NodeAdminRouteSubscriber.php/function/NodeAdminRouteSubscriber%3A%3AalterRoutes/8.8.x


Undefined variable node in Drupal 7 I am using zaptech theme in Drupal 6 while I am upgrading existing site to Drupal 7 it give me the error: Undefined variable: node in include() ,themes\zaptech\page.tpl.php can anyone tell what the solution for the node object

Remove it unless you have an automatically loaded node associated with it.


Modify "head-placeholder" in html.html.twig that's the first time I approach to Drupal or a CMS more generally but I've been working since years as FE dev.

I'm creating a theme based on a template created from scratch for the Italian Public Administration(PA) in such way to define a standard for the PA websites.

This is the template project

So I have to fully rely over the CSS and JS files provided by the theme, and can't use a base theme.

I'm struggling to understand how to change the content of the head-placehoder and the title one in the html.html.twig file

  <head>
    <head-placeholder token="{{ placeholder_token }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token }}">
    <js-placeholder token="{{ placeholder_token }}">
  </head>

I suggest you look at https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme, which provides pretty good documentation on how to add CSS in a theme.

If you don't extend from a theme then you technically extend from a special theme called "stable". You should get almost no default CSS then, at least from core modules. Unless that really results in a problem, in which case there are some options to override it (documented above), I wouldn't worry about that.


JSON format for creating users with custom fields using services I am using Services module to register new users. My registration form has some custom fields like text field, radio buttons and select list. The following is the data I am sending:

{
"name" : "testapi",
"mail" : "test@test.com",
"pass" : "testapi",
"field_name" : {
"und" : [ { "value" : "Prashant TestAPI" } ]
},
"field_contact_no" : {
"und" : [{ "value" : "9898989898" }]
},
"field_user_sex " : {
"und" : [ { "value" : "male" } ]
},
"field_role_s_ " : {
"und" : [ {"value" : "developer"}, { "value" : "tester" } ]
}
}

The other fields like username, password, email and name(textfield) goes through fine but the sex is a radio button and role is a checkbox, those are not getting populated.

If there a specific way of handling those form types?

Update:
I was able to get it to work with the following code.

{
"name" : "apiuser",
"mail" : “apiuser@example.com",
"pass" : "testapi",
"field_name" : {
"und" : [ { "value" : "Prashant TestAPI" } ]
},
"field_contact_no" : {
"und" : [{ "value" : "9898989898" }]
},
"field_user_sex" : {
"und" : "male"
},
"field_role_s_" : {
"und" : ["developer","other"]
}
}

The views datasource module is more handy. Try this module and create a view of the data you need to send.


How to show the product "add to cart" button on a product kit? I would like to add a "add to cart" button on a product kit, for each product in the product kit. How may I achieve that? I have been searching for a while now. Ubercart 3.

This would be similar to iTunes when viewing an album, the user may buy a single song of the album. Currently with product kit, the user has to click the product link to get to the song then be able to buy it.

Drupal has a number of modules that make "add to cart" and other similar features of Drupal commerce work, by simply enabling those modules.Check out the following links:

Commerce Line Item Cart Form
This link may also help- Cart Modules


Entity Reference auto complete user name with different field I'm using the entity reference module to associate users with a particular content type.  I'm using the auto-complete widget (tag-style).  By default, it uses the user name when auto-completing users.  However, I want to change the field it's searching on.  I have a field, field_complete_name that I want to use instead of the name field.

My question is, is the Entity Reference module capable of doing this?  If so, how do I do it?

I took Mikey's suggestion and made a ctools plugin.
Here's what I came up with:

I'm using a custom module to house the plugin, but technically you could put the plugin into the entity-reference module itself. This would be ok because this method doesn't replace any module code (which would break updates).

Assuming you make a custom module you will need to put this hook into your .module file:

/*
 * Implements hook_ctools_plugin_directory
 */
function custom_module_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

Then you will make a file thats located within your module's ctools plugin directory:
.../modules/custom_module/plugins/selection/realname.inc

The file can be called whatever you want but the file path matters. You could also make the file in .../modules/entityreference/plugins/selection/ as well (as mentioned above).

Contents of realname.inc:

<?php

$plugin = array(
  'title' => t('Use realname'),
  'class' => 'EntityReferenceSelectRealname',
  'weight' => 10,
);

You will then make another file in the same directory as this one. The file uses the name of the class provided above then .class.php so it will be EntityReferenceSelectRealname.class.php for this one.

Contents of EntityReferenceSelectRealname.class.php:

<?php

class EntityReferenceSelectRealname extends EntityReference_SelectionHandler_Generic {

  /**
   * Implements EntityReferenceHandler::getInstance().
   */
  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
    $target_entity_type = $field['settings']['target_type'];

    // Check if the entity type does exist and has a base table.
    $entity_info = entity_get_info($target_entity_type);
    if (empty($entity_info['base table'])) {
      return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
    }

    if (class_exists($class_name = 'EntityReferenceSelectRealname_' . $target_entity_type)) {
      return new $class_name($field, $instance, $entity_type, $entity);
    }
    else {
      return new EntityReferenceSelectRealname($field, $instance, $entity_type, $entity);
    }
  }
}

/**
 * Override for the User type.
 *
 * This only exists to workaround core bugs.
 */
class EntityReferenceSelectRealname_user extends EntityReferenceSelectRealname {
  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityFieldQuery($match, $match_operator);

    // The user entity doesn't have a label column.
    if (isset($match)) {
      //This line uses the regular username:
      //$query->propertyCondition('name', $match, $match_operator);

      //This was added to use the "realname" field instead of the regular username:
      //CHANGE THIS:
      $query->fieldCondition('field_er_realname', 'value', $match, $match_operator);
    }

    // Adding the 'user_access' tag is sadly insufficient for users: core
    // requires us to also know about the concept of 'blocked' and
    // 'active'.
    if (!user_access('administer users')) {
      $query->propertyCondition('status', 1);
    }
    return $query;
  }

  //Not sure if this is necessary, but I'll add it in to be safe.
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
    if (user_access('administer users')) {
      // In addition, if the user is administrator, we need to make sure to
      // match the anonymous user, that doesn't actually have a name in the
      // database.
      $conditions = &$query->conditions();
      foreach ($conditions as $key => $condition) {
        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
          // Remove the condition.
          unset($conditions[$key]);

          // Re-add the condition and a condition on uid = 0 so that we end up
          // with a query in the form:
          //    WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
          $or = db_or();
          $or->condition($condition['field'], $condition['value'], $condition['operator']);
          // Sadly, the Database layer doesn't allow us to build a condition
          // in the form ':placeholder = :placeholder2', because the 'field'
          // part of a condition is always escaped.
          // As a (cheap) workaround, we separately build a condition with no
          // field, and concatenate the field and the condition separately.
          $value_part = db_and();
          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
          $value_part->compile(Database::getConnection(), $query);
          $or->condition(db_and()
            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
            ->condition('users.uid', 0)
          );
          $query->condition($or);
        }
      }
    }
  }
}

You will want to go in and change field_er_realname to your field's name. Which is field_complete_name in your case. Btw, I used the Computed Field module to generate my "realname" field based on the first and last name provided.


API to localize a path? I'm searching for a way to get all localized paths for one path.

For non-content pages this is quite simple:

foreach (language_list() as $language)
  $paths[$language->language] = url(current_path(), array('language' => $language));
}

For content pages (node, taxonomy, …) the path might be completely different and things like translation_path_get_translations() seem more like what I need.

Is there a reliable way to get paths to all translations of a page that works whether it's a content-page or not? It feels like there has to be an API-function for that.

I finally found out about language_negotiation_get_switch_links($type,$path). The tricky part is the $type argument. The types are defined by implementations of hook_language_types_info() and at least for my setup $type = 'language' does the trick.


Including a sub-template in a theme I've read numerous answers to similar questions here but I can't for the life of me work out how to do this seemingly simple thing. I simply want to include a Twig template (theme_name/templates/system/footer.twig.html) from another Twig template in my custom theme (theme_name/templates/system/page.twig.html).

In my page.html.twig I've tried all of the following (obviously with theme_name as the actual theme name):

{% include 'themes/custom/theme_name/templates/system/footer.html.twig' %}
{% include 'footer.html.twig' %}
{% include 'system/footer.html.twig' %}
{% include directory ~ '/system/footer.html.twig' %}
{% include '/' ~ directory ~ '/system/footer.html.twig' %}
{% include "@theme_name/system/footer.html.twig" %}
{% include "/var/www/html/web/themes/custom/theme_name/system/footer.html.twig" %}

Each of these produces the following error, with the template varying on the method I've tried:

  Twig_Error_Loader: Template
  "themes/custom/theme_name/templates/footer.html.twig" is not defined
  (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find
  template "themes/custom/theme_name/templates/footer.html.twig" in the
  Drupal theme registry.) in
  "themes/custom/theme_name/templates/homepage/page--front.html.twig" at
  line 177. in Twig_Loader_Chain->getCacheKey() (line 115 of
  /var/www/html/vendor/twig/twig/lib/Twig/Loader/Chain.php).

I've even tried using hook_theme in my theme_name.theme file to no avail.

<?php

function my_theme_theme() {
  return [
    'footer' => [
      'variables' => [],
    ],
  ];
}

No need to set up hook_theme, Just include like this:

{% include '@theme_name/system/footer.html.twig' with content %}

this will include that template in your main template.  The variables will need to be available from the main template.

The "with" statement sets up the variables being sent to the sub-template.  See http://twig.sensiolabs.org/doc/tags/include.html


Replace/alter/rename form labels in theme I installed this Simplenews module, and it gives default field to enter your email to subscribe for newsletter and the fields title is just 'Email:' and I need to change it to something else.

It looks like it's hardcoded and I could just dig through modules files and edit, but I know this is not recommended.

I was hoping maybe I could just paste in some preprocess function to theme's template.php file and replace 'Email:' with e.g. 'Join Our Mailing List:'.

Path to label is form.simplenews-subscribe div div label.

Solved!

Put this code to your theme's template.php, where's THEME replace it with your theme's dir name. So then where's #title = t() you put in your own custom title for the field. So what it does it alters given forms field, in this case it's simplenews_block_form inlcuded in between THEME_form_simplenews_block_form_alter

function THEME_form_simplenews_block_form_alter(&$form, &$form_state) {
  $form['mail']['#title'] = t('Join Our Mailing List:');
}

Clear cache!


Second level in the menu I have created a menu with items and one item has second level. So I created child links.

The problem is that the item which has second level links to some page and I would like to make it to link nowhere. It would be only collaps/expand link that shows or hides the child links.

I have found only possibility to set the link as <front> but this does not make what I want. Is this possible in Drupal 7?

OK, I found some modules the could help, Menu block and Nice menus but it seems that my problem could have some easier solution. How would you solve it? With some javascript?

thank you

There are two modules I know of specifically for allowing menu items that are not 'proper' links. There's Special menu items (which doesn't have a D7 release, but there's a patch) and Menu Firstchild (they're not identical in features, but both do what you want I believe).

You might also be interested in DHTML Menu which has a beta1 release for D7.


Disabling module with config sync and removing with composer I have an issue disabling modules, I've searched but cannot find something useful:
 - Developer A disable module and via composer remove it
 - I pull his changes so i run composer install that remove the code, then drush cim to update configuration, but it complains that the module is missing while it's trying to delete its configurations.

What's the right way to do this? I can't import config before running composer install because along the uninstalled module there could be also new modules needed for the configuration import.

You need two consecutive releases for stuff like that.

First release:

Your colleague uninstalls the module and commits the updated config.

If you don't manage your site via config use hook_update_N instead.

/**
 * Uninstall SOME_MODULE module.
 */
function MYMODULE_update_8001(&$sandbox) {

  \Drupal::service('module_installer')->uninstall(['SOME_MODULE']);
}

Second release:

The module can be removed via Composer.

Related:

Order of drush commands for automated deployment?


Show related Taxonomy list if created I have created the following construction. If a student choose option A with the if construction the following step in the wizard is the internships with medicine domain A, but what if the school create another medicine domain B. With this construction the student will only see the internship domain A and not the medicine domain a AND b. I'm looking for a construction that grows with my Taxonomy (shows medicine domain a and b and if the school create 5 months later a medicine domain c that last one must seen by the student also), so if a student choose medicine than he get all medicine domains (medicine domain a and b and so on) and not just $internship domain a as defined in my if structure. Hope you understand my problem because it is explained in terrible English.

enter code here
case 2:

// Taxonomy list: 'valid type of internship'.

$valueInternship = $_SESSION['gekozenOpleiding'];

//var_dump($valueInternship);

if($valueInternship == 1) { // Stagedomein a
    $internship = 10;
}

if($valueInternship == 2) { // Stagedomein b
    $internship = 11;
}

if($valueInternship == 3) { // Stagedomein c
    $internship = 13;
}

if($valueInternship == 4) { // Stagedomein d
    $internship = 12;
}

if($valueInternship == 5) { // Stagedomein e
    $internship = 14;
}

$dropdown_source_geldig_soort_stage = taxonomy_get_tree($internship);
$dropdown_array_geldig_soort_stage = array();
foreach ($dropdown_source_geldig_soort_stage as $item) {
    $key = $item->tid;
    $value = $item->name;
    $dropdown_array_geldig_soort_stage[$key] = $value;
}
$form['geldig_soort_stage'] = array(
        '#key_type' => 'associative',
        '#multiple_toggle' => '1',
        '#type' => 'checkboxes',
        '#options' => $dropdown_array_geldig_soort_stage,
        '#title' => 'Welk geldig soort stage',
        '#multicolumn' => array('width' => 4,
                '#default_value' => isset($default_value['geldig_soort_stage']) ?
                $default_value['geldig_soort_stage'] : '',
        ),
);
break;

This is a very frequent problem. Drupal has a simple solution. It is called the Context module.

The context module will allow you to ONLY show information based on term throughout the whole website. Or, only show information based on a user role. So a teacher will have different Views show in a block than a student who will have different Views based on the internship they have.

The context module also allows you to stack. You can have a context for A, B, C, D. In the Right block region of the page.tpl.php that shows four different blocks based on the taxonomy terms selected. If the student selects term A & B. Then they have the Views block for a & b show at the same time. Or, they can have terms A, B & C. If term A shows 1 block and term B shows 1 block then A & B will have two sidebar blocks showing. If intership C is much more complicated and requires 5 blocks of information then a student with terms A, B & C will have 7 blocks on one page.


How to alter default ajax_view default ScrollTop? In ajax_view.js, the code responsible of smooth Ajax View ScrollTop when changing the exposed filters is the following :

Drupal.ajax.prototype.commands.viewsScrollTop = function (ajax, response, status) {
  // Scroll to the top of the view. This will allow users
  // to browse newly loaded content after e.g. clicking a pager
  // link.
  var offset = $(response.selector).offset();
  // We can't guarantee that the scrollable object should be
  // the body, as the view could be embedded in something
  // more complex such as a modal popup. Recurse up the DOM
  // and scroll the first element that has a non-zero top.
  var scrollTarget = response.selector;
  while ($(scrollTarget).scrollTop() == 0 && $(scrollTarget).parent()) {
    scrollTarget = $(scrollTarget).parent();
  }
  // Only scroll upward
  if (offset.top - 100 < $(scrollTarget).scrollTop()) {
    $(scrollTarget).animate({scrollTop: (offset.top - 10)}, 500);
  }
};

})(jQuery);

I tried to alter this behaviour from a custom module, but no way to get it working. How can I proper change the values of offset.top - 10 to offset.top - 100 ? Here's one of my several tries...

function MYMODULE_init() {
  drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js');
  //...

//IN MYSCRIPT.js
Drupal.behaviors.events = {
  attach: function(context, settings) {
    $('.my_view', context).ajaxStart(function(){
      $('.my_view', context).fadeTo(500, 0.7);//this works
    });
    $('.my_view', context).ajaxSuccess(function(){
      $('.my_view', context).fadeTo(300, 1)//this works
          .animate({scrollTop: (offset.top - 100)}, 500);//this doesn't
  //...

As @Clive mentioned it is because your JS order load is wrong(your JS loaded before than views JS)
I suggest you instead add JS in hook_init put it in hook_form_alter or in hook_page_preprocess

drupal_add_js( drupal_get_path('theme', 'MYTHEME').'/assets/js/MYSCRIPT.js',array(
            'type' => 'file',
            'scope' => 'footer',
            'weight' => 100,
        )
);


How to set the classes used in Drupal commerce buttons with Bootstrap theme I am working on a site with Drupal commerce, I use the Bootstrap theme and a child theme.
I would like the [add-to-cart] button to have the "btn-default" class, instead of “btn-success". Actually, I want to get rid of the "info" and "warning" classes in many cases where I don't need them and replace them by "default" or "primary".

I saw in /sites/all/themes/bootstrap/bootstrap.api.php

/**
 * Allows sub-themes to alter the array used for colorizing text.
 * …
 * @see _bootstrap_colorize_text()
 */
 function hook_bootstrap_colorize_text_alter(array &$texts) {
   // This matches the exact string: "My Unique Button Text".
   $texts['matches'][t('My Unique Button Text')] = 'primary';

  // This would also match the string above, however the class returned would
  // also be the one above; "matches" takes precedence over "contains".
  $texts['contains'][t('Unique')] = 'notice';

  // Remove matching for strings that contain "apply":
  unset($texts['contains'][t('Apply')]);

  // Change the class that matches "Rebuild" (originally "warning"):
  $texts['contains'][t('Rebuild')] = 'success';
}

So I tried in /sites/all/themes/[my-sub-theme]/template.php

function hook_[my-sub-theme]_colorize_text_alter(array &$texts) {
  // Let's try a dummy change for a test
  $texts['contains'][t('Update cart')] = 'success';
}

But I can't see anything changed.

I also saw that /sites/all/themes/bootstrap/includes/common.inc sets a number of values based on the contained string, in which I find th “Update” I am looking for.  the function is
function _bootstrap_colorize_text($string, $default = '') {…}
it ends with

// Allow sub-themes to alter this array of patterns.
    drupal_alter('bootstrap_colorize_text', $texts);

But I still haven't found how to do what I want in my sub theme. and what I read in /sites/all/themes/bootstrap/templates/system/buttons.vars.php won't help me.

Can somebody please explain where to start?

I'm having the same type of issue (which I will post elsewhere). I'm not sure I have the best answer, but from what I read in the Bootstrap API documentation, I believe your code should read as follows.

function [my-sub-theme]_colorize_text_alter(array &$texts) {
  // Let's try a dummy change for a test
  $texts['contains'][t('Update cart')] = 'success';
}

The preceding "hook" needs to be entirely replaced by your [my-sub-theme] name.
From what I read, that should be what is needed for this to work. However, I'm having trouble getting it to work myself.


Restrict nodes and terms per user First of all, I'm using Drupal 6.

I'm developing a website where I want the users to automatically have their own "group"; this means they are only able to see their own nodes. If another user creates an account, he won't have access to other users' nodes. Also, users can add new terms to some fields (using "Hierarchical Select") and I want it to be restricted to each user too.

I also want a user (lets call it "user A") creates another user and they can have access to the user A's "group"; this means that they can see user A's nodes and terms.

I was looking for the Organic Groups module, but it doesn't seem able to do this. If it is, I don't know how to do that.

Do you have any suggestion?

To create something both so specific and complex, you probably won't be able to find modules that will solve this problem for you 100%. So to be able to do this you will have to develop some of this yourself (or pay some one to do it for you)

You best bet will be to start of with organic groups, rules might also help. The fact that you want users to be able to create other users complicate things, as that is something usually done by admin users. Most likely you will have to create your own custom form to handle this.


How to add javascript after form was validated with ajax callback? I created a simple form.
How could I add JavaScript commands after form was validated? Why is it so hard do this?

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#validate' => 'my_validate_callback',
  '#ajax' => array(
    'callback' => 'my_form_callback',
    'method' => 'replace',
    'wrapper' => 'form-wrap',
    'effect' => 'fade'
  )
);

If you only want to add a JS file in validate or Ajax handler function you just need to add JS to form with drupal_add_js or attach it to form.

This is an example of how can you add JavaScript in Ajax callback function:

function my_form_callback(&$form,$form_state){
if(some validation ){
$form['#attached']['js'] = array(
  drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
);
}
return $form;
}


French accented characters not saving to database I have created a module that reads in a csv file that has french accented characters in it to create nodes from. The creation of the nodes seems to work fine but when I execute the node_save() command I get the following error:

An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=55&op=do StatusText: Service unavailable (with message)
ResponseText: PDOException: in field_sql_storage_field_storage_write()
(line 494 of /var/www/html/modules/field/modules/field_sql_storage/field_sql_storage.module).

The special character I am having problems with is é character (however I am sure other accented characters will cause me grief as well).

I thought this was an encoding issue and checked the database encoding on the tables - all tables are set to UTF8. I believe that this is the correct encoding and should work (however I am no database expert).

I tried using the following code:

$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

Which seems to help but still gives the same error after 300 items are read in (there are 3000 items that need to be imported). During the importing, I am Geo-referencing the nodes, so could this be Google killing the look-ups after so many hits?

I am at a loss and would appreciate if anyone could shed some light as to what might be the issue.

Both suggested solutions above are good things to check when trying to solve this problem.

In my particular case, using the fgetcsv command. It silently chokes on files that are not UTF-8 encoded and contains accented characters. To fix this problem I had to implement the file read function as follows:

while (($line = fgets($file_handle)) !== FALSE) {
  // Ensure the line we read is encoded properly
  $value = mb_check_encoding($line, 'UTF-8') ? $line : utf8_encode($line);
  $data = str_getcsv($value);
  // process the data as normal
}

This fixed my issue.


How to create a responsive views block in bootstrap? I created a content type with one field collection field using Field collection module which accepts up to 4 values.

Field Collection: Field collection field has 3 fields (text1(40 char), text2(255 char), link). I added one content. Now I have one content with 3 field collection items.
View: I created a views grid block. Grid settings > number of columns = 1.
I selected the above field collection item as field.
On the block configuration page, I gave class col-xs-12.

When I visit the page in mobile, I have to scroll to right to see the full content. I gave bootstrap class col-xs-12, why does it not fit into into mobile screen. Can you please help?

Image-1

Image-2

The grid default format is not responsive, you can trie Semantic Views


Adding ajax to text field in node edit form I have created a content type "Type A" and added three fields to content type. I want to display value in third field equal to (value of first field - value of second field).

I want to implement the same using ajax functionality. I have created a custom module and alter the "node form" and add ajax to field 1 but ajax is not working on change event of textfield.

Code Snippet:

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

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

    $form['field_value_first']['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

    $form['field_value_first']['und'][0]['#ajax'] = array(
        'callback' => 'employee_login_ajax',
        'wrapper' => 'calculate-total-value',
        'method' => 'replace',
        'event' => 'change',
    );

}

function employee_login_ajax(&$form, &$form_state) { //print_r($form); exit;
  print_r($form_state['values']);
}

You don't need ajax, you can do this with jQuery or javascript. Something like this might work.

First, create an external js file and set up your change events.

jQuery(document).ready(
    function()
    {
        jQuery("#field2").change(subtract_fields);
        jQuery("#field1").change(subtract_fields);

        function subtract_fields()
        {
            if (jQuery("#field1").value != "" && jQuery("#field2").value != "")
            {
                return jQuery("#field1").value - jQuery("#field2").value;
            }

            return "";
        }
    }
);

Next, load the external js file using drupal_add_js.

Clear your cache and voila.


Configuration management import error I use a CMI workflow with Git.

I made configuration changes on Dev
pulled them into Production
now when I go to admin/config/development/configuration and try to
import All I get this error:

  The configuration cannot be imported because it failed validation for
  the following reasons: Entities exist of type Taxonomy term en
  Vocabulary Catalog. These entities need to be deleted before
  importing.

What do I have to do now?

Exactly what it says. You seem to be deleting the Catalog vocabulary. You need to delete all terms in it first.


Giving a user the choice to appear offline in a view showing online users I created a views block which displays users which are online. I would like to give a user a choice to be able to appear offline (i.e not be listed in the block) when he/she is online.

Thank you in anticipation.

Assuming Drupal 7, you can go to /admin/config/people/accounts/fields, attach a Boolean field to user accounts to allow the user to select their preference, then filter on that user field in your view to exclude those who opt out.


Drupal 8 create a template override for a view block within a custom module The Question:

In Drupal 8: How do I add a template override for a view block and have that twig file reside in a custom module - not my theme?

Further Information:

I have already created a custom module that creates a content type, imports data from an RSS feed and generates nodes into the content type it created.  The module also contains a view YML file so that the view for my content type is created when the module is installed.  The view only has one display which is a block.

I would like to create a template override for the block and house the template override within the module (rather than within my theme).  The template override does the following:

Adds the appropriate classes to the block
Adds an image beside the block title when the title is displayed
Wraps the {{ content }} in a div with an appropriate class
Loads the custom module's library to apply CSS

The goal is to have a module that a non-technical person can install, assign a block to the desired region and have all the templates, CSS, JS, etc pull from the module.  I don't want them to have to copy a template into their theme, etc.  I want the block to be a view so that the user can use the Views UI to make any desired updates to the view block's fields, number of returns, etc.

I was able to get Drupal to recognize the template by using hook_theme_registry_alter() but the variables from the block are null.  Both the {{ label }} and {{ content }} are null when I kint them in the template override.

Here is the hook_theme_registry_alter() code:

/**
 * Implements hook theme_registry_alter
 **/
function MYMODULE_theme_registry_alter(&$theme_registry){
  $theme_registry['block__views_block__MYVIEW_block_1']['path'] = drupal_get_path('module','MYMODULE') . '/templates/';
  $theme_registry['block__views_block__MYVIEW_block_1']['template'] = 'block--views-block--MYVIEW-block-1';
}

It should be noted that when I used hook_theme_registry_alter() for a view page template override in my module it worked.  My guess is that the variables were pulled from the page alias.

Please include detailed information because I am still learning about the various hooks and how variables are passed.  Thanks in advance!

To get the same variables as a block template add it as base hook:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__views_block__MYVIEW_block_1' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}

Now you can place the twig template in mymodule/templates/, path and filename are discovered automatically.


What is the purpose of _field_sql_storage_columnname()? While reviewing a patch, I came across an interesting function, _field_sql_storage_columnname(). And I couldn't help but wondering, why on earth do we have this function?

git blame unfortunately wasn't helpful, as it only lead me to a commit that cleanup up windows line-endings.

I think it's clear what the function is doing, the question was more why a function is required for that.

My guess is that the function was there from very first day field API existed where it might have made sense to change it. Nowadays, it's not going to be as easy as "just" changing that function, because it will obviously completely break all existing field tables.

I think the function is still useful for consistency reasons as there is one for the table name as well and I think it's also easier to read because it implies the string is the column name, which might not be that obvious if you e.g have a line like this:

$sql_field = "$table_alias." . _field_sql_storage_columnname($field['field_name'], $specifier['column']);
// vs.
$sql_field = "$table_alias." . $field['field_name'] . '_' . $specifier['column'];


How to Exclude a Specific Node from a Block View I know you can exclude the current node from a list view.

What I'm trying to do is exclude a specific node from a block view.

I have a list of the Top 5 Viewed pages I created into a block view, but I'm trying to hide one of them that keeps showing as it's the home page. I'd like to exclude that from the view.

Is it possible? I couldn't find anything in Contextual Filters.

I'm using Drupal 7 btw

Regards
Tony

Just add a filter on node id which excludes the node in question


Display content with Taxonomy on User and Content matching I've got a specific content type.  One field is a term reference field called "blog subject" in which a content author tags the node.

Ok.  Moving on to the end user.  I added the same term reference field to user account settings in which a user can select certain terms that they're interested in.

I would like to create a view in which the contextual filter is the user.  By going to www.whatever.com/blogs/12, I can see content that matches the users selected interests.

Thoughts?

Create a view showing users, and use a contextual filter on User:UID, and set 'Provide default value' the the 'Currently logged in user'.

You then should create two Relationships. The first on User:blog_subject will relate the user to the taxonomy terms. The second, using the first, will be on Taxonomy Term: Content using Blog Subject which will then relate the term to the content. Both relationships should be 'Required'.

Once the relationships  are in place, delete the 'User Name' field that is a default for the type of view you created, and add the Content:Title field displayed as a link to content. Add filters like Content:Published to eliminate un-published content and a sort by, for example, Content:Post Date (desc). All of these fields will be using the relationships. Make sure you delete all the User:... filters and sorts.

With multiple terms possible, this may create duplicate rows. There are two approaches you can use. The simplest is to go to Advanced > Other and configure the Query Settings to 'Distinct'. This might work. The other is to list the term and Set the view to Group By the term. That way you will get a list of pages that conform to each subject. If a page appears multiple times, it will do so under separate subject lists.

This should show a list of content matching the interests of the current user.


How to access variables in a fieldset with variable_get function bi_mx_enhancement_form($form, &$form_state) {
    $form['bi_mx_enhancement_government_ws'] = [
        '#type' => 'fieldset',
        '#title' => t('Government Web Service Settings'),
        '#tree' => true,
        '#collapsible' => true,
    ];
    $form['bi_mx_enhancement_government_ws']['base_url'] = [
        '#type' => 'textfield',
        '#title' => t('Base URL'),
        '#default_value' => variable_get('base_url', 'https://'),
        '#description' => t('The base URL of the Government Web Service for Medic Validation. NOTE: Do not add a trailing slash.'),
        '#required' => true,
    ];

    return system_settings_form($form);
}

Variable base_url does not get saved, I always get the default value in the form.

I took a look at Drush, and it is like this:

bi_mx_enhancement_government_ws:
  base_url: 'http://52.203.204.11:8282/api/medicos'

Since you are setting #tree to TRUE, the values will be saved in the bi_mx_enhancement_government_ws persistent variable, which will contain an array. For the code you are showing, its value will be similar to the following one.

array(
  'base_url' => 'https://'
);

Instead of variable_get('base_url', 'https://'), consider using the following code.

$values = variable_get('bi_mx_enhancement_government_ws', array());
$ws_base_url = $values['base_url'];

When you are now using variable_get('base_url', 'https://'), you should use $ws_base_url.

Since you seem to just use a single setting for that fieldset, I would rather use '#tree' => FALSE, if that form doesn't have any other form field which is using base_url as identifier.


drupal_render not working in views-exposed-form.tpl.php? I put this in the template:

<?php print drupal_render($form['title']); ?>
<?php print drupal_render_children($form); ?>

Neither renders anything. If I dsm($form) the variable looks correctly populated.

Any ideas?

Ok I noticed that #printed = TRUE on all my form elements, so they are not being printed. Going to make a new question for why they are set that way.


can you put views field values into a global token? Suppose I want to use a paragraph field value of an entity for metatag title (by using metatag views module)

I can successfully get the value of the paragraph entity and display it on the view

Now, is there a way i can save those field to a token so i can use it here?

Regards,

I do not believe this is possible if paragraphs module does not provide this token itself. The way to do it would be to create your own token. Even with this it may be tricky to figure out that information.

To create your own token you will need to look into the hook_token_* items such as hook_token_info.

It sounds like to me your best bet would be attempting to hook into the views pre processing and change the value that way.


Anchor links to views grouping field titles I want to make a table of content block where I link to the grouping field titles on a view. The problem is that the grouping field is only a h3 without any class or id. Is there a way to nest the h3 in a div with an unique ID so I can create an anchor link for it?

I think this may be a template modification task.

This is the current views-view-unformatted.html.twig file:

{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{ row.content }}

{% endfor %}

Switch:

{{ title }}

With:

{{ title }}

This would require your titles to all be unique to ensure unique ID's. There may be something better to use than "title" for the ID as well in this case.

Also, I would wonder if using an "attachment" in the view might give better options and control over a block for the table of contents...


Content type drop down filter types In the content page, there is a filter that shows the page, and other types of content.

Is there a way for me that will allow me to show only certain types of items in the content type.

Thank you,
Kevin

You can use Administer views but to quickly achieve this I would use the hook_form_alter.

Do something like this, Although I would recommend you set this restriction to specific role but for this example I am going to ignore roles. Within hook_form_alter you do

if($form['#form_id] == 'node_admin_content') {
   unset($form['filter']['filters']['status']['filters']['type']['#options']['article']);
}

You can change the ['article'] to whatever the machine name of your content type is. use devel to find out what elements the $form variable contains.


How to add custom checkout pane to drupal-commerce in drupal 8 I installed drupal-commerce on drupal 8, straightforward and easy using composer.
Now I need to collect some extra information from customer at checkout, and I understood, I need to install a custom checkout pane.

Unfortunately there is no module for that, so I guess, I have to write a custom module. I know how to generate it with drupal-console, but than I'm lost...

It should be possible to copy some of the code from commerce checkout module, but I have no idea where to start. Can someone help me with that? Thanks!

Here is an excerpt from our step-by-step guide "Creating a custom checkout pane for Drupal Commerce in Drupal 8". The rest can be found here: https://ws.agency/blog/creating-custom-checkout-pane-drupal-commerce-drupal-8

"In this article, I'll show how you can create a custom checkout pane for Drupal Commerce in Drupal 8. For this purpose, we'll create a checkout pane with a configuration form and the ability for users to add coupons to their order.

Checkout pane needs to be created with the correct annotation and in the correct namespace. We'll create CommerceCoupons class in module_name/src/Plugin/Commerce/CheckoutPane directory with annotation like in code below.

namespace Drupal\module_name\Plugin\Commerce\CheckoutPane;

use Drupal\commerce_checkout\Plugin\Commerce\CheckoutFlow\CheckoutFlowInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides the coupons pane.
 *
 * @CommerceCheckoutPane(
 *   id = "coupons",
 *   label = @Translation("Redeem Coupon"),
 *   default_step = "order_information",
 * )
 */
class CommerceCoupons extends CheckoutPaneBase implements CheckoutPaneInterface {

/**
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition,     CheckoutFlowInterface $checkout_flow, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $checkout_flow, $entity_type_manager);
}

This means that our custom checkout pane will have an id 'coupons' and will be labelled as Redeem Coupon and will be set on order information step by default.

First, we'll create the settings (configuration) form for our pane. For this purpose, we'll have settings if we, for example, want to set up that user has the ability to redeem only one coupon on order. For this, we'll have to implement four functions.

First, we'll setup our default configuration.

/**
 * {@inheritdoc}
 */
public function defaultConfiguration() {
  return [
      'single_coupon' => FALSE,
    ] + parent::defaultConfiguration();
}

Then we'll implement summary for our configuration form.

/**
 * {@inheritdoc}
 */
public function buildConfigurationSummary() {
  $summary = !empty($this->configuration['single_coupon']) ? $this->t('Single Coupon Usage on Order: Yes') : $this->t('Single Coupon Usage on  Order: No');
  return $summary;
}

Next, we'll build our configuration form..." Continue reading...


How can I get the content type of a node given its node ID? I have a URL like track-new/15/51. arg(2) returns 51.

How can I check if the content type of the node whose ID is 51 (the value returned from arg(2)) is 'artist'?

If the value returned from arg(2) is a node ID, you can load the node with node_load(). This will return a node object, which contains its content type.

$node = node_load(arg(2));
$content_type = $node->type;


Core search, when only one result, open result Is there a simple way to accomplish the feature in the title ?
When a search results in one result, don't show the result but go directly to the node.

As I see the only way is use hook menu alter for this item

/**
 * Implements hook_menu().
 */
function search_menu() {
  $items['search'] = array(
    'title' => 'Search',
    'page callback' => 'search_view',
    'access callback' => 'search_is_active',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'search.pages.inc',
  );

I propose to replace page callback "search_view" to your own and put there your logic.


Running ajax callbacks on custom composite field I am using a custom composite field("test") in drupal8 webform in a webform_form_alter() hook. Two select fields-"out_part" and "out_serial" are added to this composite field("test"). "out_serial" is dependent on "out_part" i.e. upon selecting an out_part value from the dropdown, the dropdown values of out_serial are generated. I was able to achieve this with ajax callbacks.

    $form['elements']['test']['#element'] = array(
    'out_part' => array(
            '#type' => 'select',
            '#id' => 'out_part',
            '#options' => array(
                '80002192'=>'80002192',
                '80002191'=>'80002191'
                ),
            '#ajax' => array(
                'event' => 'change',
                'wrapper' => 'serialNumber_wrapper',
                'callback'=> 'populateOutSerialNumbers',
                'method'=> 'replace'
                )
            ),
    'out_serial' => array(
            '#type' => 'select',
            '#id' => 'out_serial',
            '#validated' => TRUE,
            '#attributes' => [
                                'id' => ['serialNumber_wrapper'],
                              ],
            ));

    function populateOutSerialNumbers($form, $form_state){
        $partNumber = $form_state->getValue('test')[1]['out_part'];
        $partNumber = isset($partNumber) ? $partNumber : 'Onboard';

        // Update the $result with dynamic database query results with respect to selected out_part
        Drupal\Core\Database\Database::setActiveConnection('***');
        $db = Drupal\Core\Database\Database::getConnection();
        $query = $db->query("select distinct T1.serialnumber from assets T1 where T1.dbid <> 0 and (T1.manufacturerpartno = :partNumber)", [':partNumber' => $partNumber]);
        $result = $query->fetchAllKeyed(0,0);

        $form['elements']['test']['#element']['out_serial']['#options'] = $result;

        db_set_active();
        return $form['elements']['test']['#element']['out_serial'];
    }

This callback works only on the first set of values of the custom composite field. When I click on "Add", the ajax fails to work on the second set of values. Any suggestions on how to overcome this? Do I need to add the ajax to
    $form['elements']['test']['items'] ?

You can not modify the $form in the ajax callback. The option for the element out_serial should be set inside form build not in ajax callback. Try with following approach:

// Inside your form build or alter function.
$form['elements']['test']['#element'] = array(
  'out_part' => array(
    '#type' => 'select',
    '#id' => 'out_part',
    '#options' => array(
      '80002192'=>'80002192',
      '80002191'=>'80002191'
    ),
    '#ajax' => array(
      'event' => 'change',
      'wrapper' => 'serialNumber_wrapper',
      'callback'=> 'populateOutSerialNumbers',
      'method'=> 'replace'
      )
    ),
  'out_serial' => array(
    '#type' => 'select',
    '#id' => 'out_serial',
    '#validated' => TRUE,
    '#attributes' => [
        'id' => ['serialNumber_wrapper'],
      ],
    )
);

// Set value here as when you return the element in ajax callback.
// the form will come here again for rebuild with $form_state having filled values.
if (!empty($form_state->getValue('test'))) {
  $partNumber = $form_state->getValue('test')[1]['out_part'];
  $partNumber = isset($partNumber) ? $partNumber : 'Onboard';

  // Update the $result with dynamic database query results with respect to selected out_part
  Drupal\Core\Database\Database::setActiveConnection('***');
  $db = Drupal\Core\Database\Database::getConnection();
  $query = $db->query("select distinct T1.serialnumber from assets T1 where T1.dbid <> 0 and (T1.manufacturerpartno = :partNumber)", [':partNumber' => $partNumber]);
  $result = $query->fetchAllKeyed(0,0);

  $form['elements']['test']['#element']['out_serial']['#options'] = $result;

  db_set_active();
}
// End of your build or form alter function.

/**
 * Ajax callback of out_part element.
 */
function populateOutSerialNumbers($form, $form_state){
  return $form['elements']['test']['#element']['out_serial'];
}


Alias URL not changing when switching language in a View I have a content node in 2 languages. When I use the language switcher while displaying the English content:

www.example.com/en/content/Article-on-relativity

it displays correctly the translated content in Spanish in this URL

www.example.com/es/content/Articulo-sobre-relatividad

However, when I include the contents filtered in a View, the language switcher only swiths the first part of the URL, but not the alias URL of the content itself, displaying Not Found

www.example.com/en/myView/Article-on-relativity

changes to

www.example.com/es/miVista/Article-on-relativity

instead of the desired

www.example.com/es/miVista/Articulo-sobre-relatividad

Thanks!!!

An alternative would be to use i18n_page_views module - it is a display plugin that installs an item labeled i18n page into the +Add (display) button menu. It's like a page display extended by fields for entering a path for each enabled language.

While it does not offer any tool to convert existing displays into i18_page type, it's quite easy to do that manually - just export your existing view(s), change the type of the display in a notepad and re-import w/override.

Regretfully, the module does not offer UI for creating translated menu items - this also has to be done manually.

At any rate, it's advisable to bind all translation paths (created manually as jdu suggested, or created automatically) into a translation path set (admin/config/regional/i18n_translation/path/add). I found that without it the i18n_get_path_translations function worked whimsically.


Why are there two database tables to handle taxonomy terms structure There is a taxonomy_term_data table and there is a taxonomy_term_hierarchy table.  Why are there 2 tables, instead of them being combined?

taxonomy_term_hierachy strucutre

description of table: Stores the hierarchical relationship between
field: tid: 'Primary Key: the taxonomy_term_data.tid of the term'
field: parent: 'Primary Key: The taxonomy_term_data.tid of the term's parent.
0 indicates no parent.'

taxonomy_term_data structure:

description of table: Stores term information.
fields: vid, name, description, format, weight

Question motivation
I am the maintainer of the draggableviews module.  Currently module is using just 1 table.  Going forward, the module's goal is to mimic taxonomy structure.  Tried to search the web for an answer but could not find one.

taxonomy_term_data is the base table for the taxonomy entity type. It holds ID, property and bundle data for that entity type.

taxonomy_term_hierarchy holds the parent/child relationship between taxonomy terms (which of course can be multiple in nature).

You can't store the data for anything more than a one-to-one relationship in the same table, hence the split into two.


URL paths taxonomyterm/pagename instead of content/pagename I've set up a vocabulary with some terms. I've created some new pages and tagged with the newly created terms. However, the node urls are in the form of content/pagename and I would like them to be taxonomyterm/pagename instead.

What do I need to do in order to get the urls to display in the taxonomyterm/pagename format?

Drupal 7

Under /admin/config/search/path/patterns you can change the default pattern for the content type from content/[node:title] and set the pattern to [node:field-tag]/[node:title]. It is probably a good idea to restrict field_tag to a single value, and to make it required if you are going to use a pattern like this.


Drupal 7 to 8 migration The "taxonomy_term_reference_plain" plugin does not exist When running the d7_field_formatter_settings.yml (in core/modules/field/migrations/) migration I get the following error.

The "taxonomy_term_reference_plain" plugin does not exist

Has the taxonomy_term_reference_plain formatter been removed from Drupal 8?
If so what is the equivalent in drupal 8 and how can I map taxonomy_term_reference_plain into its drupal 8 equivalent during migration

Yes, taxonomy terms are now treated as general entities rather than special (for the most part), so some of the taxonomy-specific formatters were inevitably removed.

I believe the entity_reference_label formatter is the natural replacement for Drupal 8.


Programmatically assign user role I have multiple roles on my website, and I want to assign a certain role to some users when they register to my site.

How can I assign a specific role to new users programmatically when they submit their registration forms?
I have tried modules like logintoboggan, autoassignrole, but they provide a default user role on registration, when I want to assign role to specific users, not to all users signing up on my site.

We also solved this task with the user_multiple_role_edit() function.
In our usecase we didn't react on the register-form but on a special menu-callback to create users on the fly.

First: Create a user

$user = new stdClass();
$user->name = $name;
$user->status = 1;
user_save($user);

Second: Assign the user to the role

$role = user_role_load_by_name("my custom role");
user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);


Metatags for Views page? Possible Duplicate:
  Meta tags on Views in Drupal 7

Tried metatags module, it is great, but can only set meta for Content, Tax, Front, etc, not for Views.

How to set metatags info for Views page? programmatically or by module

Thanks.

You can use
Meta tags quick
The Meta tags quick module allows you to specify Meta tags based on path for your views

Interesting article on Meta tag generation here


Basic page still showing in view that filters out basic page content from view I made a view that is only supposed to show Album, Mixtape, and Artist content types, but the basic page I made called "About Us" is showing up.  I've tried deleting that content and re-making it and then doing the same with the view but it still shows up!

I'm attaching a couple of pictures to show you what I mean.

I never found out why this was happening, but I found a workaround for it.
Add another filter that says content cannot be of type: Basic Page.
It's not pretty and I would prefer to not have to use that and fix the problem instead, but if you're pressed for time this will work.


Create a time span field The date module provides a handy widget for specifying a date.  Is there something similar on Drupal 6 for specifying a length of time such as 6 months or 3 days?  The time span will need to be converted to or stored as seconds for use by my module.

The Interval Field module looks like it would do the trick.

Interval field gives you a simple field and widget to allow users to enter interval values eg

2 months
3 days
4 years


Problem while using the user_reference field in my bundle I am creating an entity for my D7 Module and trying to include a user_reference auto-complete field in it. The autocomplete-field shows up correctly with the add-more option since I have set cardinality to unlimited.

However, nothing shows up in auto-complete suggestions and it doesn't accept any of the user-instances.

Even more annoying is that when I go and check the field settings in
Home » Administration » Structure » Content types » » Manage fields
and click on Save without making any changes, the suggestions start appearing correctly as they should.

I have written down the following settings for the field and the instance.

field :

'vocabulary_authors' => array(
      'field_name' => 'vocabulary_authors',
      'type'        => 'user_reference',
      'settings' => array(
        'referenceable_roles' => array('2','3'),  // for authenticated user + administrator
        'referenceable_status' => array('1'),    // for active
      ),
      'default_widget' => 'user_reference_autocomplete',
      'default_formatter' => 'user_reference_default',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    ),

instance :

'vocabulary_authors' => array(
      'field_name'  => 'vocabulary_authors',
      'label'       => $t(' Authors'),
      'bundle' => 'vocabulary',
      'entity_type' => 'node',
      'description' => '',
      'required'    => FALSE,
      'widget' => array(
        'type'    => 'user_reference_autocomplete',
        'settings' => array(
         'autocomplete_match' => 'starts_with',
        ),
      ),

Please help me out here. I think I am I missing out on some required settings.

You are missing the module definition, though I'm not sure it's required.

The easiest thing to do it so use field_info_field and field_info_instance for the field to see what info Drupal provides and fill in the blanks until every works.


jquery SmartMenus conflict? I believe I've got a jquery conflict, but for the life of me I can't find it.
I admit, I'm not the best with jquery.

I'm using D7 with jquery update (7.x-2.3+6-dev) and I'm trying to get the jquery based SmartMenus to work: http://www.smartmenus.org/

For the most part I've got it installed and working, but the problem I'm having is that the drop down menus will not close when I mouse off them.

The menu can be seen here:
http://www.multibrand.visionmix.us/

I'm not sure what other kind of information to post, so please let me know and I'll add it.
I'd really appreciate any help.

I got it, I was calling a tag not specific enough.

Once I replaced:

$('#mainnav ul.menu').smartmenus();
$('#main-menu').smartmenus('menuHideAll');

with

$('#mainnav ul.menu:first').smartmenus();

Everything was fine.