Why is my site which resides in a subfolder broken when visiting it through a subdomain URL? I have a Drupal 8 website on a server in a subfolder called news so the homepage for this Drupal instance is www.site.com/news. The original www.site.com was not Drupal so this is why this was done. Fast-forward to today, we've redone www.site.com as its own Drupal instance on another server and would like to still use the old news site where it's at. What we've done was create a subdomain of www.news.site.com pointing to the other server so that it could be its own instance, however, when you visit the site from that new subdomain URL, most of the links/images are broken due to it looking for files at /news/filename.jpg or /news/article-title.
What would be the best way to set up either server so that the new subdomain works properly? Should we have set this up another way?
Let me know if any other details are needed and I will happily supply them.

From your description it looks like you need to

add your subdomain to proper site folder. Check your sites.php to be correct, for example-

Check your settings.php to allow your sub-domain as per the documentation-

Check if image urls are hard coded

Cache or CDN plugin are affecting it.

Adding the type of error you are getting could let us help you better.


How to insert block into Article content type? I haven't found any option or module to achieve this yet.

I started to think I should do this by inserting code directly into article, but this would not be really good/easy solution on regular basis, for Adsense for example....

Have you tried Insert Block?

  Sidebar blocks contain all sorts of nifty stuff, but sometimes you
  want to include or embed that stuff into the body of your node.
  Instead of using PHP snippets (a possible security hole on public
  sites), you can use this module. When it's activated...

  [block:name of module=delta of block]

  ...will insert the contents of a rendered sidebar block into the body
  of your node. If no delta is specified, the default block for that
  module will be displayed.

There's only dev releases for this module, but it has almost 6.000 installations.


Why does the EN version of the Main menu not appear on the EN version of my site? I can't see any menu in the EN version of my drupal site with the following settings in my menu :

EN and FR languages installed.
2 Menu's : main menu en (fixed language : en) and main menu fr (fixed language : fr)
I add some menu items in those menu's indeed

When I'm navigating trough FR, all is ok, but when I select EN, nothing appears.

I see in HTML that no menu is shown too (0 div for the menu)...

( I cleared the cache 10 times haha )

Site is available here : http://drupatest.clementhallet.be/en

I'm going crazy about this, any suggestions?

I've been struggling with a similar issue in the past too. Below is how I resolved this for a multilingual site with menus in multiple languages. In this case for the "main menu", but you can do this for any menu.

Step 1

Use a single "main menu" that contains all menu items for all languages, so not 1 main menu for only EN menu items and another main menu for only FR menu items.

Step 2

Configure the multilingual options of the menu via the Menus administration page and follow the "edit menu" link to the menu in question. For the Main menu that would be admin/structure/menu/manage/main-menu/edit.

For "Translation Mode", use the option "Translate and Localize". So that
menu items with language will allow translations, and menu items without language will be localized.

Step 3

Add the links for any of your languages to the single menu, but make sure to specify for each of these links for which specific language you want the link to be shown. Or as an alternative, if you have menu items that should be shown for al languages, make sure such link is marked as "Language Neutral".

Summary

For any language the very only (single) "Main menu" is shown. However based on the selected language, only those menu items in it will be shown that match the selected language. Not sure if it is the best/most elegant way to make this work, but IMHO it works like a charm ...


Find latest Drupal version number I'm trying to find how to get the latest version release -number- of Drupal, not actually download it. I appreciate that I can read the contents of the ftp projects page then selectively pick out latest, but I wondered if there was an easier way of doing it.

The reason I'm looking is for an external (non-drupal) page I'm writing that gives current versions of the server's current drupal installations, and whether they're up to date or need to be upgraded - that's why I don't want to actually do a wget of the tarball.

For Drupal 7, fetch the XML at https://www.drupal.org/node/3060/release/feed?api_version[0]=103 to get the release history. The first item's title contains the latest version.

<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xml:base="https://www.drupal.org/node/3060/release?
    api_version[103]=103" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Releases for Drupal core</title>
    <link>https://www.drupal.org/node/3060/release?api_version[103]=103</link>
    <description></description>
    <language>en</language>
      <item>
    <title>drupal 7.32</title>
    <link>https://www.drupal.org/drupal-7.32-release-notes</link>
    <description>...

If you want information for all major versions (including 8 and 9), you may simply use https://www.drupal.org/node/3060/release/feed. You are then required to go through the items until yo find a release for the major version you are looking for.


Edit tab available to anonymous user on some but not all pages? On a Drupal 6 site that I've inherited, there is a custom content type for staff profiles.  Editing should be limited to two user roles "content creator" and "careers."  This has worked fine for the past 2+ years, but a few weeks ago we noticed that some, but not all, of the individual staff page/nodes are editable buy anonymous users (anyone!).

I've looked at the permissions for this content type as well as for all our user roles-- nothing indicates that this should be possible at all.

The only way I've been able to "fix" this is by recreating the nodes 1-by-1 and deleting the "broken" ones.

I'm particularly curious as to why this only affects some nodes-- I have so far been unable to detect any sort of pattern that connects them.

Any ideas where I should be looking to diagnose this?

We finally found out what was happening.  Drupal was configured so that when an authorized user account was deleted, the owner for all their content was changed to Anonymous.  Modified the setup so that the owner of all "orphaned" pages is set to Admin.


How to debug or explore an unknown object or array too big for Drupal's debug()? I'm trying to see what variables I have available in a $vars object in a Views hook. Unfortunately, like many Drupal object, this one is huge and attempting to output it using the Drupal debug() function (with or without the 3rd boolean argument) causes the server to crash with an out of memory error.

Note that this is after increasing the memory limit quite high, the memory limit isn't the problem here (UPDATE: I later discovered the array output was over 370 megabytes!).

What's the least intensive (fewest contrib modules, patches, custom code, 3rd party libraries etc) way to explore the contents of a Drupal object like this that's too big for Drupal's debug()?

Devel

Devel module provides dd() command which is very useful for dumping very large object. Just run dd($vars) in the middle of code, it'll dump any object to the temporary file in your Drupal temp folder (temporary://drupal_debug.txt).

XDebug

Use XDebug PHP extension, so var_dump() will be replaced by xdebug_var_dump() so your big dump won't consist circular dependencies and would be limited only by specific depth.

Alternatively use TVarDumper, array_slice, serialize or json_encode, so check below for further details:

Using print_r and var_dump with circular reference at SO


How do I use the 'Filebrowser' module? I have installed/enabled the Filebrowser (v 7.24) module and set permissions...

It is said to provide ftp style file browsing capabilities, but I can't find any way of invoking it.

I am used to installing and getting modules working, and I have read the sparse documentation which refers to it as a node, but I can find no way to create a node or navigate to a page that is anything like the screenshot.

There are no new content types, nothing changed on creating new content, nothing new appears under any of the admin menus, appending filebrowser and variations to my site's URL does nothing.

How to open file browsing window?

I could be going blind or it could have been a page refresh that was needed...

You create a new node and select "create a new directory listing"

Really straight-forward...


Different registration procedures (with or without approval) for different roles? I am currently setting up a simple LMS in D8 and would like to create different registration procedures for different kinds of users. In particular:

There should be a registration page for simple member profiles: Only basic user data should be required and the account should be unlocked immediately after registration (and e-mail confirmation).
There should be a second registration page for student profiles: They need to upload a valid student identity card, which is why their registration requires admin approval.

I have already set up different registration profiles/pages for members and students and after registration the correct role is automatically assigned to the new user. So, that is working well already.

However, I need to also set up a different approval process, depending on the registered role and I'm not sure, how to approach this. Note: I really don't want this to be a two-step process, where students register as members first and only then upload the required documents. I need to make this as easy and quick as possible for them, while at the same time allowing for unrestricted member registrations.

Note that I'm working in D8 and I'm hesitant to install the Rules module, as there doesn't seem to be a stable version yet. Or is it usable?

Can this be done? Any help?

So, first of all, I'd like to refer to my other answer here, it's good to take a look

You are going to be needing to separate webforms, each with its own required fields, then after building our webform, in Emails \ Handlers section located at admin/structure/webform/manage/[WebformName]/handlers. We are going to enable our custom webform handler module.

  One thing that you need to make sure is correct, is the structure of
  the module folder, so that webform would read it as a handler, we
  assume the module name here is: webform_handler_user_creation so the
  structure would be something like this:
  webform_handler_user_creation>src>Plugin>WebformHandler>UserCreationHandler.php
  with a webform_handler_user_creation.info.yml file in the root of
  the module directory.

With all that said, here's an example of the module on my github page

So what we need to do first is to make sure we do create our users after saving the webform submission, then load the submission values and use them based on their machine names to fill in our user creation thingy, here's an example code:

<?php
namespace Drupal\webform_handler_user_creation\Plugin\WebformHandler;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;
/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "usercreate",
 *   label = @Translation("User Create"),
 *   category = @Translation("Action"),
 *   description = @Translation("Creates a user after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class UserCreationHandler extends WebformHandlerBase {
  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
        $user = \Drupal\user\Entity\User::create();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $user_name = $webform_submission->getElementData('user_name');
        // Mandatory user creation settings
        $user->enforceIsNew();
        $user->setPassword('testPassword');
        $user->setEmail('test@example.com');
        $user->setUsername($user_name); // This username must be unique and accept only a-Z,0-9, - _ @ .
        $user->set("langcode", $language);
        // Optional settings
        $user->set("init", 'email');
        $user->set("preferred_langcode", $language);
        $user->set("preferred_admin_langcode", $language);
        $user->activate();
        // Add a custom role
        $user->addRole('CustomRoleName');
        //Save user
        $user->save();

  }
}

So based on your use case, you can add the user with a custom role with $user->addRole('CustomRoleName'); and maybe activate it with $user->activate(); it or a lot other things. You will be needing two different handlers/module with different concept for each role, one for simple member profiles and one for student profiles


Why is loading a field value from a group of nodes taking 30 seconds plus? I have a D7 site with around 300,000 nodes. I am passing this function an array of 300-500 nids. Sometimes the function runs in under a second. Sometimes it takes 40 seconds or more! I can't figure out what causes the slow runs. How can I get the query consistent and fast?

function _load_field_values_for_nids($field_name, $nids)
{
  $field_info = field_info_field($field_name);
  $field_id = $field_info['id'];

  $map = array();
  $nodes_without_required_field = [];

  // Load up the properties from the node table.
  $sql = 'SELECT * FROM {node} WHERE nid IN (:nids)';
  $nodes = db_query($sql, array(':nids' => $nids))->fetchAllAssoc('nid');

  // Attach the single field to all nodes.
  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT, array('field_id' => $field_id));

  foreach ($nodes as $nid => $node) {

    if (isset($node->{$field_name}['und'])) {
      $map[$node->nid] = $node->{$field_name}['und'][0]['value'];
    } else {
      $nodes_without_required_field[] = $node->nid;
    }
  }

  $absent_count = count($nodes_without_required_field);
  if ($absent_count > 0) {
    watchdog("vwyw_load_fields", $absent_count." nodes did not have field, \"".$field_name."\" ");
  }

  return $map;
}

I noticed this SIX-SECOND query on the main /admin/content page (which took 12+seconds to load):

Here is the expanded XHProf output regarding that Count query:

I think this might be a mysql configuration issue rather that the particulars of a query. For instance, I think this query should run very quickly but it takes a second and a half:

The next time (same page load) it took 120ms and the time after that, 4.8sec!

UPDATE

Here is the XHProf output sorted by duration for a simple admin page that calls the function:

I'm guessing that the difference between the fast runs and the slow runs is caching. Within field_attach_load is a call to cache_get_multiple(). The field values can load from a cache which should be a lot faster: https://api.drupal.org/api/drupal/modules!field!field.attach.inc/function/field_attach_load/7

To investigate further I recommend using devel module's query logger. It can show the amount of time spent within queries. If that is not sufficient you can use a profiler like XHProf or Blackfire to see exactly which function calls are taking the most time.


List content referenced to another content type I'm creating a simple site which has shows and episodes. I have created both content types and I added the entity reference field to the episode type. The episode would reference a show which it belongs to. I have a view which lists all the shows. However, when I click a show I want a list of all the episodes belonging to that show.

How would I achieve this?

You can create a view that lists episodes that references the show. This is done using the module Views.

Go to admin/structure/views/add and add a view, call it episodes and create a block display.

Create a new view and a relationship, the label will be "Entity Reference: Referencing entity" and as description you will see "A bridge to the Content entity that is referencing Content via field_YOURFIELD".

Then add a contextual filter called "Content: Nid". In the settings for the filter look for "When the filter value is NOT available" and choose "Provide default value" and choose "Content ID from URL".

Your settings will look something like this (I removed the second column to make the image smaller).

Now go to admin/structure/block and place the block you created (if named the same as my example it will be called "View: episodes") and place it in the region you want it to show.


Organic Groups strict membership access I have set up multiple organic groups on my site that can only be joined with admin approval.

My issue now is that members can post content in groups of which they are not members. I really don't want this.

Does anyone know of a module or technique to stop unauthorized members from posting content in a group but only in groups they are members of and hence authorized to do so?

You need to enable Organic groups access control module. This will let you set your groups to public/private.

There is a tutorial series on Organic Groups which explains everything you need to know about the configuration at http://modulesunraveled.com/organic-groups


Change Form Single Select element to Multi Select for JS enabled users I would like to have an exposed filter that shows single select by default, but for JS users is able to be altered to a multi-select.

The reason for this is that I want to apply the JQuery plugin Chosen onto my multi-select elements. However showing the pure multi-select element in the same block space on the page will be both unsightly and unwieldy for non-JS users, so I'd prefer they fell back to a single-select drop down menu.

I guess I can easily change a single select to a multi-select using JQuery, however is this going to prevent Drupal from accepting multiple values since the form element will only be expecting a single value for that single-select element?

Thank!

Looks like someone made a module for this: http://drupal.org/project/chosen, maybe he can provides some support for views.

Some details from the module's project page:

  Chosen uses the Chosen jQuery plugin to make your <select> elements more user-friendly.


Alter html output of a term reference form field On my node edit form a term reference field is rendered with the following html output:

  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="12" class="form-radio">
  External

As you can see the value attribute is set to 12 which is the term id of that particular item. Now I would like to replace 12 with the term name, External.

So it would look like:

  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="External" class="form-radio">
  External

I am unsure which function to use to target this particular field.
I was looking at theme_checkbox() and theme_form_element() but I am uncertain how to proceed and if these are the right functions for the job.

UPDATE:
So I would like to show another field based on the option chosen for the field_trainingstype. In a hook_form_alter I am now doing this:

$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => '12'),
  ),
);

But I would like to trigger this by term name External because the term id might differ per environment.

Doing it that way round will cause problems with the form submission; the value for a term reference field needs to be an integer and throwing a string at it will undoubtedly upset things. You could massage values back into place in a validate function but it seems a bit...messy.

The alternative would be to load the taxonomy term up in the form, so you can use the ID from there:

$terms = taxonomy_get_term_by_name('External', 'vocab_machine_name');
$term = array_shift($terms);
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => $term->tid),
  ),
);

That should make it reusable across different environments (provided the vocab only has one term with the name "External").


Nesting Navigation Tabs In my custom module, I'm defining a menu_item with the type MENU_NORMAL_ITEM. In the default bartik theme, this adds a new navigation tab (next to the Home tab). This is great; however, I need nested tabs as well! Something like the following:

Home (default tab on Bartik)

Menu Navigation Item added via custom module

Nested Friend

With a structure similar to this, my frontend guys can theme around this and make a dropdown out of it. I've tried this:

$items['custom tab'] = array...
$items['custom tab/sub-item'] = array...

But there's no luck, and it's not even rendered when I clear my caches and do na inspect element, so I know it's not hidden or anything. I think I'm attempting to define a parent/child relationship purely through PHP. Any tips?

You need to change the type for submenu.

 $items['custom tab'] = array(
    'type' => MENU_NORMAL_ITEM,,
);
 $items['custom tab/sub-item'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
);


How to import custom content type in XML? I have installed the newest Drupal 7.12 and need to import custom content type data exported from custom CMS but ... don't know what is the correct XML structure.

1) I have added <MY_CUSTOM_CONTENT_TYPE> into Structure
- added about 20 fields

2) prepare Import feed

Attach to content type: Use standalone form
Fetcher: file upload
Parser: Sitemap parser - Parse Sitemap XML format feeds.
Processor: Node processor
Node processor settings: Text format: plain text; Content type: <MY_CUSTOM_CONTENT_TYPE>

3) I have exported XML file with content (probably with the wrong XML structure)

<?xml version="1.0" encoding="UTF-8"?>
<articles>
<article type="MY_CUSTOM_CONTENT_TYPE">
     <title>1234</title>
     <custom_1>1234</custom_1>
     <custom_2>abcd</custom_2>
     ...
     <custom_20>...20...</custom_20>
</article>
</articles>

3) after loading XML file getting "There are no new nodes."

I can prepare XML structure when exporting content, but want to know how to do it.

In my case an error "There are no new nodes" was caused by a wrong xml context in the xpath parser setting.

In your case should be: //article and not only: article.

This is because //article in xpath is equivalent to say "all the article tags".
If you put only article in the xpath, context feeds does not import anything.


Search nodes and taxonomy terms I need to implement functionality for search nodes and taxonomy terms through one search form and display results in one listing.

I try to use these modules:
1. Apache Solr
2. Search API
3. Search API Solr Search
4. Search API multi-index searches
5. Search_api_views

I can't make apache solr module add taxonomy terms into index.
It's possible? What I do wrong?
Now my apache solr index only nodes.

I configure apachesolr module http://i.imgur.com/V1OYd.png
Also I configure Search API http://i.imgur.com/qeAvs.png

Any help is appreciated

I do face similar situation and I am trying with http://drupal.org/project/apachesolr_term module.

  This module provides basic indexing of the taxonomy terms for the
  multi entity branch of the Apache Solr Search Integration Module

I will post back my findings soon.


db_query() PDOException (no parameters were bound) I have a relatively simple query that is executed via db_query()->execute;
For some reason this causes a PDO Error, which I assume has to do with the way drupal handles the input. Any ideas on what causes this error and how to avoid it?

db_query('
    INSERT INTO {account_floodprotect} (ipaddress, soapcount, mailcount)
    VALUES (:ipaddress, :soapcount, :mailcount)
    ON DUPLICATE KEY UPDATE
    soapcount = soapcount + :soapcount,
    mailcount = mailcount + :mailcount',
  array(
    ':ipaddress' => $ip,
    ':soapcount' => $soapcount,
    ':mailcount' => $mailcount,
  ))->execute();

/*

ERROR CAUSED:

PDOException: SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

The table involved:

+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| ipaddress  | varchar(255)     | NO   | UNI |         |                |
| soapcount  | int(10) unsigned | YES  |     | 0       |                |
| mailcount  | int(10) unsigned | YES  |     | 0       |                |
| updatetime | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+

Don't need execute()，

db_query('
    INSERT INTO {account_floodprotect} (ipaddress, soapcount, mailcount)
    VALUES (:ipaddress, :soapcount, :mailcount)
    ON DUPLICATE KEY UPDATE
    soapcount = soapcount + :soapcount,
    mailcount = mailcount + :mailcount',
  array(
    ':ipaddress' => $ip,
    ':soapcount' => $soapcount,
    ':mailcount' => $mailcount,
  ));


How can we achieve multiple forms in a single page? I have menu callback which is getting called multiple times on the same page by an AJAX request resulting rendering the form with same HTML id

$items['mymodule/page'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('page_callback_form'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

function page_callback_form($form, &$form_state, $thing) {
  $form['message'] = array(
    '#type' => 'textarea',
    '#title' => t('Message'),
    '#cols' => 80,
    '#rows' => 5,
  );
  return $form;
}

Result:  <textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>
<textarea id="edit-message" name="message" cols="80" rows="5" class="form-textarea"></textarea>

i was wondering is there a way i can have unique Ids, i have tried [hook_forms].1

You can do it!
With the drupal fapi. You can overload every HTML attributes by using the element #attributes.
Exemple:

  $form['form_element'] = array(
    '#type' => 'textfield',
    '#title' => t('If you Have a Code, Redeem it here:'),
    '#attributes' => array(
      'id' => 'your_id',
    ),
  );

If you add a counter or something to your id, you will have a different id for each fields.
Cheers


How to link taxonomy and views in a succinct way? So here is my use case: I have taxonomy vocabularies titled accommodation, and in the vocabulary, there are 4 terms.

hotel
motel
campground
guest housing

I want to create a view that displays in a page that has these four terms as menu links that once you click the link all content nodes containing that taxonomy term are listed. I have been struggling with this.

My main Block is creating a menu from taxonomy and linking it to the view(I would like to use a custom URL), I have tried the Taxonomy Menu module, which is close, but cannot figure how to configure it correctly, I have gotten closest creating an attachment display within the view. I am so close.

Forget views here and write a few lines of own code here. I had this problem also recently. Views is much to unflexible. You must do the following:

Create a route to your controller method
Get all relevant nodes in the method
Create a template via hook_theme() for the output.
Realize all your details! ;)

I needed around ~1 hour for this.


Wrapping a block in jQuery Accordion Problem

I'm creating a search page for a module. On that page I have an exposed views filter block and I'd like to put it into a jQuery accordion.

In case it's relelvant: In the same sidebar below the filter block I have a series of facets which use the Facet API Collapsible Module.

At the moment I've put the script "facetaccordians.js" in mytheme/js/ and added it using the .info file.

What I've tried so far

Here is the .js file.

(function ($) {
        $(function() {
               $(document).ready(function(){
                    $(".views-exposed-form").accordion();
                });
            });
})(jQuery);

This selects the following horrible bit of HTML:

But the accordion doesn't work correctly. It doesn't open and close.

I tried adding in
Test
 into the tpl.php for views exposed forms to give this:

However it still doesn't work. And that will cause me a bunch of other problems. What's the correct way to put this block into an accordian? OR what am I doing wrong? Do I need to select a div above the current ones, do I need different HTML?

(I know about the Accordian Blocks module, but it doesn't work either. The open close also doesn't work)

Easy Solution 1

As it turns out the accordion blocks does work. However if you're just using it for a single block it won't automatically because the default jQuery accordion only works with multiple objects.

Install Accordion blocks and open the accordion_init.js file. It'll look like this

(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, });
      }
  };
})(jQuery);

You need to add the property, collapsible: true, as shown below. I've also removed the animation and made it start closed by default.

(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, collapsible: true, active: false, animated: false});
      }
  };
})(jQuery);

Possible Other Avenue

I also managed to get jQuery accordions working, it has to have a certain HTML structure (see the UI documentation) which is difficult to implement around blocks thus why I took the easy route.

But if you fancy trying it the following code will enable jQuery accordions on your website for your theme at a basic level. This code goes into the template file.

function themename_preprocess_page (&$vars) {
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion({ collapsible: true, active: false, header: "h3", animated: false});});', 'inline');
}


How can I auto-rotate an image on file upload in a custom form? I'm using the FAPI to provide the user an upload field for an image.  The field is:
$form['product_img'] = [
  '#type' => 'managed_file',
  '#description' => 'Upload a PNG or JPG image of the product.',
  '#multiple' => FALSE,
  '#required' => TRUE,
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_is_img' => [],
    'file_validate_extensions' => ['png jpg jpeg']
  ]
];

A lot of the users are uploading images taken with their mobile device, resulting in the image in landscape.
The solutions I've seen involve the default file upload widget, but I need something that will automatically rotate the image after the upload.

you can try the next code. You will have to create a new image style which rotates the image and then use it in prerendering on image preview.
$form['product_img'] = [
  '#type' => 'managed_file',
  '#description' => 'Upload a PNG or JPG image of the product.',
  '#multiple' => FALSE,
  '#required' => TRUE,
  '#upload_location' => 'public://',
  '#upload_validators' => [
    'file_validate_is_img' => [],
    'file_validate_extensions' => ['png jpg jpeg']
  ],
  '#process' => array('custom_managed_file_element_process'),
];

// Process callback

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

  $element = file_managed_file_process($element, $form_state, $form);

  $element['#pre_render'][] = 'custom_managed_file_element_preview';

  return $element;
}

function custom_managed_file_element_preview(array $element) {

  if (empty($element['#file'])) {
    hide($element['remove_button']);
  }
  else {

    $file = $element['#file'];
    hide($element['upload']);
    hide($element['upload_button']);

      $info = image_get_info($file->uri);
      $variables = [
        'alt' => $file->filename,
        'path' => $file->uri,
        'style_name' => 'thumbnail', // change your style name here
        'attributes' => [
          'class' => ['upload-preview'],
        ],
      ];

      if (is_array($info)) {
        $variables += $info;
      }

      $element['preview'] = [
        '#type' => 'markup',
        '#weight' => -150,
        '#markup' => theme('image_style', $variables)
      ];

  }

  return $element;

}


How to make scheduled Feeds importers run consecutively? I have two Feeds importers that need to run in a specific order. For example:

1) Importer 'Films' imports all the films showing at a cinema, creating 'film' nodes.

2) Importer 'Showtimes' imports the show times for each film, creating 'showtime' nodes.

Both importers are scheduled to run every day. 'Showtimes' must always run after 'Films' is fully imported, as it creates node references to film nodes.

Things I have tried:

Using Rules instead of Job Scheduler. I created a custom rules action using this code:

while (FEEDS_BATCH_COMPLETE != feeds_source('my_importer_id', $node->nid)->import());

I created a rule that triggers on cron with two actions: import films, import showtimes. This kind of works but when I look at the newly created nodes, showtime nodes are being generated before all the film nodes are created. So I guess rules actions aren't processed sequentially...?

Using Feeds Rules to chain one import onto another. Feeds Rules provides a 'after Feeds import' rules event.

So I tried creating a rule that triggers 'showtimes' importer (using my custom action above) after 'films' importer has run. But I ran into a problem applying a condition on the rule provided by the module. I'm not convinced this is the best method anyway.

Thanks

You've entered that territory where you would be better served by a custom module than trying to force Rules to do what you want.

If I were posed with this problem I would do the following:

Create two CRON jobs one for each of the importers in a new module. See hook_cron().
Turn off all of Feeds default importing for those feeds.
Install Elysia Cron.
Schedule your cron jobs with Elysia to run at appropriate intervals leaving enough
time for the first to complete before running the second.
For extra credit you could programatically check that the first import is
complete before allowing the second to run.


Is a content type or profile a better choice? I am working on a new site where I want to show information for art galleries, artists, museums, public art installations and art education.

I understand both the content type and profile differences but can't decide which is better in the long run. I know the artists will need a profile and I would like to give the rest of the "types" the ability to edit their own content if they desire.

I have done a lot of research and can't seem to find an answer on how to link a content type entry with a user profile and am leaning toward profiles for everybody. However, this has drawbacks because of need for authentication info (which I don't know) as I create the profile.

Am I missing a magic module or some other clue?

You can use a profile, or a content type to expose information about a person. The difference between them is that a profile is always about an existing user account on the site.
For example, if your site is about emergent artists that will have a user account on your site, then a profile can be used from those artists to expose information about themselves. If your site is about famous past artists, then a content type can be used to expose information about them.

The other difference is that profiles are usually created from the users who want to add information to their own account. (The other alternative could be a user with the permission to administer users that adds a profile for another user.)
With nodes, out of the box, it's more difficult to limit who can create a node associated to the account of another user.

As for linking content types to a user profile, it is possible to use the Views module to show a page that, for example, on user/%user/profile shows those specific nodes that contain information about a user.


How to make all render caches update on a configuration override? Short version:

I am using a configuration override to override the site name. Changes are reflected in the HTML title, but not in the system branding block. Drupal keeps serving this block from the render cache.

Long version:

I am using a configuration override service that implements ConfigFactoryOverrideInterface, which overrides configs on demand. Slightly simplified, it looks like this:

class MyConfigOverride implements ConfigFactoryOverrideInterface {

  /**
   * {@inheritdoc}
   */
  public function loadOverrides($names) {
    $overrides = [];

    if ($override_required) {
      if (in_array('system.site', $names)) {
        $overrides['system.site']['name'] = 'My name';
      }
    }
    return $overrides;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheSuffix() {
    return 'MyConfigOverride';
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();

    if ($name === 'system.site') {
      $my_entity = MyEntity::Load(1);
      if ($override_required && !empty($my_entity)) {
        // Append entity cache metadata (cache tags and context).
        $metadata->addCacheableDependency($my_entity);
      }
    }
    return $metadata;
  }

  /**
   * {@inheritdoc}
   */
  public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
    return NULL;
  }

}

However, as soon as this override kicks in, the render cache for the System branding block does not get updated with the new site name. This is because the SystemBrandingBlock class does implement getCacheTags() in which it merges the system.site cache tags (see below), but it does not implement getCacheContexts() (which my module uses since I serve a variation of the page).

/**
 * {@inheritdoc}
 */
public function getCacheTags() {
  return Cache::mergeTags(
    parent::getCacheTags(),
    $this->configFactory->get('system.site')->getCacheTags()
  );

}

I have tried to overcome this by adding additional 'empty' cache metadata to my class for the cases where the override does not apply.

  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata($name) {
    $metadata = new CacheableMetadata();

    if ($name === 'system.site') {
      $my_entity = MyEntity::Load(1);
      if ($override_required && !empty($my_entity)) {
        // Append entity cache metadata.
        $metadata->addCacheableDependency($my_entity);
      }
      else {
        // Append 'empty' cache metadata.
        $metadata->addCacheContexts(['mycachecontext']);
        $metadata->addCacheTags(['myentity', 'myentity:0']);
      }
    }
    return $metadata;
  }

Since the block does not inherit the cache contexts of system.site and I do not update or otherwise invalidate any of the provided cache tags ('myentity', 'myentity:0'), the render cache still persists. I can append cache context to the system branding block in a hook_block_build_BASE_BLOCK_ID_alter implementation, but I'd prefer not to implement such specific exceptions as they will never cover all situations.

I am somewhat hoping for a hook to update all renderable elements (blocks?) and append cache contexts to those that inherit cache tags provided by system.site. But I am open to alternative solutions as well.

How can I make any block or other entity in the render cache, that is depending on the system.site config aware of the config override?

In the meantime I have come up with this approach, but I am still open to other solutions.

I have found a solution in a pre_render callback for the blocks, by deconstruction the cacheable metadata, searching it for a system.site tag and append my own context and tags (if required).

/**
 * Implements hook_block_view_alter().
 */
functionmymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  $build['#pre_render'][] = 'mymodule_block_view_pre_render';
}

/**
 * #pre_render callback: Sets my module cache tags.
 */
function mymodule_block_view_pre_render(array $build) {
  $cacheable_metadata = CacheableMetadata::createFromRenderArray($build);
  $tags = $cacheable_metadata->getCacheTags();

  if (in_array('config:system.site', $tags)) {
    // Always add a cache context, so we have a variant without overrides as well.
    $cacheable_metadata->addCacheContexts(['mycontext']);

    if ($entity = MyEntity::Load(1)) {
      $cacheable_metadata->addCacheableDependency($entity );
    }
  }

  $cacheable_metadata->applyTo($build);

  return $build;
}


how to prevent node revision update when node is updated? I noticed that every time a node is updated, a timestamp column in node_revisions table is also updated for this node. I would like to change this behavior for "forum" content type and disable updating of the revisions table when forum node is edited. I don't use any modules that impact revisions. How do I achieve it (probably via my own custom module?)

[Edit]

The suggested duplicate  solution ("How to disable the revision feature completely?" ) is quite a big thing. I don't want to disable revisions functionality so deeply, only in particular "forum" node type case and only prevent timestamp change, nothing else. The reason I need this is that the advanced forum module sorts topics by revision timestamp. There is a question how to change this behavior, but there is no answer, so it may be difficult and I also tried to figure it out myself but was lost - this module uses views handlers etc in code, hard to change anything.

I will try maybe to write a hook mymodule_node_save or mymodule_node_insert which is called after the revision table update (as visible in node_save function) and then just reverse this timestamp column back to node creation timestamp.

If it doesn't work then I'll try to deal with the node_save overwriting.

@camcam, have in mind that even when you are not using revisions (keeping separate node revisions for each update you make to your node content), the revisions table will still always have one record in the node_revisions table associated for each record in the node table that it keeps track of.

On the other hand, if you have enabled revisioning, you will have multiple entries in your node_revision table associated with each node, corresponding, not just to the current revision, but all past revisions too.

My suggestion is to make sure you really want to mess with that functionality before you go ahead and do anything - because what you're seeing is actually standard behavior.  :-)

If you look at the code in node_save, you can see that a revision is created or updated in each instance of a node_save() call.

If this really doesn't work for you, I'd suggest using the hook_form() function to edit which function is called when your specific node content type is saved, and you can choose not to call the standard node_save() function (this should only be done if really necessary).  The api documentation, along with some code samples in the comments, can be found here: https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_form/7.


The missing modules don't get installed after updating with Composer To update a site locally, I cloned the code base with git to my local computer and imported the database, then ran "composer update --with-dependencies", there were no errors, then I went to /web directory and ran "drush updb -y", it showed me 8 missing modules:

The following module is missing from the file system: add_to_head    [warning]
bootstrap.inc:276
The following module is missing from the file system: context        [warning]
bootstrap.inc:276
The following module is missing from the file system: context_ui     [warning]
bootstrap.inc:276
The following module is missing from the file system: libraries      [warning]
bootstrap.inc:276
The following module is missing from the file system: menu_target    [warning]
bootstrap.inc:276
The following module is missing from the file system: panelizer      [warning]
bootstrap.inc:276
The following module is missing from the file system: phpmailer      [warning]
bootstrap.inc:276
The following module is missing from the file system: site_verify    [warning]
bootstrap.inc:276
The following module is missing from the file system:                [warning]
special_menu_items bootstrap.inc:276
No database updates required                                         [success]

I tried to log in to the local site, but first ran "drush pm-uninstall captcha", but the site returned the white screen and:

  "The website encountered an unexpected error. Please try again later."

I thought that the problem was due to the missing modules and started running "composer require" for each of them.
But they either didn't get installed or returned:

 Using version ^3.0@beta for drupal/phpmailer
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 1 update, 0 removals
  - Updating drupal/phpmailer (dev-3.x 950f2af => 3.0.0-beta2):     Update failed (The .git directory is missing from web/modules/contrib/phpmailer, see https://getcomposer.org/commit-deps for more information)
    Would you like to try reinstalling the package instead [yes]? yes
  - Removing drupal/phpmailer (dev-3.x)
  - Installing drupal/phpmailer (3.0.0-beta2): Cloning 8.x-3.0-beta2 from cache
Writing lock file
Generating autoload files
> DrupalProject\composer\ScriptHandler::createRequiredFiles

I don't what else to do. Is the "unexpected error" caused by those missing modules? What should I do to fix it?

UPDATE:
I looked at /admin/reports/dblog and here's the php error I saw:

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route ""
  does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()
  (line 201 of
  /sites/bak/web/core/lib/Drupal/Core/Routing/RouteProvider.php).

Remove your Composer lock file and run following command in sequence:

composer clear-cache
composer install
composer require Drupal/module


How to allow special character in username? Is there any way to allow the special character in username like "#" and "~"?

You have to override the defualt user_validate_name($name) :

Verify the syntax of the given name.

To do that, define your username validation code in your custom module

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['#validate'] = array();
    $form['#validate'][] = 'registration_username_validate';

  }
}

And inside registration_username_validate function do your logic to allow your special characters.

Care about security issues caused by allowing special chars in username and about display issues not sanitized usernames may cause in themes.


Get taxonomy name instead of id I set up a search criteria using taxonomy terms to filter content. The taxonomy and filter work great. The problem is the links return like www.example.com/work?tid=1 but instead I would like the filter links to use the taxonomy term name like www.example.com/work/logo. I have tired to set a alias on the terms but it keeps referring to the tid. The has taxonomy option only allows you to change the name of the identifier before the ? But the link still shows the =1 id after the identifier.

you can use Pathauto contrib module.

  The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.

https://www.drupal.org/project/pathauto


Getting field label with entity_metadata_wrapper Say I am iterating through a list of field names, and I have loaded a particular node using entity_metadata_wrapper().

$wrapper = entity_metadata_wrapper('node', $node);

Shouldn't I be able to just grab the label by using the following command?

Or is this not the correct command to do what I want?

        foreach($field_names as $item)
        {
           $label = $wrapper->$item->label();
        }

Here's the field as it is in the actual node:

'field_grade_comment' =>
    array (size=13)
      'default_value' => null
      'description' => string '' (length=0)
      'display' =>
        array (size=4)
          'default' =>
            array (size=5)
              ...
          'email' =>
            array (size=5)
              ...
          'teaser' =>
            array (size=4)
              ...
          'node_reference_embedded_view' =>
            array (size=4)
              ...
      'label' => string 'Grade Comment' (length=13)

How about this?

$wrapper = entity_metadata_wrapper('node', $node);
$fields = $wrapper->getPropertyInfo();

foreach($fields as $field => $info) {
  $label = $info['label'];
}


How to give meaningful id names to blocks? Instead of styling with ids/classes such as block-block-3 which may be deleted and then recreated, how would I go about giving my blocks meaningful names?

Use the block class module. Block Class allows users to add classes to any block through the block's configuration interface.


How to add destination parameter in hook url_inbound_alter Hi I have used  hook_url_inbound_alter to alter the URL. When I access user/%/order anonymously it should redirect ti user/login. I have used below code

 function module_url_inbound_alter(&$path, $original_path,
 $path_language) {
  $argument = explode('/', $path);
  if (!user_is_logged_in() && isset($argument[0]) && $argument[0] == 'user' && isset($argument[2]) && $argument[2] == 'orders') {
      $path = 'user/login';

   }
}

It redirects the user to login page but my question is how to add destination parameter. Above code redirects localhost/drupal/user/login
but I want to add destination paramater such as localhost/drupal/user/login?destination=user/1/order

When I tried to  add the desination variable in $path variable

  $path = '/user/login?destination=user/1/order;

I am getting the url like this

  http://localhost/drupal/user/login%3Fdestination%3Duser/1/order

Instead it should be like this.

  http://dt.drop/user/login?destination=user/1/order

How can I achieve this.

For your particular problem (redirect an anonymous user to user/login), it can be better to redirect on form submit. So, on hook form_submit() you check whether user_is_logged_in(), if not drupal_goto('user/login').


How to show logout link in drupal I have created a user account. Then signed out of admin and logged in with the new user account. But the new account does not have a logout link, So how can i show it to the other users ?

Create a link to user/logout. It can be a menu item or an HTML link in a block.


How to get a machine name of a custom block I have a custom "Slider Items" field type, as well as the custom "Channel Slider Block Type" type block (created using "Custom block library").

Also, I have several "Channel Slider Block Type" blocks.  I need to somehow determine the machine name of a block that this field displays in @FieldFormatter of my field. How can this be implemented? Perhaps there is a special service for this?

/**
 * @FieldFormatter(
 *   id = "channel_slider_formatter",
 *   label = @Translation("Channel Slider Formatter"),
 *   field_types = {
 *     "channel_slider"
 *   }
 * )
 */
class ChannelSliderFormatter extends FormatterBase {

  public function viewElements(FieldItemListInterface $items, $langcode) {
    // Here I need to get a block that reflects this field.
    $blockMachineName = '...';
    ...
    return [
      '#theme' => 'channel_slider',
      '#items' => $itemsData,
    ];
  }

}

A custom content block has no unique machine name, only a bundle type, an UUID and an ID. Only custom content blocks placed in a region have a machine name, but this is NOT the machine name of the block, it is the machine name of the block placement (configuration)


Make user logged in after created by rule I have an entityform on my Drupal website, which helps me to generate leads. I've configured a rule, creates a new user by that entityform's e-mail and name fields. (Similar scenario is told here.)

I need that user (created by rule) to be logged in, after creation. What should I do?

Have a look at the Logintoboggan module. This offers you to login new users immediately.

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

1.Allow users to login using either their username OR their e-mail address.

2.Allow users to login immediately.

3.Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

4.The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a
separate page, but returns the user to their original page upon login.

5.Customize the registration form with two e-mail fields to ensure accuracy.

6.Optionally redirect the user to a specific page when using the 'immediate login' feature.

7.Optionally redirect the user to a specific page upon validation of their e-mail address.

8.Optionally display a user message indicating a successful login.

9.Optionally combine both the login and registration form on one page.

10.Optionally have unvalidated users purged from the system at a pre-defined interval
(please read the CAVEATS section of INSTALL.txt for important information on 12.configuring this feature!).

11.Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)


Move title of a specific node What I want to do is remove the title of a specific content type from where it normally shows throughout the site and print it somewhere else in the template.

I have a custom node.tpl.php for the content type, lets call it node--custom-content-type.tpl.php and it sits within a little submodule I made for this content type and section on the website. Let's call that mycustom_subtheme. I have also created a custom page.tpl.php, page--custom-content-type.php.

I was able to successfully re-print the title later on in the template, thanks to Aram's explanation here, by putting <?php print $title; ?> after <?php print render($content); ?>. I'm looking to find a way to remove it from it's original section just for this content type; See screenshot below.

Things I've tried:

I tried the Exclude Node Title module, but as I feared, it actually renders the title null, which isn't suitable for my purpose of retaining the title but just moving it. For this reason, this post isn't what I need.
I tried hide($content['title']); and hide($title); just to see if that would work in node--custom-content-type.tpl.php.
I tried moving the $title data to something like $title2 and then replacing $title with "Custom Text" but am not sophisticated enough to pull that off.
I tried adding custom CSS to no avail (the title is H2 in my node template): body.node-type-custom-content-type h2.title, {display: none;}
And finally, I even tried all the suggestions here. At the very least, copying the page.tpl.php and removing the title should have worked.

Here is a pastebin of my codes: custom node template and custom page template

Does the original node.tpl.php inherit the title anyway if node--custom-content-type.tpl.php simply doesn't mention it?

I managed to get this to work but welcome better options. I prefer not to alter the theme, but rather use a function or something else instead so that this module can stand alone and not be affected by themes and subthemes and other design team changes.

Here's what I did:

body.node-type-answers-question .page-title {
  visibility:hidden;
}

The source code of the loaded page, which is from a node content type called answers-question. I noticed that there was a "page-title" class in the h1 title. Making the visibility hidden worked for me.


How to generate stats or reports for multi-sites? We've a large deployment of multi-sites, each site with its own database, and I am looking at generating reports from these sites and making those available online in some format.

For e.g., our sites implement many redirects. I want to be able to pull a report on what redirects are in use by which site. I can readily do this via drush and shell scripts, but it would be nice to have a "stats site" to do the generating of these kinds of reports for all sites in a multi-site setup.

Here's how I do this:

I created a "meta" site and database in the system where I added a new table called "databases".  In that table I store the access info of all the DBs in the system.

Then loading an array from a query to that table, query the other DBs individually using the methods outlined here:
http://drupal.org/node/18429


How to investigate (and get control over) the execution order of 3 Rules working on the same action? I have three Rules to do something after saving content. I need to know which one is executed first and how I can control this order?

Is there a certain answer for this question?

It's based on the weight. Edit the  Rule settings and you'll find a drop down to set the weight. I believe those with a lighter weight, e.g. -1, are  executed before those with heavier weight, e.g. 5.


Alter all Webform's form with hook_form_BASE_FORM_ID_alter What is the base form_id for Webform's forms to use in hook_form_BASE_FORM_ID_alter()?

My website will have lots of Webforms and I'm looking the proper way to alter this huge amount of forms.

the base form is webform_client_form and hook look like

  HOOK_form_webform_client_form_alter

or if using HOOK_form_alter we need statement as

if (strstr($form_id, 'webform_client_form_')) {
  //our code for all webforms
}


Drupal 6.19 - cannot add node links to primary-links I have a problem that is driving me crazy. I've been trying to solve it for a week now without luck.
The problem is, I can't add any internal (node/xxx) links to primary-links. After I add one, it appears, but I cannot edit or add any nodes until I delete that menu item. If I try to edit a node, i get the message "username admin does not exist". It looks like this triggers an effect that is causing admin user to lose permisson for node_access. After I delete the created menu item, everything is back to normal... until I add another menu item.

Here's a summary:

I can add external links to primary-links, no problem
I can add internal links to seconday-links, no problem
It doesn't matter if I add the menu item manually or by specifying one on the node edit page, the effect is the same
The language, weight and position of the menu item doesn't matter, as long as I add an internal link to primary-links, the above problem appears
I tried to rebuild the menu, disable modules, clear the cache, rebuild permissions, no luck
I double checked the menu_links table, there were some orphan items (had no parents) which I deleted, but otherwise everything is fine

I am using Drupal 6.19 with only one user (the admin), a bunch of modules and 11 languages. I must solve this problem soon as we need to add another language and it'll definately need some internal links in the menu.

Edit: Here are the modules currently enabled:

CCK

Content   6.x-2.8
Content Copy  6.x-2.8
FileField 6.x-3.7
FileField Sources 6.x-1.2
Node Reference    6.x-2.8
Number    6.x-2.8
Option Widgets    6.x-2.8
Text  6.x-2.8

Location

IP to Locale  6.x-1.0-rc1
Smart IP  6.x-1.3

Meta tags

Nodewords 6.x-1.11
Nodewords - basic meta tags   6.x-1.11

Multilanguage

Block translation 6.x-1.7
CCK translation   6.x-1.7
Content type translation  6.x-1.7
Internationalization  6.x-1.7
Menu translation  6.x-1.7
String translation    6.x-1.7

Other

Custom Page   6.x-1.17
Custom Page Admin UI  6.x-1.17
GeoIP 6.x-1.4
Global Redirect   6.x-1.2
Menu attributes   6.x-2.0-beta1
Menu breadcrumb   6.x-1.3
Page Title    6.x-2.3
Path redirect 6.x-1.0-rc2
Token 6.x-1.15
Webform   6.x-3.14

I can provide any information if you can help, just ask!

Thanks in advance

Issue solved.

Looks like that with the large menu tree, Mysql packet size was exceeded.

I just added the following to mysql config (my.ini) and the issue resolved:

[mysqld]
max_allowed_packet = 16M


How to get a text field with each radio input in cck I want to have a text field input in front of every radio input so, that when a user selects a radio input the appropreate textfield will appear infront of every radio input in node/add

It seems you are looking for the Double field module

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can split your fields up into two separate parts.

  For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea

  Consequently, in all there are 4 x 4 = 16 widget types.

You can also achieve that using Field collection module.

  This module Provides a field-collection field, to which any number of fields can be attached.

But this module requires the Entity API module. Also note that this field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


Drupal theme IMG folder rewrite rule from vhosts conf file? I am wondering if it is possible to create a rewrite rule in my vhosts config file for a site to remap the location of the images folder in the theme directory.

The scenario is that I don't want to create a whole new theme for on region of a multilingual site but given that the URL is different for this region I would like to remap for example:

sites/all/themes/theme/img/(.*) to sites/all/themes/theme/img_other/$1

I have tried some variations ion what I have just put there as the example but nothing is working as yet.

Any help would be much appreciated.

Thanks

I would add a RewriteRule to the .htaccess file rather than a vhosts config; it's portable in the event of a server change and it doesn't require an Apache reload if you need to update redirect rules.

For your scenario this line is all you need in your .htaccess file:

RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]

If you're using a vhosts conf because it's a multi-domain site (e.g. en.example.com, de.example.com, etc.) then you can add a RewriteCond in front of it to match the domain you need to apply it to:

RewriteCond %{HTTP_HOST} ^de.example.com$ [NC]
RewriteRule ^sites/all/themes/theme/img/(.*)$ /sites/all/themes/theme/img_other/$1 [NC,L,R=301]


How can I use different database backend for certain tables? What do I need to do in order to serve config entities from Mongo and cache from Redis database backends?

So basically:
a) how do I tell Drupal that I want to use different db backend for certain tables?
b) what is needed in regard to drivers for those database backends? Are they available?

This is similar to How can I save/load my Entity from a different database in Drupal 8? but in this case I am interested in entirely different db backend + I want to include also non-entity tables so that annotation approach is not working for me.

That's actually more than one question because the answer is different.

To use redis as the cache, you can use our port on github: https://github.com/md-systems/redis

The README isn't been fully updated yet but the quickstart part tells you how to configure it (after enabling the module):

  $settings['redis.connection']['interface'] = 'PhpRedis'; // Can be "Predis".
  $settings['redis.connection']['host']      = '1.2.3.4';  // Your Redis instance hostname.
  $settings['cache']['default'] = 'cache.backend.redis';

To use redis for the cache tags checksum service, which most cache backends use, you need to override a service, for example in sites/default/services.yml, add the following:

To use the redis cache tag checksum implementation, put this in
sites/default/services.yml or any other yml file that is loaded after
core.services.yml:

services:
  cache_tags.invalidator.checksum:
    class: Drupal\redis\Cache\RedisCacheTagsChecksum
    arguments: ['@redis.factory']
    tags:
      - { name: cache_tags_invalidator }

In the same way, you can replace any service that is defined in the core or one of the module services.yml files with a different implementation, for example some of the mongodb service implementations provided by https://www.drupal.org/project/mongodb.

In general, you don't think in terms of tables but services and API's, and you either replace them directly or by configuration he factory service (cache/key value/queue/...)


How to import decimal fields using Feeds? I'm trying to import a decimal value from an XML feed to a Drupal decimal number field.

For example the XML feed source is: 7,6 Now I want to import it in a Drupal decimal field. So the field value will be the same: 7,6

Thing is, when I import the feed and the nodes are getting created - this field remains empty. Is this a bug or can someone point out what I'm doing wrong here?

It could be that the there is an issue with how it's interpreting the value especially if you are in a non-English context. For example, in Drupal's terms if you have a decimal value it's formatted like so "7.6". If you are trying to import a decimal value formatted with "7,6" it may have an issue.

If it is a bug, you could try and import and use a module like Feeds Tamper to rewrite that field output so that Drupal will import it.

I just tested myself and it imports fine using English decimal notation.


What's the difference between landing pages and panel pages? I'm trying to create pages (like 'Questions', 'Tags'... on top of this website). I thought the best way to do this is to use the Panels module. The Panels module has two types of pages: landing pages and panel pages.

What's the difference between them and which one's the best to create static pages?

I do not see much difference between both, in fact landing page itself a panel page.The only difference I can say is there might be predefined pages like user profile, node template that we can override using panels and thus making them a panel page while landing page is pretty much same as a node with a url to navigate and contents with various ways might be static text, embedded blocks and much more.

Panels should be never be considered as a tool to build static pages as they are resource intensive,instead use nodes for that purpose.There are many reasons why node is preferred instead of panels like node being entity has attached attributes like author, created time, revisions, also there is long list of node api which allows you to hook into node edit/insert/view processes.


User defined field not updating with PHP code I am using the uc_node_checkout and I need to set some fields that I have created. The php code is this

if (isset($order)) {
  foreach ($order->products as $product) {
    if (isset($product->data['node_checkout_nid'])) {
      $node = node_load($product->data['node_checkout_nid']);
      $node->field_productid['0']['value'] = $order->order_id;
      node_save($node);
    }
  }
}

If I create an order and add this line to the end of the php code, it dies and show a number.
die($node->field_productid['0']['value']);
When I remove that line and place and order the productid is empty.

Change this:

<?php
      $node->field_productid['0']['value'] = $order->order_id;
?>

To this:

<?php
      $node->field_productid[LANGUAGE_NONE][0]['value'] = $order->order_id;
?>

See if that helps.


Honeypot in custom webforms (manual) I'm making a custom form (fields are added by using drupal_render), but since I have Honeypot enabled for all my web forms, when I submit a form, I get the following message:

  There was a problem with your form submission. Please wait X seconds and try again.

That's because Honeypot markup isn't being included in my custom form.

I have two options:

Disable Honeypot for this form (not possible through module settings from Drupal administration menu). How can I add an exception?
Enable Honeypot manually (with drupal_renders I guess).

Honeypot docs is so poor, so I also have tried to add Honeypot markup manually in this way:

  <?php print drupal_render($form['honeypot_time']); ?>
  <?php print drupal_render($form['url']); ?>

It adds the markup actually, but it isn't fixing yet.

According to the module documentation, you can do this:

  If you want to add honeypot to your own forms, or to any form through
  your own module's hook_form_alter's, you can simply place the
  following function call inside your form builder function (or inside a
  hook_form_alter):

<?php
  honeypot_add_form_protection($form, $form_state, array('honeypot', 'time_restriction'));
?>

  Note that you can enable or disable either the honeypot field, or the
  time restriction on the form by including or not including the option
  in the array.

  You can also use Honeypot's API to modify the time delay for forms,
  add or remove protections for certain forms, etc.


Creating Code Snippets I'm attempting to use Drupal as creating a pretty versatile code snippet site for storing all of my  and others goodness. Yeah I know, sounds a bit familiar, but stick with me. What I'm having a hard time grasping is the best way to handle this in terms of both functionality and security.

At its simplest form, I'm thinking I'd create a Code content type with some taxonomy attributes, language type, etc. and then the actual 'body' of the node will be the code snippet itself. What I'm struggling on is, do I allow unfiltered text through here so anything and I mean anything can be put in and then on the node display just wrap the body in a code or pre block? I think then I could just  wrap that with Google Prettify and bam, code snippets.

Am I way off with this? Is there something I'm missing with how that could conceptually work? In terms of security, it seems a single code or pre block from any code actually rendering sounds a bit scary - is that how normal code snippet sites work?

I've been fumbling around with ideas in my head, so any help to either lead me in the right direction or slap some sense into me would be greatly appreciated. Thanks!

I would definitely encourage you to look at the http://drupal.org/project/geshifilter input filter

From the page:

At the time of this writing the GeSHi library supports highlighting for more than 200 programming languages and configuration syntaxes, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, Bash, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.

There is a stable D7 and D6 version.


How to define another data table to join for views (ie from csv file)? I successfully created two Views query plugins by learning from XML Views. My plugins query a YAML, and CSV file; they are both base view types on their own.

Now I want to learn how to join tables. (The following assumes a minimal views module skeleton called csv_views, I deleted the query plugin class I mentioned before.)

I thought of a fix table (i.e. a CSV file) that is queried without any additional features. I want to join it to a node table, let's say via title field, both in node (node title) and a column in the CSV file.

What do I need to define in mv csv_views.views.inc? For now it contains the following:

function csv_views_views_data() {
  $data['csv']['table']['group'] = t('CSV');

  $data['csv']['table']['join'] = array(
    'node' => array(
      'left_table' => 'node',
      'left_field' => 'title',
      'field' => 'title',
    ),
);

  return $data;
}

Is a field handler necessary?

In which class is the table query execution method defined? Is there a views module I can examine to learn that?
AFAIK all modules which provide tables to be joined use real database tables.

I use Drupal 6 because that is the Drupal version required by XML Views works, but I want to know Drupal 7 too and I could also settle to views 2. I guess it's still the main Views version, right?

Views can do some clever things. But I think that joining a sql query to a csv file may be a bit beyond it. (not that I'll be surprised if someone has a solution).

The issue is that within a data engine (sql, mongodb, sparql), views can work well providing that everything you want to work with is also in the same engine. If you wanted to say join a sql table to a sparql query you would have to try and do the join in code. Bring back results from sql and use in sparql or vice versa. This is not a scalable solution. It may work for a few rows, but beyond that you are going to hit some serious performance buffers.

In this case you may have more luck importing the csv file to mysql and using the data module. that should allow you to define joins and use it in your view.


Debugging help- rules are getting fired multiple times (recursively) when they should not be I'm running Drupal 7 with Rules 2.0.  I also tried the latest dev version (March 08) and I'm running into the same problem.

I have two rules that are set to run whenever a user account is updated.  Each rule should only be executed once per account update.  The "Activate- Lex" rule behaves properly; however, the "Activate-Friends" rule executes twice.  Both rules are nearly identical in structure except for the fields that they check.

In the Rules evaluation log, I see "Reacting on event- After updating a user account" and both rules fire once.  Then, near the bottom there is an additional entry for "Reacting on event- After updating an existing user account" and under this entry the "Activate- Friends" rule fires again but for "Activate- Lex" there is this message: "Not evaluating reaction rule Activate- Lex to prevent recursion."

How can I prevent "Activate- Friends" from also being fired recursively?

I am including the rules below.

"Activate- Friends" fires twice:

{ "rules_activate_friends" : {
    "LABEL" : "Activate- Friends",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "profile_management" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:field-acc-friends" ], "value" : 1 } },
      { "data_is" : { "data" : [ "account:field-acc-friends" ], "value" : 1 } }
    ],
    "DO" : [
      { "component_rules_activate_friends_features" : { "acc_to_add_friends" : [ "account" ] } }
    ]
  }
}

While "Activate- Lex" fires only once (correctly):

{ "rules_activate_lex" : {
    "LABEL" : "Activate- Lex",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "profile_management" ],
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "IF" : [
      { "NOT data_is" : { "data" : [ "account-unchanged:field-acc-lex" ], "value" : 1 } },
      { "data_is" : { "data" : [ "account:field-acc-lex" ], "value" : 1 } }
    ],
    "DO" : [
      { "component_rules_activate_lex_features" : { "acc_to_add_lex" : [ "account" ] } }
    ]
  }
}

The problem was with the components.  It turns out that the "Activate Friends" rule component only had a heartbeat "Log Activity" action, which was the source of the problem.


Setting multiple checkbox values with form_set_value I have a field that is a taxonomy term reference with a checkbox widget that allows multiple values.

I am looping through a json structure, finding the associated code value and then setting the value on the checkbox widget in the form with a case statement.

My problem is it's only setting the last value, not all the values. Here is the code. In this case where the hosts array contains all three values, I would expect all checkboxes associated with all three taxonomy terms to be checked. Only the last one is checked.

//json structure
"hosts": [
    {
        "alias": "external",
        "url": "abc.com"
    },
    {
        "alias": "internal",
        "url": "abc.com"
    }
    {
        "alias": "local",
        "url": "abc.com"
    }
]

          //php
          $hosts = $response->{'hosts'};

           foreach($hosts as $host){

           $alias = $host->alias;

            switch($alias){
                case "external":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '758'))), $form_state);
                break;
                case "internal":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '759'))), $form_state);
                break;
                case "local":
                    form_set_value($form['field_proxy_host'], array(LANGUAGE_NONE => array(0 => array('tid' => '760'))), $form_state);
                break;

            }

        }

I believe you want to pass an array with all values to form_set_value() as the function is setting the value, not appending to it. I would alter your setup to build an array of values with your switch/foreach block and then pass that array in a single form_set_value call below the switch, outside of the foreach.

Update your your foreach / switch like so:

$host_values = [];
foreach($hosts as $host){
  switch($host->alias){
    case "external":
      $host_values[] = ['tid' => '758'];
      break;
    case "internal":
      $host_values[] = ['tid' => '759']
      break;
    case "local":
      $host_values[] = ['tid' => '760']
      break;
    default:
      break;
  }
}

form_set_value($form['field_proxy_host'], [LANGUAGE_NONE => $host_values], $form_state);


Best way to convert PHP block to improve site I've just taken control over a Drupal site which the old admin used php blocks. I normally work on Joomla sites but from research and advice from others PHP blocks don't help the site in the long run.

What's the best way forward when some of the PHP blocks are set to some pages in a set area.

For example PHP block 1 is only on the Home Page's Sidebar where PHP block 2 is on Page About Us and Contact Us' Sidebar.

Just some background, This is the first Drupal site I've worked on and know only bits and pieces about Drupal apart from the general how it works and some extra details. If I've missed some research or reading which could aid in this issue which you can direct me too, this again would be great help.

Just make them a custom module!

The best start I can think of would be taking block_example.module from the Examples for Developers project as a start. Rename it, of course, and then just define your blocks in it, the way example blocks are defined. For blocks' content - move code from where it is now to appropriate functions.

That's pretty much all, if you will have more specific question during development, ask it, too.

Understanding the hook system for Drupal modules might be a useful read, too.


ajax button doesnt fire callback function I need to put some ajax buttons on each row of table.

My theme looks like this:

/**
 * Implements hook_theme().
 */
function application_wizard_theme($existing, $type, $theme, $path) {
  return array(
    'application_wizard_table' => array(
      'render element' => 'element'
    ),
  );
}

function theme_application_wizard_table($vars) {
  extract($vars);
  $header = $element['#header'];
  $header['operations'] = array('data' => t('Operations'));

  $rows = $element['#rows'];

  foreach ($rows as $key => $row) {
    foreach ($row as $fieldKey => $field) {
      $fieldValue = $field[$fieldKey][LANGUAGE_NONE]['0']['value'];
      $rows[$key][$fieldKey] = $fieldValue;
    }

    $operations = array();
    $operations['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#ajax' => array(
        'wrapper' => 'wizard-form-wrapper',
        'callback' => 'application_wizard_callback'
      ),
    );

    $rows[$key]['operations'] = drupal_render($operations);
  }

  return theme('table', array(
    'header' => $header,
    'rows' => $rows,
    )
  );
}

function application_wizard_callback($form, $form_state) {
  return $form;
}

function application_wizard_submit($form, &$form_state) {
  if ($form_state['triggering_element']['#value'] == t('Delete')) {
    dpm($form_state['triggering_element']);
  }
}

There is no action when I click on generated Delete buttons. In other words, buttons doesn't work.

I have no clue what I am doing wrong so I was hoping someone could tell me thank you in advance.

try adding '#submit':

$operations['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#ajax' => array(
    'wrapper' => 'wizard-form-wrapper',
    'callback' => 'application_wizard_callback'
  ),
  '#submit' => array('application_wizard_submit'),
);


How to resolve configuration objects lang code differences? The default language for my site is Arabic, but the administration bits are in English. This means that for now, the only needed translations are those of labels and the interface.
Earlier I tried to translate some of my content types and found most of them configured like this:

English
Arabic
None (original)  Edit

With this message above:

The configuration objects have different language codes so they cannot
be translated:

node.type.person: en
core.base_field_override.node.person.title: ar

I tried changing the language settings for the content type but the language remained set to 'None'. Any idea about how to fix this?

I'm not sure I can help but I had a similar issue.
After enabling translation for pages, I got a similar error in admin/structure/types/manage/page/translate:

The configuration objects have different language codes so they cannot be translated:

node.type.page: en
core.base_field_override.node.page.title: pt

I think this happened because I was by mistake in /pt/admin (?).

Anyway, I fixed this (in my case, I always want en), by running the command:

$ drush cset core.base_field_override.node.page.title langcode en


hide a node from node author in view I have a view of content type 'video' which shows a preview videos of particular author. I have passed content id as contextual filter. Now,I want to show a node (video) to the other users but not the node author.How can I hide it from only the node author in my view?

Without Code:

To adjust views to show/hide author content...

under Advanced Tab create a Relationship, Content:Author, Require this field
create a new Filter, User:Current, Relationship Author(or whatever name you gave the relationship), Is the logged in user -> No

This will compare the author of the content to the currently logged in user and only show the content if they don't match. This method can be used to show only content by the current user by changing the 'Is the logged in user' -> Yes


insert big array into database $array = Array(
  [a001] => Array(
    [0] => Array(
      [id] => 1789823
      [start] => 2014-09-29
      [end] => 2014-10-02
      [status] => 1
    )
  )
)

function to insert reservation:

    foreach ($array as $room_id => $item) {
      foreach ($item as $reservation) {
        db_insert('reservation')->fields(
          array(
            'room_id' => $room_id,
            'id' => $reservation['id'],
            'start' => $reservation['start'],
            'end' => $reservation['end'],
            'status' => $reservation['status']
          )
        )->execute;
      }
    }

I have an multidimensional array $array and it has about 30000 records of $reservation index. Using looping method above in my personal computer, it takes about 30 minutes to insert all of reservation, my PC spec is (dual core, memory 2GB).

Is any better implementation to do insert job?

You should avoid executing insert many times. It is enough to call ->fields multiple times, like this:

$query = db_insert('reservation');
foreach ($array as $room_id => $item) {
  foreach ($item as $reservation) {
    $query->fields(
      array(
        'room_id' => $room_id,
        'id' => $reservation['id'],
        'start' => $reservation['start'],
        'end' => $reservation['end'],
        'status' => $reservation['status']
      )
    );
  }
}
$query->execute();

This will speed up things, allowing database to prepare space for new data in one step, but with 30 thousands of records it still may take time. Be sure to tune your database accordingly - but that's out of the scope of Drupal Answers.

If you can't optimize DB enough, consider using Batch API for the job. It will make things a bit slower than the code above, but by importing a hundred or two each step you will avoid HTTP connection timeouts, PHP timeouts etc. Just make sure you only execute once per step with hundred records - even with Batch API it is good approach to group rows in as few inserts as practical.


Composerise Drupal command syntax and starting location I have 2 sites a dev site and the production site.  Need to convert them from drupal/drupal composer sites to the newer format allowing continued support for composer.
The syntax is unclear to me as detailed below. From https://github.com/grasmash/composerize-drupal

The 'composer-root' is supposed to be where .git is.  Composer is at /home dir, their is a Git directory a .composer (dir) .gitconfig (file) (I have always ran composer from terminal /opt/lampp/htdocs/d8/web directory)

So is composer-root=./home ??

The Drupal dev site is located in /opt/lampp/htdocs/d8/web where in the web dir the index.php, composer.json, composer.lock, update.php files are.  This is where I ran composer from previously.

So is --drupal-root=./opt/lampp/htdocs/d8/web ??

And I run the command from /opt/lampp/htdocs/d8/web as I have done previously?

If correct: composer composerize-drupal --composer-root=./home --drupal-root=./opt/lampp/htdocs/d8/web --no-update

Many thanks for any suggestions!

composer-root should not be your Home directory. It looks like you might have assumed that because there is a directory named git there, but that's not what the installation instructions at https://github.com/grasmash/composerize-drupal are referring to. Those instructions assume that your project files are being tracked as part of a Git repository. You can tell where the root of a Git repository is because it contains a directory called .git (note the dot in front, which the git directory in Home doesn't have).

If your project files are indeed part of a Git repository, the root would be in one of the upward directories from /opt/lampp/htdocs/d8/web.

  So is --drupal-root=./opt/lampp/htdocs/d8/web ??

Almost. The drupal root is where the core directory and index.php can be found. But that . in there makes this a relative directory path. You almost certainly mean to use an absolute path there, which would be --drupal-root=/opt/lampp/htdocs/d8/web.

  So is composer-root=./home ??

No. Most likely, you will want your composer-root to be one directory up from your project root (where index.php is). So I'd try --composer-root=/opt/lampp/htdocs/d8.


CKeditor has empty node body for some nodes On Drupal 7.52 and ckeditor module 1.17 (library version 4.6.1) and this is driving me insane. Here's a list of things I've noticed and tried:

Seems to primarily happen with unpublished nodes but not all unpublished nodes seem to have it. I have been testing using account 1 which has all privileges so I doubt it's permission related.
If I refresh the page, I can see the node body show up where ckeditor would be for half a second. When ckeditor loads it's gone though.
Checking the page source I can in fact find the textarea with the entire node body, so it is being sent to the browser.
No errors at all on the browser's console.
Can get in both Chrome and Firefox.
Disabling ckeditor makes the node body viewable again, re-enabling brings me back to the same problems.
Typing something on the empty ckeditor field, going to plain text mode and I can see the HTML, then going back to rich text mode and it's all gone again! This behavior happens when creating new nodes as well, but not with already published nodes that show the node body from the beginning. This also produces no console errors!
Updated ckeditor from 4.5.9 to 4.6.1.

Anyone have any ideas as to things I can test to pinpoint this problem?

If anyone is ever having this problem, you should check your response headers for requests sent by ckeditor. It will attempt to send a request to /ckeditor/xss to run XSS filters and if that fails it will silently just hide the entire contents of the form. In the response header I noticed a Location parameter that is only available when the form fails. The location parameter was: /user/login?destination=ckeditor/xss. This obviously means that ckeditor's request for the XSS filters is being intercepted by some other module and sending it to the login page.

In my case, the problematic content was unpublished nodes. I have yet to find the exact module causing the redirect for ckeditor, but disabling the XSS scan in includes/ckeditor.utils.js on line 163 worked perfectly to solve all my issues (seen on post #9 here https://www.drupal.org/node/2069871)


Linking content type nodes with each other I have two content types that I want to link each other. I checked node references, but node references only allows me to link to others when creating a node of that content type. What If I wanted to link two nodes of content types that are already created?

Please let me know if it is possible in Drupal-6.

Thanks

You can actually "link" nodes at any time, you just have to edit the node to add the reference.

If you want to add multiple references, you have to specify this when you set up the node reference field in your content type.  In the configuration page of the node reference field, choose how many references you want to allow (1-10, or unlimited).

For a user to add a reference that did not create the node, make sure the correct permissions are set in admin/user/permissions for the given user role. (ie "edit any EXAMPLE content")


Send unique code to user email I want to send a unique code to the user after registration. I know how to do custom modules. Also in the mail text send to the user I can see there are variables such as [user:name]. Should I define a variable and send it to the user?

Any help will be appreciated.

Thanks

I assume you will have to store that unique code somewhere because the user is going to use it and you will have to verify it against something?

I'd suggest to define a field for that unique code, you can use the field permissions module or a custom hook_field_access() to hide from the user. Then you generate that unique code in hook_user_presave() for new users and save in that field. The advantage of this is that you can then enable the token.module and you get tokens for all fields for free.

Alternatively, you can also store it in a custom table or $user->data and define hook_token_info() and hook_tokens() yourself. Instead of directly defining it as a token, you can also define it as a property (hook_entity_property_info()) to entity.module and it will automatically be available as a token as well if the entity_token module is enabled.

So yes, whichever way you chose, in the end it will be a token and you can use it in the mail.


Show external mysql database data in webform field External database. - I want to allow drupal webform users to choose data from an external mysql database table. They would have the option to choose a region and an associated locality when completing the webform. What is the best way to expose this data in webform?

I have created a view using the entity reference but can't seem to expose this in the form field?
What is the simplest

It seems you need Webform Views Select module.
But it works for D7 only.


Insert block above comments in node How to display block in node above comments. What i have tried is:
create region - regions[above_comments] = Above comments after in template.php i have added this to THEME_preprocess_node

$variables['above_comments'] = theme('blocks', 'above_comments');

and in my node.tpl.php i have added this below print render($content);

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

Added my content to this region, but its still empty, dpm($variables['above_comments']) - - is empty.
What is wrong?

theme_blocks() was only available for Drupal 5 & 6, which is why your code isn't working.

The D7 equivalent is block_get_blocks_by_region(), e.g.:

$variables['above_comments'] = drupal_render(block_get_blocks_by_region('above_comments'));


Database Query to test new users In my Drupal 7 site, I inserted values into the 'surname' and 'date of birth' fields of my database tables. I want to prevent new users whose username and date of birth do not match those on my database from being able to log into my site.
How do I achieve this?
Thank you in anticipation.

There is (AFAIK) no module that will do this for you.

But you will be able to add and process any additional criteria for logging in by using hook_user_login to insert your own business logic into the login process.  In this hook, you may insert code to redirect those users that you do not want to login to a page that explains the situation.  There is an example on how to redirect logins in the comment thread in the API documentation for hook_user_login  on Drupal.org.

For sake of completeness, I also mention that it is also possible to stop users not meeting specific criteria from registering in the first place.  To do this, you add an additional validation callback function for the registration form processing using hook_form_FORM_ID_alter.  There is a question on Stack Overflow that explains how to do this in detail for Drupal 6.


formatting dates in views I have added a date field to the article content type. I am writing a view to display this date. When I add the field I get a formatter drop-down which allows me to select three different date formats "Date & Time", "ago" or "plain".  However if I add the article post date I get more options including a "custom" format option. It seems that the handler associated with my date field is 'views_handler_field_field' whereas the handler associated with the 'system added' date field is 'views_handler_field_date'. What is going on here? Why are the two fields treated differently? What do I need to do to get the extra options?

I dont know why the post date has extra options, it seems that it allows you to create a custom format "on-the-fly". But you can create a custom date format and use it for your date field, and for other date fields as well along with the "Short", "Medium" and "Long" formats.

If you go to: configuration > date and time, you should see the three default ones (Short, medium,long). You can then click the "Formats" tap and then Add format. In the text field you can write a string that provides the format you want. Use the PHP date manual to find the letters that provides the month, date and so on. E.g if you want your format to be something like:

25-03-2014 15:48

Your string would be:

d-m-Y H:i

(Hint - you dont need necessarily to have minutes, you could also just have: d-m-Y)

Save that format and go back to the "Types" tap. Click Add date type, give it a name and then select your format on the list (it is typically at the bottom).

Then head over to your view, click the date field, and under the formatter, select Date and time, and then you should see your newly created date format on the list. Save your view and your custom date should display as the date...


How to get multifield(subfields value) in rules Drupal 7 i use the multifield module with multifield table display in my entityform.

So, in my entityform i have one multifield type with 5 subfields.

How can i get subfield value in Rules?

Thanks

First, you can try to "drill down" your entity and find the subfields. This is a great tutorial on how to drill down your data in rules. If it's not available, you can "Fetch an entity by id" into rules (under actions) and then it will be available.


Within bootstrap theme, print radio item with label and input as siblings instead of parent -> child By default, Bootstrap will render the input radio and checkbox elements as children of the label.  This is done in Drupal\bootstrap\Plugin\Preprocess\FormElement, starting at line 45:

// Place single checkboxes and radios in the label field.
if (($checkbox || $radio)) {
  $label = Element::create($variables['label']);
  $children = &$label->getProperty('children', '');

In some instances, I don't want these printed as siblings - how can I undo this?  form-element.html.twig isn't helpful unless I can somehow print the children first e.g. {{ label.#children }} and then twig will know not to print them again.  Not sure if that solution is even possible.

Thanks!

At first I was going to say hook_form_alter, but when I started digging into the Bootstrap theme I found they've created their own plugin system. I would checkout this page, you might be able to get to the render array by creating a Bootstrap theme plugin: https://drupal-bootstrap.org/api/bootstrap/docs%21plugins%21Form.md/group/plugins_form/8