Content Template no longer displaying new nodes. Works fine for older nodes In my D7 site, I have a content type that's being displayed using Content Template (Contemplate). The Content Template code hasn't changed in over a year. It's been running like a champ… displaying new content and edited content on hundreds of nodes.

All of a sudden, no new node content will be displayed through Content Template. If I temporarily disable the Content Template, the node content will appear. When I turn it back on, nothing.

I wiped out my Content Template code thinking there might be some conflict in there. I replaced the whole thing with just one line:

<?php print $node->field_body[$node->language][0]['safe_value']; ?>

Nothing.

What's interesting is that any HTML or PHP in the Content Template code will still work… it's just the field variables that are not producing any values. And again, this is only for newly created nodes.

Some of the core node variables will still work (like NID and Title), but none of the custom fields. So, for example, this code works:

node: <?php print $node->nid ?>

title: <?php print $node->title ?>

This would produce the NID and the node title successfully on the page. But, the aforementioned $node->field_body… (which is a custom field), produces nothing.

In a further effort to troubleshoot, I've disable any recently activated modules (Entityforms and Rules). No change.

The module's page explicitly states:

  NOTE: This module may be deprecated in Drupal 7! Here's your reason,
  basically the theming changes in D7 mean the field theming gets bound
  a lot lot later in the process, so it's not possible to generate the
  output into a Textarea for you to edit

In fact the module has been marked as deprecated and not updated since 20 September 2011.

Also there is a long discussion on https://www.drupal.org/node/1285558 about better ways of doing things without Contemplate module.

So it's just time for you to give up the deprecated module and re-code your template files as it simply won't work with later versions of Drupal 7.


Sorting by taxonomy sub-term weight I've got troubles with a views sorting. I'm attempting to order the views output by a term's weight. The problem is that each taxonomy sub-term starts with weight 0, no matter what.
Is there a way to get around that, so that the sub-terms are displayed correctly?

You can use hook_views_query_alter(&$view, &$query)
here you can pass extra sorting more sorting fields

http://www.chrisfree.me/2010/12/use-hookviewsqueryalter-handle-special-sort-cases
please check this link


How can I automate the "Clear Cache" everyday? Currently we have to clear it manually everyday logging in to admin console and browsing to Home->Administration->Configuration->Development->Performance

Is there way we can automate this job in Drupal 8. We tried with "cron", but that didn't help.

Despite you saying it didn't work with cron, I would suggest using cron in some way.  :)

The CacheFlush module claims to allow configuration of this via its UI (although I haven't used it so cannot personally vouch for it).

If you are implementing custom code, drupal_flush_all_caches() will handle the flushing for you.

The Rules module also allows acting on Cron runs. Using rules you could either write a custom action that uses drupal_flush_all_caches() or find a module that provides one (I haven't seen any for D8 but that doesn't necessarily mean one doesn't exist).

You could also potentially do it outside of Drupal, using a cron job on your server to call drush cr for your site.

Aside: I would suggest also considering why you need to do this and what alternatives there are. I can't really think of many (any?) cases where I would want to do this instead of just invalidating the cache of specific content entities/pages as they are changed.


Show a block on the front page, but only on the first page I have a block that I want to show on the front page, but not on every paged page (i.e., don't show it on /front-page?page=1).

How can I achieve this?

Install and enable request_data_conditions module

Then on the configuration of your block add following settings

Pages as <front>
URL query parameters set

page as must not be set
page as  must equal  0
uncheck require all


How to serve retina images? How to serve images for retina displays? It seams that there is no modules for drupal 8 in stable release. How can we properly set up to serve hi-res for retina displays?

You also have the chance to deliver double size low-quality images always. It is a valid and very popular technique.

You can do it with CSS or use the following module:https://www.drupal.org/project/hires_images


obscuring email addresses in user to user email conversation my registered users can send each other proper emails (not private messages) through contact forms on their user profiles. When user A sends such an email to user B, I need user B to be able to reply to the email that was sent by A such that the two can start having an email conversation.

*) How can I encrypt the sender's and the recipient's email address such that the original email addresses of A and B are never revealed, even if the whole email conversation - after being initiated through the contact form - continues in their external email mailboxes?

Let me elaborate this a little bit further, even though I don't know if the path I am suggesting to take is at all feasible: To each user I assign a randomly generated key, e.g. 1k1 for user A and ki8 for user B. I would then set up the contact form on the profile of A such that every submission gets sent to 1k1@mydomain.com. Then, how can I make sure that every email going to 1k1@mydomain.com automatically gets forwarded to the actual email address of user A? If this could be done, I would simply replace the sender of this forwarded email with ki8@mydomain.com and upon reply start over again.

I think this is perfectly possible, though out of the scope of Drupal to some extent. Drupal can set from and reply_to headers in the mails sent out to, eg "John Doe <abc@mydomain.com>". You'd have to then set up a mail service on the domain which would receive any replies and forward them to the correct users. How you would configure the mail service is a matter for another forum, I think.

(I suggest you edit the original question to make it about obscuring or masking the original email address rather than encrypting it. What you describe is not really encryption.)


Faceted Search Block displays values from other facet blocks I'm using the Faceted Search API (drupal 7) and followed this Tutorial: Part 1 and Part 2

All worked fine but there's a little Problem with the Values each Block displays

"Kategorie" and "Serie" are both showing all selected Fields instead just the related. But if i check one Value, which is not related to the "Kategorie" Field, I don't get any results so the search works fine but displaying the values doesn't.

I deleted all and made the search page from scratch like the tutorial described but i've got the same issue all over again. Also i checked the CSS settings for my facet blocks. Indexing all again didn't help, neither does running Cron again.

Does someone have any clues?

I finally got the answer by myself. Never thought it would be such a little setting:

If you're going to index a "text field" (and maybe going to enable the related facet block), make sure the text field is declared as string instead of fulltext.

Just go to -> Search API >> edit the correlating index >> Fields

and check the textfields. Following this you just have to re-index the items.


Simple&efficient slider module for the following purpose I'm looking for a recommendation of a rather simple, conventional, D7 carousel\rotator\slider module that will let just to replace images (without many advanced techniques).

What I do need this module to have, and doesn't very much compromise about, is these features:

Pointers (Left and right) to move between pics.
Small dots that reflect the current picture being shown.
Text that "comes" into the center of the picture from different
directions, and that Ican have full management of it's appearance
(Font-Family, size, color, etc).

Thank you very much for your help!

Views Slideshow isn't a bad way to go. It will probably take some working with css/templates/views to get it to display the way you want, but it is the most used module, so if you find yourself up against a wall using it, there's a good chance someone's already has done it and has written a tutorial, or would answer a question.

There are a few other modules out there you could look at. A quick search I found this page, which has a decent list

Also a very in-depth comparison on the different modules out there from drupal.org


How force to rebuilds all block list? When I change some block info, in my custom module, sometimes the block doesn't change in my page, even if I clear all cache.

Is there anything I can do for force change?

Sometimes clearing the cache twice in a row helps, for whatever reason.


Rule to send mail to the users about the percentage of their profile completed(single & multiple profiles) I am trying to write a rule to send an email to the user if his/her one of the profiles is not completed. But I am not getting how to get the empty field's list to sent to the user. What actually i wanted to do is. List all the fields which are empty from profile (Single & multiple) and sent the list to the user, requesting to fill all the details or just percentage of profile completion . Please help me to sort out this problem.

Thanks for your time,

How about using Content Complete or Profile Complete Percent to track profile completion. Content Complete integrates with Rules.


How to fix view with no ID I get WSOD when I try to access the views page (admin/structure/views).

I get the notice below in the error log followed by the error.

Notice: Undefined index: id in Drupal\Core\Config\Entity\Query\Query->Drupal\Core\Config\Entity\Query\@closure() (line 92 of /home/pierost0/public_html/core/lib/Drupal/Core/Config/Entity/Query/Query.php).

Drupal\Core\Entity\EntityMalformedException: The "view" entity cannot have a URI as it does not have an ID in Drupal\Core\Entity\Entity->toUrl() (line 189 of /home/pierost0/public_html/core/lib/Drupal/Core/Entity/Entity.php).

I have disabled all views through Drush but there's seems to be one empty view. Take notice on the screenshot. An empty view is enabled.

Is that view my problem? Where are the views files, or entries in the db so I can have a look for the solution there.

If you have access to the database check the table config for all entries starting with views.view.*
One of these entries might be empty or with a corrupt uuid. If so, take a backup of your database and try to manually delete this entry and see what happens.

Update
According to coments below I suggest taking a database backup and then delete views one by one from the database until the error is gone


Filter a view with contextual authored date I have a Drupal 8 view where I want to sort nodes by authored year using  contextual filters.

So www.mysite.com/2017

will list all nodes from 2017.

I set up the filter using 'Content: Created Year' which takes YYYY format.

But the filter is ignored.

www.mysite.com/2017 returns all years.

What did I miss?

Try adding the placeholder % to the path (in the main views UI in the middle column under "Page settings"),

e.g. something like my-view/by-year/% which will accept URLs like my-view/by-year/2019


Create a view that links to another view I'm trying to create a view that works as category page (aggregates a list of titles from content pages I've created). I need that list to link out to another view that is used to display photo galleries. Am I approaching this the correct way?

I want it to be dynamic so the customer can create photo galleries and they will automatically populate in the category page; then, a link send you to the proper display view.

Suppose the name of views are view1 and view2 as content pane.You have to link view2 to view1.

For linking one view to another you would have to follow some simple steps:

In view2 you have an option under PANE SETTINGS 'Link to view' and select Yes.
In view1 also you have an option under PANE SETTINGS 'Link to view' and select Yes.
Now decide the place where you want to display view2.
Suppose its the footer region. Go to the footer region and add a Global:View area.
There you have a list of all views. Select view2 and save the view.

This way you can let one view execute under another view.


LDAP password sync, happens every login I've successfully setup the LDAP configuration so that users can login to Drupal using their LDAP account.  I've mapped the Drupal password to the LDAP password so that when users change their Drupal password it updates their LDAP password.

I mapped Pwd: User only to [unicodePwd] and it synchronizes On LDAP Entry Creation and On Synch to LDAP Entry.

Those are the only two Synch options, and I need them in order to set the LDAP password.

The Question
How can I synchronize the password only when the user sets their Drupal password?  The LDAP password expiration date keeps changing every time a user logs into Drupal because it synchronizes the password with LDAP.

Edit: I actually thought I answered this question by only checking On LDAP Entry Creation and not On Synch to LDAP Entry.  That did prevent the password from being set every login, but it also prevented it from being changed at all!  Problem remains...

The password field is special in that it should only be synchronized when the password changes.  The most current version of the LDAP module can trigger field synch's either on account creation or during any account synch.  It doesn't allow the password field to be triggered only during password changes.

The password field can be unicodePwd for AD, or userPassword for other LDAP databases.

I had to modify the 7.x-2.x April 8, 2014 version of LDAP to get this to work.  Within the modifyLdapEntry function we need to know if the password field is being modified.  Don't synchronize the password field if we know the password is not changed (which is true during login synchronization).  Also, do not synchronize the password if it's not set (such as during the edit account page).

Modify LdapServer.class.php, function modifyLdapEntry(), adding global variables for the current password, and for whether or not the password is being changed.  If there is no current password but we are changing the password (such as password reset form or admin edit user form), set the password.  Also, if the current password is given and it does not match the new password (such as user edit form), set the password.  Otherwise, unset that property from being synchronized.

..

  global $current_password;
  global $changing_password;
  if ((empty($current_password) && $changing_password) || (!empty($current_password) && $current_password != $attributes['unicodePwd']))
  {
    $attributes['unicodePwd'] = ldap_servers_convert_password_for_active_directory_unicodePwd($attributes['unicodePwd']);
  }
  else
  {
    unset($attributes['unicodePwd']);
  }

..

Modify the ldap_user.module, function ldap_user_grab_password_validate(), and set the current password if it is given, and set the changing password variable if we know it's changing.

/**
 * store password from logon forms in ldap_user_ldap_provision_pwd static variable
 * for use in provisioning to ldap
 */
function ldap_user_grab_password_validate($form, &$form_state) {

   // This is not a login form but profile form and user is inserting password to update email
  if (!empty($form_state['values']['current_pass_required_values'])) {
    if (!empty($form_state['values']['current_pass']) && empty($form_state['values']['pass'])) {
      ldap_user_ldap_provision_pwd('set', $form_state['values']['current_pass']);
    }
    // Or this is a profile form where the user is updating their own password
    elseif (!empty($form_state['values']['pass'])) {
      global $current_password;
      $current_password = $form_state['values']['current_pass'];
      ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
    }
  }
  // otherwise a logon form
  elseif (!empty($form_state['values']['pass'])) {
    if ($form['account']['pass']['#type'] == "password_confirm") {
      global $changing_password;
      $changing_password = TRUE;
    }

    ldap_user_ldap_provision_pwd('set', $form_state['values']['pass']);
  }
}


How to make menu block item show up? I have a menu block composed of menu items with submenu items.
Each menu item is displayed separately in a block.

They are all set to appear on every page, no restrictions. However if I were to access one of the submenu items, the entire menu item (including the submenu items) belonging to it does no longer appear.

I have checked in variables from template_preprocess_page, the region where the menu item block should appear is showing as empty.

How can I make it show up?

I have found the issue, "Make the starting level follow the active menu item." needs to be unticked.


How to customize the email subject for a webform? I am using Webform 7.x-4.0 on Drupal 7.24 and I am trying to customise the email subject for my webform.
I have followed the instructions as per the instructions in this post How to use [submission:values] in Email template in Webforms but when I save the settings, the email subject is blank.

I entered [submission:values:event_type] for the custom field and my field key is as follows:

After saving the configuration, the field turns up blank.

The email sent out just shows -no subject given as the subject of the email.

So, I think you're using the UI wrong. Each of those email templates you have should be to a different user and it doesn't look like you've added an email to anyone.

Below where you have your Value of "Event Type" line there's the option to send an email to a specific email address (I.E the admin) or to add an email to the value of the Email token, you need to add and save an email to a specific person there and add a subject using your token substitution there. Or at least that's what it looks like from what you posted.


How to add reset button to forms? I've been researching this matter for a while with no clear answer yet.
So, here are a few questions ...

I'm assuming (correct me if I'm wrong) that Drupal 7 doesn't support reset buttons. It appears, according to the form API (as discussed in Pro Drupal 7 Development), that all the buttons (input type="submit", button, and image_button) are by default submit buttons. There doesn't appear to be a way to override the defaults either.
So, if I wanted to add functionality to my forms for my users to clear forms (if they choose), would I have to create a module?

Would I be able to pull this off by using the general button type with executes_submit_callback set to false and by adding some type of Ajax function to the mousedown event?

** EDIT: I added the following to my hook_form_alter() **
$form['reset'] = array(
'#input' => TRUE,
'#name' => 'reset',
'#button_type' => 'reset',
'#executes_submit_callback' => FALSE,
'#limit_validation_errors' => TRUE,
'#process' => '',
'#theme_wrappers' => array('button'),
);

I got the following error message & warning:

Notice: Undefined index: #type in _form_builder_handle_input_element() (line 1949 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).
Warning: Invalid argument supplied for foreach() in form_builder() (line 1763 of /var/www/vhosts/lae/drupal-7.11/includes/form.inc).

Is there a way to add the "reset" button type to the types of buttons without crashing the entire form.inc?

My preferred way to do this is.

Add the button to your form like so:

$form['options']['reset'] = array(
  '#type' => 'submit',
  '#value' => t('Reset'),
  '#submit' => array('MY_MODULE_FORM_ID_reset'),
);

Then create the reset function like so:

function MY_MODULE_FORM_ID_reset($form, &$form_state) {
  $form_state['rebuild'] = FALSE;
}

No Javascript, no markup.


Display field's label only when any value added to it For example Taxonomy Terms field Label is always displayed even if no tags added to it. How can I show Taxonomy Terms field's Label and its values (tag's links), only when there have been a value added to it?

I try to achieve that by adding conditionals based fields, something like below code to node template:

{% if content.field_tag is not empty %}
{{ content.field_tag }}
{% endif %}

or

{% if content.field_tag %}
{{ content.field_tag }}
{% endif %}

According to the article:Comparison of PHP Template and Twig theming paradigms but whatever I try I can't get any result.

almost you did , instead of content.FIELD_MACHINENAME use node.FIELD_MACHINENAME.value
I mean try something like

{% if node.field_tag.value %}
{{ content.field_tag }}
{% endif %}

for make sure that this solution work correctly(for debug) try {{ kint(node.field_tag }}.


Custom module template override not loaded Hi I am desperetly trying to override the template of my D7 custom module's block here is my code :

  function lnr_block_info() {
    $menus = menu_get_menus();
    $blocks['actualites_filter_article'] = array(
      'info' => t('Actualités: Filtres Articles'),
    );

    return $blocks;
  }

  function lnr_block_view($delta = '') {
    $block = array();
    $menus = menu_get_menus();

    if($delta == 'actualites_filter_article'){
      $block['content'] = theme('actualite_filter_article');
    }

    return $block;
  }

  function lnr_theme() {
    $module_path = drupal_get_path('module', 'lnr');

    return array(
      'actualite_filter_article' => array(
        'variables' => array('result' => NULL),
        'path' => $module_path. '/templates',
        'template' => 'actualite-filter-article',
        //leave off .tpl.php
      ),
    );
  }

The template of the module is loaded correctly, but once I copy paste it in the theme templates directory it is not overriden. (the name of the template file is : actualite-filter-article.tpl.php ). What aam i doing wrong ?

Thanks in advance

I think you are missing the argument for the hook_theme so you can do it this way

/**
* Implements hook_theme().
*/
function lnr_theme($existing, $type, $theme, $path) {
 $items = array();
 $path = $path . '/templates';

 $items['actualite_filter_article'] = array(
  'path' => $path,
  'template' => 'actualite-filter-article',
 );

  return $items;
}

Give it a shot


Replacing field result with hook_views_pre_execute when replacing SQL query I have a simple page view (unordered list) with just one field (content: path) and one contextual filter (nid). The view isn't displaying the right path if the language of the selected node is not the current site language.

For that reason i've decided to replace the query and try to get the aliased path of the selected node. I've used hook_views_pre_execute and already replaced the query for this view. The query already shows up in the preview section in Views UI but the result is empty now. The query works in phpmyadmin.

I can't find much documentation about this hook. How to get my query to replace the views Path field and display the result instead?

This is my SQL Query:

SELECT ua.alias AS alias
FROM
{url_alias} ua
WHERE  (ua.source = 'node/247')
LIMIT 1 OFFSET 0

This is my function from my custom module:

function views_node_path_views_pre_execute(&$view) {
 if($view->name == "global" && $view->current_display == "node_path_page") {
  $myQuery = db_select('url_alias', 'ua')
  ->condition('ua.source', 'node/' . $view->argument['nid']->value[0], '=')
  ->fields('ua', array('alias'));
  $view->build_info['query'] = $myQuery;
 }
}

EDIT:

Just fixed it myself with hook_views_post_render from views API. I know, it's just a dirty hack and i don't really like it but i need this part to be working.

function views_node_path_views_post_render(&$view, &$output, &$cache) {
 if($view->name == "global" && $view->current_display == "node_path_page") {
  $result = db_select('url_alias', 'ua')
   ->fields('ua', array('alias', 'language'))
   ->condition('ua.source', 'node/' . $view->argument['nid']->value[0], '=')
   ->execute()
   ->fetchAll(PDO::FETCH_NUM);
  if($result) $output = '/' . $result[0][1] . '/' . $result[0][0];
 }
}

From your description, you are trying to display the aliased path of the current page using a view.If you are trying to encourage users to deep-link to your site, a PHP code snippet might be a better approach. (Drupal often encourages complex answers to simple requirements.)

Using aliased links means that the links may be broken if the alias changes (as with a change in the page title) unless the old aliases are retained. In that case, multiple aliases will exist for each page. Deep links should use the un-aliased url.


Modifying contextual filters to display user name I have a view that takes one contextual filter for a UID. I would like to make the title of the page include the user name? My closest bet it the "Override title" option under "When the filter value is  in the URL or a default is provided". However, it appears that the only tokens available there are for the plain filter values, but I need the user name (as opposed to the UID). Is there a way to do this?

It appears that %1 does actually return the title.


Is there a way to re-categorize content in a list form? There are hundreds of content pages on a site I work with. These are categorized with Taxonomy, which connects the pages to the menu system. There is a need to revise these connections. I would like to create a page (view) where these Taxonomy references couyld be updated?
Is this possible?

Assuming I read your question correctly, you could try the Edittable Views module. details from its project page:

Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.
Editable fields can be added on the base entity as well as on entities brought into the View by a relationship. Other, non-editable fields may be added to the View, in which case they function normally.


Hide block on 404 (not found) page SITUATION:

A View page displays all "items" that have a certain "code".

The code is passed via a contextual filter, e.g. /items/17, where 17 is the code.

A user might try to guess a code by typing it in, e.g. /items/345.

When the View is empty (i.e. the code is bogus), a not-found exception is raised as follows:
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if ($view->current_display == 'page_machine_name' && empty($view->result)) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  }
}

There is a menu included as a block that's displayed at the top of the View page.

The menu block configuration restricts the block to pages with paths /items/*.

PROBLEM:
The menu also appears on the 404 page, since that page retains the bogus path /items/345. How can I exclude the menu block from the 404 page?
NOTES:

I want to display the default 404 page rather than the view with a "not found" message as its body.
I don't want to display the view as a block instead of as a page unless it's the only way. I already know how to solve the problem if I have to do that.
If there were a way to say, "Include this block only on View pages" (like you can for content types), that would be ideal.
There are actually three blocks that need to be excluded from the 404 page; I mention only one to make it simpler. The other blocks are a text block and a banner block.
I see that a solution to this problem has been proposed for Drupal 9, but not available yet.

Yes, the solution is not available yet in core, see https://www.drupal.org/node/2245767.
But you can use this contrib module https://www.drupal.org/project/block_in_page_not_found and negate the condition to not show the block on a 404 page:


Drupal shows ?? instead of special characters with oracle I have a Drupal 7 installation working with Oracle 11g database with Apache/2.2.12 (Linux/SUSE) and PHP/5.3.8

The problem I face is that special characters are not displayed correctly. Instead two question marks ('??') are shown.

I've been able to correct some static pieces of content (in blocks) converting the characters to their corresponding html entity. However, new content and menus dont support this.

I would like to know how to show those characters correctly.

Check you are using UTF8 character set in Oracle database, and in apache config.
For data in Oracle db that is not UTF8 be careful if you need to convert, you need to identify what the original characterset is and the best way to convert to UTF8.

  The general rule of thumb is that if you are using UTF8 all the way
  you should not see those question marks in the browser.

Take a look here for Oracle UTF8 conversion info: https://stackoverflow.com/questions/8239250/how-to-configure-utf8-character-set-in-oracle


Print Block heading for $page - section In my page.tpl.php I have 2 different sections nl. $page['section_orange'] and $page['section_contact'].

What I want is for my block.tpl.php to print my heading in h2 when a block is listed in the $page['section_orange'] section and in h4 in the $page['section_contact'] section.

How can I achieve this from within my block.tpl.php template.
Or do I need to create a hook within my template.php?

You can create template file with name block--section_contact.tpl.php, put there code from default block.tpl.php file, replace h2 tag by h4 and all blocks in section_contact region will have h4 heading.


Override form.html.twig into module i need to override a form.html.twig in my custom module.

i used hook_theme_suggestions_alter in my .theme file to add new suggestions.

function MY_THEME_theme_suggestions_alter(array &$suggestions, array $variables){

if (isset($variables['element']) && isset($variables['element']['#type']) && $variables['element']['#type'] == 'form') {
    $original_theme_hook = $variables['theme_hook_original'];
    $suggestions[] = $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']);
}

return $suggestions;
}

the debug show me this suggestions

THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS: * form--pom-mapping-setting-form.html.twig x form.html.twig -->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/form.html.twig' -->

if i put form--pom-mapping-setting-form.html.twig in my_theme/templates/ folder works.

if i put form--pom-mapping-setting-form.html.twig in my_module/templates folder doesn't works

I don't understand why :/

why drupal doesn't read templates in module folder?

thanks

You need to alter the Theme registry and set the path of the hook suggestion "form" to your_module/template path as bellow:

/**
 * Implements hook_theme_registry_alter().
 */
function My_Module_theme_registry_alter(&$theme_registry) {
  // You can add some conditions here in case you want
  // to override the form template only for some reasons.
  $theme_registry['form']['path'] = drupal_get_path('module', 'My_Module') . '/templates';
}

And the structure of your module should be:

-- My_Module
  +-- templates
     +-- form--pom-mapping-setting-form.html.twig


Display an Array as a List inside a Table I have an array that have a created with items in it that I want to populate a cell in a table.  In my case this is a table of Orders in Ubercart and have created an array, called $models that is populated with the Model numbers of the line items in that order.  What would be the best way to display this array in my table?

Currently,

$rows[] = array(
  ...
  array('data' => $models),
  ...

display's nothing in the Model column.

There's theme_item_list() which

  Returns HTML for a list or nested list of items.

e.g.

$rows[] = array(
  ...
  array('data' => theme('item_list', array('items' => $models))),
  ...


new product display content type not showing in products view I've just started playing with drupal commerce which seems pretty good.
I'm using Kickstart v2-rc1. I created a new product display type (content type with a product reference field). Everything seems to work, I can create a new node of this type and create/add variation. I can see my product under the correct category.
However, when I use the product view (all product), my product doesn't appear in this list. What am I missing ? Is it an permission problem or the products view which is filtering my product ?

I finally found the problem. The answer is probably obvious for a drupal expert but not for someone who just use drupal commerce out of the box.

Right, so the search facility (search box and 'all product' link ) use the search API which needs to be re-indexed when something changed.

For some reasons it wasn't. I'm expecting that adding a new product/entiry will triggered a reindexation but it doesn't. It seems also it could be done via the cron (but I haven't set any cron either, nobody told me to so). And, anyway, it seems the indexation was 'broken' (I changed one of the category name) so I add to recreate the indexes form scratch.

So the answer is , my searches need reindexation.


Override template files in child theme I am newbie in Drupal. Using some articles, I have created a child theme of Bartik in Drupal 8 but I do not know how to override default template files. Can anyone help me to understand the child theme structure in Drupal 8?

In your child theme's folder create a subfolder called "templates". In this folder you should store your own templates. Just copy the system's (or parent theme's) template to your folder and modify it.
Further on, you can create more special templates, i.e. not only node.html.twig but also node--blog.html.twig.
Finally, switch on twig debugging, then you will get comments in your html like this:
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--bootasde-branding.html.twig
   x block--system-branding-block.html.twig
   * block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block/block--system-branding-block.html.twig' -->

Then you always know which template was finally taken.


How do I configure the mock server? According to the documentation, the test module included with the LDAP module  should  contain the mock LDAP server.

Where can I find it after enabling this module?
How should I configure it so that I can start testing logging in with a LDAP server?

The "Mock LDAP" server that is being used for the LDAP Test module is, in fact, a mock server object. It allows the tests to run, and doesn't exist outside the scope of the simpletests.

If you're looking to provide a way to "mock" an LDAP instance on your development site, it can't provide that functionality.

If you're trying to write your own simpletests for LDAP integration, check out the Examples for Developers project. The included module, simpletest_example, has excellent documentation for writing simple tests.


How to fix missing php extensions problems in custom Docker image? There are many excellent questions here about automating the initial setup process for Drupal but I haven't seen any pertaining specifically to Drupal containers in Docker.

Here's my setup. I've kept the images/builds as vanilla as possible; the only Dockerfile I have is for composer, inspired by the accepted answer to this question.

docker-compose.yml

version: '2'
services:

  drupal:
    image: drupal
    ports:
      - 8888:80

  mariadb:
    image: mariadb
    environment:
       MYSQL_DATABASE: drupal8
       MYSQL_USER: drupal8
       MYSQL_PASSWORD: drupal8
       MYSQL_ROOT_PASSWORD: drupal8
    restart: always
    depends_on:
      - drupal

  drush:
    image: drush/drush

  composer:
    image: composer
    build: composer_init
    depends_on:
      - drupal
      - drush

Dockerfile for composer:

FROM composer

RUN composer -vvv create-project drupal-composer/drupal-project /var/www/html --stability dev --no-interaction
RUN cd /var/www/html
RUN drush si -y \
  --db-url=mysql://root:drupal8@localhost/drupal8 \
  --site-name=drupal8 \
  --site-mail=drupal8@foo.com \
  --account-mail=drupal8@foo.com \
  --account-name=drupal8 \
  --account-pass=drupal8 >> /dev/null 2>&1

I spun up the build process by issuing docker-compose up -d --build.
Now when the process reached the composer part, it blew up with the following message:

Resolving dependencies through SAT
Dependency resolution completed in 0.001 seconds
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - drupal/core 8.5.x-dev requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - drupal/core 8.5.1 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - Installation request for drupal/core ~8.5.1 -> satisfiable by drupal/core[8.5.1, 8.5.x-dev].

  To enable extensions, verify that they are enabled in your .ini files:
    -
    - /usr/local/etc/php/conf.d/date_timezone.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-zip.ini
    - /usr/local/etc/php/conf.d/memory-limit.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Based on other answers/suggestions here, I added a Dockerfile to my drupal section and added RUN apt-get install php7.0-gd to the Dockerfile, but this now blows up with E: Package 'php7.0-gd' has no installation candidate.

I've ensured that the PHP version for this Docker image is PHP 7.

php --ini gives me:

# php --ini
Configuration File (php.ini) Path: /usr/local/etc/php
Loaded Configuration File:         (none)
Scan for additional .ini files in: /usr/local/etc/php/conf.d
Additional .ini files parsed:      /usr/local/etc/php/conf.d/docker-php-ext-gd.ini,
/usr/local/etc/php/conf.d/docker-php-ext-opcache.ini,
/usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini,
/usr/local/etc/php/conf.d/docker-php-ext-pdo_pgsql.ini,
/usr/local/etc/php/conf.d/docker-php-ext-zip.ini,
/usr/local/etc/php/conf.d/opcache-recommended.ini

How can I resolve this error now?

I resolved this by removing the drush and composer services from the docker-compose file and updating my Dockerfile for drupal as follows:

FROM drupal

RUN apt-get update -y && apt-get install -y wget vim git mysql-client

RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \
    php composer-setup.php && \
    mv composer.phar /usr/local/bin/composer && \
    php -r "unlink('composer-setup.php');"

RUN wget -O drush.phar https://github.com/drush-ops/drush-launcher/releases/download/0.4.2/drush.phar && \
    chmod +x drush.phar && \
    mv drush.phar /usr/local/bin/drush


Runing PHP Code inside region.tpl.php file I'm trying to create a dynamic site based on a static theme. I wonder to know why when I want to put my main menu in the region--page-top.tpl.php it does't work. this code

<?php print theme('links__system_main_menu',
                   array('links' => $main_menu,
                            'attributes' => array( 'class' => array('links','inline'))));?>

works correctly inside the page.tpl.php but it seems that php code doesn't recognize in the region section. The HTML codes work fine, though.

I believe you cannot render main menu in this way within a region, the variable is not there. You could try with:

$main_menu_tree = menu_tree(variable_get("menu_main_links_source", "main-menu"));
print drupal_render($main_menu_tree);

Even better, I would recommend that you simply render the output of the particular region properly and add the menu dynamically from Blocks administration.

To render a region in your theme shortly, you need to define a proper region in your theme's .info file (eg. my_region) and render it using print render($page['my_region']); in the .tpl.php file. I hope this guide will help you: https://drupal.org/documentation/theme


Block does not show up in block list recentpost.file

name = recentpost
description = A list of node with thumbnail
package = Liu's custom
core = 7.x
version = 1.0
files[] = recentpost.module

recentpost.module

/**
 * @file
 * Add thumbnail to each node
 */

function recentpost_block_info(){
  $blocks['recentpost'] = array(
    'info' => t('Recentpost'),
    'status' => true,
    'weight' => 0,
  );
  return $blocks;
}

function recentpost_block_view($delta = '') {
  $block = array();
  $block['subject'] = t('Node with thumbnail');
  $block['content'] = 'ssssssssssssssss';
  return $block;
}

I've created a sample module from scratch and can activate it in admin->module, but when I go to structure->block, the block I've just created doesn't show in the list no matter how many times I've cleared the cache both from drupal and the IE. Can anyone help me sort it out.

Always set region (Until bug is fixed)

I believe this may be a bug in the code, it seems that is Status/region are toggled it causes problems, to guarantee that it shows for now make sure you set region

    function recentpost_block_info(){
      $blocks['recentpost'] = array(
        'info' => t('Recentpost'),
        'region' => BLOCK_REGION_NONE,
        'status' => true,
        'weight' => 0,
      );
      return $blocks;
    }

The bug seems to be in the function "_block_rehash()" where it checks for empty($block['status'])


Is there for modules the same as theme_get_setting() for themes? I am using variable_get('name-of-setting', 'default-value') to retrieve module/theme settings in several locations in code.

The purpose is to keep default settings in one locations preferable in .info file. I am able to this for themes:

variable_get('name-of-setting', theme_get_setting('name-of-setting'));

Here the theme_get_setting() retrieves the settings from the theme-name.info file:

settings['name-of-setting'] = some_value

Can i do the same for modules? What is the API to retrieve settings from module .info file? If not, how do you handle module default settings to avoid it scatter around code?

You're probably looking for drupal_parse_info_file()

Parses Drupal module and theme .info files.
Info files are NOT for placing arbitrary theme and module-specific settings. Use variable_get() and variable_set() for that.

Pay attention to the second paragraph - it applies to you :)


How to implement module dependencies in a theme and package modules with a theme? If you're making a theme and associated custom modules designed for that theme and no other theme. Is there a way to package the modules with the theme so that when the theme is activated the modules will show up in the module list ready to be activated? The custom modules are build for the theme and so if they can be packaged with the theme that would make it simple to distribute.

I would like to avoid the problems of the user not being able to fully use the theme due to a missing library or module.

If a theme and collection of modules that are packaged in a single zip file, when passed to the drupal installer, permit Drupal the ability to extract the theme and modules to the correct locations? Can it determine the themes dependencies and then install the modules from a url?

Some examples that I can think of is having color pickers for a theme so you can select different colors for the theme in the settings area. I could make custom modules for this and have the modules show up if the theme is active. Maybe also have it alert the user to activate the modules one theme activation. If the theme has a custom slideshow should this be built into the theme or maybe as a packaged module inside the theme that shows up as a module in the modules list to be activated.

Maybe inside the theme package it could have a modules folder that Drupal could then extract the modules and install them into the module directory. On uninstall could prompt the user if they would like to also uninstall the associated modules. If this is possible (or soon to be) this would make managing complex themes clean and simple. It would also keep the module list clean as well. maybe some dependency in the theme info file?

Other thoughts would be if a theme was active maybe it could find said modules and inject rendering options into the modules configurations options.

As of right now this is just a curiosity of mine and I wonder if it could be done. This idea came about after setting up many Drupal sites and making custom modules and themes. Then it hit me what if I could do more with my custom themes by knowing it can only run if all the needed modules where there. Then I wouldn't have to worry about a bad user experience.

Up to Drupal version 7, themes do not allow to have the typical directive for module dependencies in their info files. Because themes are supposed to be module independent.

However, for D8, there is the issue about dependencies[] for themes, so they can depend on modules (created back in 2009 ... current status = needs work).

For D7, Comment #3 in (Drupal core) issue 647014 contains a possible work around that you may want to consider, something like so:

<?php
function mytheme_preprocess_page(&$vars)
{
  ...
  if (!module_exists('needed_module'))
  {
    // No needed_module means we need to add it, let everyone know.
    //
    print "
"  . t( 'mytheme requires that module needed_module is installed')
        . "
"
        . "
"  . t( 'warning generated in file: %f', array ( '%f'=>__FILE__ ))
        . "
";
  }
  ...
}
?>


Accessing location field programmatically in Drupal 7, via hosting entity object and wrapper I'm using Location module (particularly its Location CCK part) with Drupal 7. Added location field 'field_location' to User (as an example of hosting entity), and initialized location values for test users in user edit interface. However, I'm unable to access location data of the current user:

global $user;
$user_id = $user->uid;

$loc = $user->field_location;

or:

$wrapper = entity_metadata_wrapper('user', $user_id);
$loc = $wrapper->field_location;

The statements with $loc don't work for object and wrapper (while both user object and wrapper are initialized successfully). Same for:

$loc = $wrapper->field_location[0];
$loc = $wrapper->field_location->raw();

I've read a number of posts on this topic, however haven't found a workable solution, would appreciate insights on this.

For a custom field to be available to the wrapper, the module defining it needs to implement hook_entity_property_info() (or, which is new to me, by adding property metadata to the field using hook_field_info_alter()).

The location_cck module doesn't do that, but the bundled location_entity module does.

If you enable that module you should be able to access the location field as you'd expect.


How do I add a class to local task links in Twig template? I've used custom templates to add BEM style classes to both the local tasks UL wrapper and the individual LI items, I'd like to also add a class to the actual local task (tab) link.

This is the default code in the Classy template:

<li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>

Is there no way to simply add a class to the {{ link }} item?

{% set link = link|merge({ '#attributes': { 'class': [ 'your', 'custom', 'classes' ] } }) %}

<li>{{ link }}</li>


Statistics module not logging content views after upgrade I recently upgraded my news blog from 8.4.0 to 8.6.1 and the major issue I have is that the statistics module is not logging the content views any more. The old articles seem to have stack in the same count number and the new articles not showing up in teaser links as they are stuck to zero.

Any ideas please?

There was a problem with missing php file in theme folder and that caused the issue. When we added the file then the counter worked as expected.


Not able to assign value to field using form_alter hook I have a add entity form. On which I want show some fields pre-populated from other entity. I wrote form_alter hook and pre populate fields....
But for one field it wont work. It populate the data in text box but when user change that data and click on save it saves pre populated data not the changed or updated one.

Scenario 1:
"field_summary_introduction" this is a text area and code used to prepopulate data is
$form['field_summary_introduction']['und'][0]['#value'] = $arrDefaultEntityData['field_summary_introduction']['und'][0]['value'];

This is working fine and if user update the data it stores updated data

Scenario 2:
"field_company_subtitle" this is text field and following code is not working

$form['field_company_subtitle']['und'][0]['#value'] = $arrDefaultEntityData['field_company_subtitle']['und'][0]['value'];

Instead if I use following code then it prepopulate data

$form['field_company_subtitle']['und'][0]['value']['#value'] = $arrDefaultEntityData['field_company_subtitle']['und'][0]['value'];

But not able to store updated data it stores prepopulated data....
All fields in my form taking populated data to save in db. If user update the populated data it saves old populated data in database.
Thanks in advance

You need to use #default_value:

$form['field_company_subtitle'][LANGUAGE_NONE][0]['value']['#default_value'] = ...


Show parent items in hierarchical facet display Taxonomy terms are configured as such:

Parent category 1
- Child category 1
- Child category 2

Parent category 2
- Child category 3
- Child category 4

"Empty facet behaviour" is set to "Do not display facet".

"Flatten hierarchy" is turned off.

"Treat parent items as individual facet items" is turned off.

But the facet display doesn't show the parent items. How do I configure it properly to do so?

Enable the "Index hierarchy" option under your index filters. After enabling you can choose the field(s) for which you want to index the hierarchy. Save. Re-index.

Parent terms will now show in your facet.


Drupal Feature Recreate Module - what next I am newer to drupal features. I have a site that was built heavily with them.

There is a drupal-feature where I added some fields. After I added and reorganized them I recreated the module.

Do I need to uninstall the current drupal feature module then install the new one?
Or can I just add the new module turn it on and go from there?

Thanks for the help!

From Modifying, updating and reverting Features:

  The "recreate" button in the web-based administration interface is the equivalent to "update". However, the modified code will be provided for download as a .tar archive, instead of overwriting the existing feature module. It is up to the site builder to manually unzip and re-upload the modified module, replacing the original.


How can I add code that will call the javascript within a block every minute? I have a block that contains javascript which calls a website that sends an ad to this block (see below: Note: I changed the domain name to adserveringwebsite).
How can I add code that will call the below javascript every minute so that a different ad will show up every minute instead of just one ad at page load?

<script src="http://www.adserveringwebsite.net/1e-kn99655"></script>

You will need to use JavaScript's setTimeout() function:

To elaborate, place the code that calls your ad server inside a JS function.

Then, use setTimeout(), as demonstrated in the website I linked to, to call it at every x interval.


hello_world_page_attachments is not called I was following the documentation about creating a custom hello world module.
I got to the point where you are told how to attach custom JavaScript and CSS files using hooks. I want to get a JavaScript file attached on every page. Unfortunately, I can't manage it to work. Everything was working, so far.

This is the code I am using.

hello_world.libraries.yml

hello_world:
  version: 1.x
  css:
    theme:
      css/style.css: {}
  js:
    js/hello_world.js: {}
  dependencies:
    - core/jquery

hello_world.module

function hello_world_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'hello_world_for_drupal_8/hello_world';
}

hello_world.js

alert("outside script");
console.log("outside script");

Libraries are refererred to as module_machine_name/library_name

If the other names in your post are accurate, in your case that should be:

$attachments['#attached']['library'][] = 'hello_world/hello_world';


I need to add rel="nofollow" to the button provided by "views load more" module I need to add rel="nofollow" to the button "Load More" provided by Views Load More, but the problem is that the anchor is created in views_load_more.module (line 91) this way:

$li_next = theme('pager_next',
    array(
      'text' => (isset($tags[3]) ? $tags[3] : t($vars['more_button_text'])),
      'element' => $element,
      'interval' => 1,
      'parameters' => $parameters,
    )
  );

But I dont know how to add an attribute to that, when I print_r($li_next), it prints the link.

I have tried this:

function THEMENAME_preprocess_pager_next(&$vars) {
  $vars['#path']['options'] = array('attributes'=>array('rel'=>'nofollow'));
}

But didn't work

I found the answer myself, and I want to share it in case someone have the same problem in the future.

Just override the theme_pager_next() function in the template.php file of your theme like this:

function YOURTHEME_pager_next($variables) {
  $text = $variables['text'];
  $element = $variables['element'];
  $interval = $variables['interval'];
  $parameters = $variables['parameters'];
  global $pager_page_array, $pager_total;
  $output = '';

  // If we are anywhere but the last page
  if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
    $page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);
    // If the next page is the last page, mark the link as such.
    if ($page_new[$element] == ($pager_total[$element] - 1)) {
      $output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters,'attributes'=>array('rel'=>'nofollow')));
    }
    // The next page is not the last page.
    else {
      $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters,'attributes'=>array('rel'=>'nofollow')));
    }
  }

  return $output;
}

I've just add 'attributes'=>array('rel'=>'nofollow') to theme() function :)


Route parameter upcasting and route access? Original problem:

I am trying to do a couple of (seemingly) simple things to convert a module I made in Drupal 7 to Drupal 8 (RC1).

First I will note I am using the File Entity module in Drupal 8, which may or may not be stable/complete.

I want to add a tab on a File entity (much like Edit or Archive) that lets me trigger processes, related to the data contained in the file (its a spreadsheet).

So far, I have been able to stumble through getting a route defined and a tab to appear.

mymodule.routing.yml:

entity.file.import_data:
  path: '/file/{file}/import-data'
  defaults:
    _form: '\Drupal\datacenter\Form\ImportDataForm'
    _title: 'Import Data'
  requirements:
    _permission: 'access content'
  options:
    _admin_route: TRUE

mymodule.tasks.yml:

entity.file.import_data:
  route_name: entity.file.import_data
  title: 'Import Data'
  base_route: entity.file.canonical
  weight: 3

Well okay. So far so good. Not the most robust thing in the world, but I am still working my way through unfinished docs and such. From here, I have a new tab on a File entity form, right next to Edit.

First, how can I change the permissions to not be access content, but to check access to see if the current user has access to edit the file in question? If I change _permission to _entity_access: file.update (as I have seen in File Entity) the tab vanishes, and direct URL access returns Access Denied (even as user 1). Do I have to implement something extra to make that work?

Second, I don't seem to be receiving the {file} argument or file entity object in my form builder.

Form class:

namespace Drupal\datacenter\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ImportDataForm extends FormBase {
  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'datacenter_import_data_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state, FileInterface $file = NULL) {
    // fields to be defined

    return $form;
  }

 // extra code removed

buildForm doesn't have an entity (file) argument. What am I missing? I thought upcasting basically happened if the object ID was in the route (like node, user, etc).

Also, is this even the way to go about it? Basically this screen will do a few things, it will inspect the file object, check to make sure the mime is right, parse the csv or excel data, and read it back on the screen in the form of options. Whatever the user ticks off, will kick off a series of batches. Where would those batch functions go? In this class? In another file? I also see other classes like ContentEntityForm, EntityForm, etc.. which one should I be using?

I have all of this working great in Drupal 7, I am just having trouble getting momentum converting it over and finding what I need.

Entities can be upcasted with these methods:

Note: to use _entity_access requirement, you must implement one of these options this information. See \Drupal\Core\Entity\EntityAccessCheck for internals.

Controller reflection

Type cast the entity object as a parameter of the controller.

For your form controller, replace:

 buildForm(array $form, FormStateInterface $form_state, $file = NULL) {

with:

 buildForm(array $form, FormStateInterface $form_state, \Drupal\file\FileInterface $file = NULL) {

This works with any entity type, not just files.

See EntityResolverManager:setParametersFromReflection.

Using _entity_view or _entity_form controllers

Entity types found in the path are upcasted automatically if the route definition has _entity_view or _entity_form as a default.

See EntityResolverManager:setParametersFromEntityInformation.

Add upcasting info to your route

Add the following to your route YAML

options:
  parameters:
    my_slug_name:
      type: 'entity:my_entity_type_id'

Replace my_slug_name with whichever text you used in your route within the {}. Usually this is exacly the same as the entity type Id.

Then replace my_entity_type_id text with the entity type Id.

I have written something similar for Views Advanced Routing in its README.


Inserting html just before body of all pages (drupal 7) I want to add some html just before the start of body of all pages. I have managed to do so by adding the html before the body tags in html.tpl.php. It works fine. But it appears in all themes. I want it to appear only for my default theme (i.e. stark). How can I do that?

You should be editing the template file with in the theme. By default stark does not have any template files. You should copy the required template file to the theme you are using and then edit the same there.


How to migrate products display nodes with multiple product references? I have a site being migrated from Drupal 6 to 7. The old site had a home grown system for adding payments to signups for event nodes. We plan to use commerce module to selling the registrations for events going forward.

In the new site, we are planning to import the preexisting SKUs from the old site with feeds but I want to include the product references with the event migration we have written. This migration is already working and just needs to have the product references added to it.

My question is about how to prepare the source data to be mapped when it looks something like this:

nid | sku
---------
1   | a
1   | b
1   | c
2   | a
2   | d

When it seems like it would be better if the data was like this:

nid | sku
---------
1   | a,b,c
2   | a,d

I think if I had the like the second table, I could join the source table

// Join payment_options_skus table
$query->join('payment_options_skus', 'pos', 'pos.nid = n.nid');
$query->fields('pos', array('sku'));

and then map like so:

$this->addFieldMapping('field_registration', 'sku')
     ->separator(',');

Is there a better way to do it using the existing data in the first example table? I would like to limit the number of manual massaging steps needed. Thanks.

I'm in a similar boat, but doing an import for a content type. If data is prepared with multi-value fields as in your second table, I can import the data using Feeds and the plugin 'Feeds Tamper'. So I'm also looking at repeatable and efficient ways to arrange data with multi-fields in CSV format. Saw a post about using Drupal 7 'Feeds Tamper PHP' to do create the multi-valued fields here, https://www.reddit.com/r/drupal/comments/2tumv9/drupal_7x_feeds_tamper_column_values_to_single/co2hesj. <-- Untested, just a reference. HTH.


How to export 'Content-Type' data into JSON? I'm using Drupal 7 and I've created a content type as 'CONTENT_TABLE', which includes multiple fields (COLUMNS) as such: CONTENT_ID, CONTENT_NAME, LARGE_THUMBNAIL, ZIP_FILE...

I want to export the data (each row of the table) into a JSON. I need to use this JSON as an input for another website.

I have tried to look for Node export module, but I'm not sure how to export the data into JSON which can be used as is.

Expected JSON:

{
   "ContentItems": [
      {
         "CONTENT_ID": "123",
         "CONTENT_NAME": "ABC",
         "LARGE_THUMBNAIL": "C:/LargeThumbnail/ABC.jpg",
         "ZIP_FILE": "C:/LargeThumbnail/ABC.zip"
      },
      {
         "CONTENT_ID": "234",
         "CONTENT_NAME": "PQR",
         "LARGE_THUMBNAIL": "C:/LargeThumbnail/PQR.jpg",
         "ZIP_FILE": "C:/LargeThumbnail/PQR.zip"
      }
   ]
}

You could use the Forena module (disclosure: I'm a co-maintainer of it) as your 1-stop-solution (using only 1 contributed module) to:

Build your custom query to fetch the data, whereas these data can be retrieved directly from your Drupal database. Obviously, in this case it's be an SQL to retrieve your CONTENT_ID, CONTENT_NAME, LARGE_THUMBNAIL, ZIP_FILE ...
Format the look and feel of your results (the report) using xHTML (and/or charts if you'd like).
Download the results in any of the typical formats, such as PDF, XLS, CSV, XML, JSON, etc. For any report that you create (using Forena), just add .csv as an extension to the report (output) URL. That contains the CSV equivalent of that report (similar for the other formats).

Example

As a sample, consider the sample report located at /reports/sample.states in your own site (one of the samples shipped with Forena) or in the Simple Table of States in the demo site. Change the URL to /reports/sample.states.csv (= just add .csv to it) to get the same report in .csv format. By adding such .csv to the URL, the result is like so ...

Same technique applies for other supported extensions (export formats), such as:

the PDF version.
the HTML version.
the XLS (MS Excell) version.
the DOC (MS Word) version.
... there are more.

Remark: when building a report, you can also specify for which of these Document Types an hyperlink should be made available in the report.

Direct access to data blocks

All data blocks are also accessible directly via their url, provided you have permission to access that block. Here are a few samples of that (from the demo site), for the sample report located at /reports/sample.states:

in JSON format.
in XML format.

More info

To get an idea how its Custom Queries (SQLs) and/or Report Specifications look like, refer to the example in my answer to "How to retrieve data directly from a Drupal database".
The Forena Video demos and tutorials contain quite some links to live demos.

Getting started

To actually install/configure Forena, make sure to look at the various steps in the Setup Guide that comes with it, which you can find at /reports/help.setup in your own site also after you enabled Forena (similar to what you can see in the demo site). Missing (forgotten) "permissions" and/or "text formats" configurations (if you don't follow the Setup Guide) or the most common showstoppers if you"re new to Forena ...
If you run into "PDO driver support for sqlite not installed", then head over to comment nr 7 in issue #1061436. Here is a summary of it: you only need that for using the "sample database" (the one you can also see in the demo site), which is delivered in SQLite format. So you can use Forena without that support, eg to access your own Drupal database (in MySql fmt). And/or you might want to look at the "drupal admin samples" instead ...


how to get parent tids of a taxonomy term I used this code to get the parent ids , but the result is a huge object .  how do I get the parent id's and term names from the resulting object ?

 $ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);

In $ancestors you'll find an array of the parent terms starting with the term $tid itself:

$ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);
$list = [];
foreach ($ancestors as $term) {
  $list[$term->id()] = $term->label();
}


Using Newsletter module question I have just installed the Newsletter module, and I am wondering if it is possible to allow users to click on a "subscribe" button, and have them signup for a newsletter, rather than have an administrator manually add subscribers.

The newsletter module already has this built in by default.

Go into permissions and enable "Subscribe newsletters" to all roles.

Then, go to the Blocks UI and enable the "Newsletter: Subscribe" into the region of your choosing.


D7 Organic Groups - Set group context in panel I'm using Organic Groups for committee membership on a university intranet. Each group has a landing page created with panels per these d.o instructions. This is working fine, however, I cannot get the panel to pass the group context (gid / group ID) to views contained within the panel. In D6, Group ID (gid) and Node ID (nid) were the same; in D7 they are different. I need to pass the group ID to a view in order to show content generated by that group on the landing page. I've been struggling with this for a while. Am I missing something really basic?

Versions:

Context 7.x-3.0-beta2
Context OG 7.x-1.x-dev
Organic Groups 7.x-1.4
Panels 7.x-3.2
Views 7.x-3.3

Thanks,

Jordan

Ahh. After a week of fighting with this, I figured out that the "OG Members" Content Pane will work after some extensive customization. Somehow, I deleted this in my install, so I didn't know about it. I will use this as a starting point template for future group/panel needs.


Taxonomy Alphabetical Sorting - Nested or Multi-Level Terms I have a problem with the taxonomy list. Currently my website's taxonomy is unsorted, and I want to do an alphabetical sort. It is also a multi-level nested list (3 levels). I heard that using 'Reset to alphabetical' button would sort the list as a whole, and not sorting it within the sub-levels. Is there a way to address that? Currently I'm doing a drag-and-drop sort manually, but there are tons of terms and I'd appreciate any help with that! Thanks!

You may reset the list to alphabetical without losing your hierarchy. While the terms will be sorted alphabetically, those terms that have a parent item will keep that parent item, and so naturally will continue to be displayed under that parent in the hierarchy.

The reset button is found at the bottom of the list terms page in Drupal 7


Define variables for specific template I would like to pass variables to a single specific template file(tpl.php).
My setting is the following:

my_entities.module

function my_entities_theme($existing, $type, $theme, $path) {
  return array(
    'my_entities_property' => array(
      'variables' => array('element' => null),
      'template' => 'my-entities-property'
    )
  );
}

I am using a template file at my_theme/templates/my-entities-property.tpl.php

In the module file I am trying to invoke a preprocess function to add a variable but it is not being invoked.

function template_preprocess_my_entities_property(&$variables) {
  $variables['test'] = "test";
}

How could I make this work?  I followed https://www.drupal.org/node/2275895#comment-8832701 but it seems that I am doing something wrong.

You should put your template in your module as well.

my_theme/templates/my-entities-property.tpl.php

Make sure to update your theme function like this :

function my_entities_theme($existing, $type, $theme, $path) {
  return array(
    'my_entities_property' => array(
      'variables' => array('element' => null),
      'template' => 'my-entities-property',
      'path' => drupal_get_path('module', 'my_entities') . '/templates'
    )
  );
}

Try to use THEME_preprocess_my_entities_property(&$variables) in template.php instead.


Installation fails with missing "file" -plugin error We are creating our own D8 installation profile from previously built site. We exported config and split it to modules, so that our custom modules are defining their own configs.

We've had a lot of issues, basically because we don't know how to debug site installation. XDebug seems to catch nothing. But now I've gotten pretty far, modules do get installed, but the configuration import fails on following error:

[ERROR] The "file" entity type does not exist.

Error gets thrown at Drupal\Component\Plugin\Discovery\DiscoveryTrait.php, but sadly I'm not able to get PHPStorm's debugger to catch that file.

protected function doGetDefinition(array $definitions, $plugin_id, $exception_on_invalid) {
    // Avoid using a ternary that would create a copy of the array.
    if (isset($definitions[$plugin_id])) {
      return $definitions[$plugin_id];
    }
    elseif (!$exception_on_invalid) {
      return NULL;
    }

    throw new PluginNotFoundException($plugin_id, sprintf('The "%s" plugin does not exist.', $plugin_id));
  }

So basically I'd need a way to debug this installation via profile or some way to find out which config file is responsible. I'm finding this unnecessarily difficult, so any help is appreciated.

Cheers,

Janne

Yeah, got this sorted.

The reason for this strange behavior was unsurprisingly misconfigured field in some entity's baseFieldDefinition method.

Someone had used in display plugin configuration "file" instead of correct "file_generic" and for some reason this hadn't been triggered before this. The app has been live for about 6 months and gone through numerous updb's and entity-updates.

This was a nice one. I'll just leave this here in case someone has same mistakes :)


How do you enable translation for a field which was defined by a contrib module? I am trying to enable translation for a field which was defined by a different module.

The problem is this field does not list in the UI. When I checked the definition for this field in hook_entity_field_storage_info I can see the setTranslatable(TRUE) is missing. So I added the same in hook_entity_field_storage_info_alter . After this I can see the field listing in the UI for translation, but when I enable the checkbox and submit the value is not saved.

How can I enable translation for this field?

After a bit of struggle and research, here is the approach taken -

custom_module.install file -

/**
 * Enable translation for workbench_reviewer field.
 * Implements hook_update_n.
*/
function hook_update_xxxx() {
  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $field_storage_definition_node = $entity_definition_update_manager->getFieldStorageDefinition('workbench_reviewer', 'node');
  $field_storage_definition_node->setTranslatable(TRUE);
  $entity_definition_update_manager->updateFieldStorageDefinition($field_storage_definition_node);

}

custom_module.module file -

/**
 * Implements hook_entity_field_storage_info_alter().
 */
function hook_entity_field_storage_info_alter(&$fields, EntityTypeInterface $entity_type) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  // Alter translation settings.
  if (($entity_type->id() == 'node' || $entity_type->id() == 'taxonomy_term') && !empty($fields['workbench_reviewer'])) {
    $fields['workbench_reviewer']->setTranslatable(TRUE);
  }
}

Once running drush updb I can see the field appearing in translation UI with the checkbox enabled.


Problem with breadcrumb on forum I am using Drupal 7, and I want to show the breadcrumb only on the forum, so I used the following code:

$node = menu_get_object();
if (arg(0) == 'forum' || $node->type == 'forum') print $breadcrumb;

The code works, but it gives errors when I visit the admin page.

  Notice: Trying to get property of non-object in include() (line 18 of /srv/www/lusciousanime.com/public_html/sites/all/themes/anime/page.tpl.php).

Does anyone know how to fix it?

That is because, when you visit a page that is not a node page, menu_get_object() (when called without arguments) doesn't return any value. The function could not return any value in other cases too, or not return an object, if the load function returns FALSE, as the code executed from the function is the following one.

  $router_item = menu_get_item($path);
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
    return $router_item['map'][$position];
  }

Your code should be similar to the following one:

$node = menu_get_object();

if (arg(0) == 'forum' || (!empty($node) && $node->type == 'forum')) {
  print $breadcrumb;
}


How do I recover a deleted Views display? I installed a module (FAQ) which provides multiple Views displays, which are based in code. I accidentally removed the master display, and am left with the various block and page displays also created by the module.

Is there any way to retrieve/recover the master display, short of removing/reinstalling the module?

To revert the whole view back to what the faq module provides by default:

Go to the views listing (admin/structure/views).
Click the little arrow next to "Edit" in the operations column.
Click the "Revert" link.
Click the "Revert" button.


How do I migrate translated content? I'm working on migration from an old Drupal 8 site to new Drupal 9 site:
I developed a source plugin to get data from D8 database:
My migration works, but it doesn’t migrate all my contents and get this error:

Drupal\Core\Database\IntegrityConstraintViolationException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '8a7e1ba8-9b75-4813-80d6-99104c82efa5' for key 'node_field__uuid__value': INSERT INTO {node} ("vid", "type", "uuid", "langcode") VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3); Array

When I debug the issue and I have found that there is some translated nodes have the same nid vid only langcode is different like the example bellow.

I added the langcode as id in my source plugin but it doesn't help:
  public function getIds() {
    return [
      'nid' => [
        'type' => 'integer',
        'alias' => 'n',
      ],
      'langcode' => [
        'type' => 'string',
        'alias' => 'n',
      ],
    ];
  }

How can i migrate those nodes ?
Used modules: Migrate/ Migrate plus / Migrate Tools .
Drupal Version : 9.0.3

I have found that there is some translated nodes have the same
nid vid only langcode is different

When using translation, that's ok and normal.

However, what's never ok and not normal:

Duplicate entry '8a7e1ba8-9b75-4813-80d6-99104c82efa5' for key
'node_field__uuid__value': INSERT INTO {node} ("vid", "type", "uuid",
"langcode")

Universally Unique IDentifier cannot be the same, has to be unique. The error is telling you that you have two or more nodes, in the node table, with the same UUID.
So either you have 2 or more Nodes in D8 with the same UUID or perhaps you have a node that was already migrated to D9, but your migration is failing to see that and skip it.
If both are on D8, when you find which nodes have the same/duplicate UUID, via Drupal delete one and re-create it. Just in case, check that the other one didn't get deleted as well because it had the same UUID.


Calling node delete (node_delete_multiple) is not deleting all comments from database When I do a query on the database (SELECT * FROM comment c  where c.nid = 119445765;)  I get a 12 rows in set (0.00 sec)
The I call node_delete_multiple(array(119445765)).
Then I go back to the database and perform the same query SELECT * FROM comment c  where c.nid = 119445765;)  I get a 5 rows in set (0.00 sec).

Now These may be replies to comments since this is a forum. However, how do I ensure they are deleted? Do I have to perform the query myself?

UPDATE:

I have stepped debug this issue here is my notes:
1. node_delete_mutliple -> invokes comment_node_delete
2. comment_node_delete perform this query $cids = db_query('SELECT cid FROM {comment} WHERE nid = :nid', array(':nid' => $node->nid))->fetchCol(); and it correctly returns  all cids  associated with the node.
3. comment_node_delete calls comment_delete_multiple which in turns calls $comments = comment_load_multiple($cids); NOW comment_load_multiple($cids); is not returning the correct number of comments. Surprisingly it is always ommiting comments by a certain user.

I am continuing to debug and will add more info,

Update 2

 $cids = db_query('SELECT cid FROM {comment}
 WHERE nid = :nid', array(':nid'  => 119318471))->fetchCol();
 dpm($cids); // Gives the correct number of $cids
 $comments = entity_load('comment', $cids, $conditions = array(), TRUE);
 dpm($comments); // Is an array with fewer comments than number of $cids

So the problem so far is in entity_load.

Note I failed to mention that the database is migrated from another system and may contain some bad references.

you should check the watchdog table to see if there are any errors. The function calls comment_delete_multiple and with in that functions deletes all the replies as well.

If there was any error during this process it would rollback to a specific point in this case I guess it would be during the delete process of child comments. Tne information would be stored in the watchdog table with type set to comment. This would give you a hint as to why it was not deleted.


How to add CSS classes to a an image which belongs to a content type? I have a content type with an image field; I would like to add CSS classes to those images.

I have looked at the values of the $content variable in node.tpl.php via the dpm(), but I couldn't see any properties/keys related to classes or attributes. Maybe I just couldn't see them, or I didn't know where to look.

I would like to print something like <img src="path-to-image" class="my-classes"> by using print render($content['myimage_field']) in node.tpl.php.

I do not want to use external modules to accomplish this. Is there any theme functions I can override? How do I override them?

You can use hook_node_preprocess in your themes template.php file to add to the 'attributes' array for the node before the variables are sent to your node template. when your field gets built up into html it will then have your class.

If you enable the devel module you can add the following to template.php to see what this 'build array' which is used to render the node looks like.

function twt_preprocess_node(&$vars) {

    dpm($vars);

}

To alter the classes added to your field use something like the following (though look to the above to find out if you are putting your class in the right place).

function twt_preprocess_node(&$vars) {

    $vars['field_myimagefield']['#attributes']['class'][] = 'myclass';

}

Some useful reading:

Render Arrays in Drupal 7
Setting up variables for use in a template
hook_preprocess_HOOK (Drupal 7)


AJAX calls fail when the base URL is set I have installed the Drupal 7.17 security update, and I am having some issues with my site.

If I comment out the $base_url ='www.xxx.com'; line in the setting.php file, the AJAX calls work; when I uncomment that line, the AJAX calls fail.

What could be the reason behind this? how can I get my base_url working again?

Make sure you didn't already include a base URL in your ajax link. For my development site, http://localhost/project1/ajaxlink, the following will work perfectly when no base URL has been set.

$.ajax({url: 'project1/ajaxlink', ...

In case a base URL has been set, the AJAX call is equivalent to the following, which will not work.

$.ajax({url: 'project1/project1/ajaxlink', ...


Use custom profile field in Rules I have a custom Boolean field in user profile called "social reading" in my drupal installation. I want to create an action using rules module which should check if this field is marked or not. But I am not able to find the option in rules.

Under the Rules module add the event that fires After new user is created, then under conditions add a Data comparison, on the first step you should select your checkbox field, on clicking continue you will be presented with the options of this field, that is checked or unchecked.

Now add your action/s under the actions section.

If you want to also check when a user is modified, you should add a rule for the event Existing user is updated.


How to monitor several sites for updates from one central site? I have several Drupal sites and wish to have one site list all of their "status" and available updates. So to start with I am trying to find how to get the available updates.

The central site has access to the databases of all of the others so I am hoping to pull info direct from there but I have no clue where to look.

Is there a table with such information that is auto updated on cron etc?

You can use Drupal Remote Dashboard module for this

  This module is for system administrators. It's a tool to monitor and manage any number of Drupal installations at once and it's built to be extensible by other modules. Since version 2.X this module also comes with the highest level of security where as all communication between the dashboard and each of the cores is AES encrypted, hence the dependency (see below). Optionally the monitoring data will be made visible in nice graphs if the Google Chart API is available.


Form Validation. Ensure Placeholder is not submitted value I have a Drupal registration form with a placeholder set on a first name field. I am trying to get the form to check so that if the placeholder value is the same as the submitted value it will give an error asking them to be sure to enter their first name. Here is my code:

function mytheme_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'user_register_form'){
    $form['field_first_name']['und'][0]['value']['#default_value'] = t('First Name');

    $form['field_first_name']['und'][0]['value']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'First Name';}";
    $form['field_first_name']['und'][0]['value']['#attributes']['onfocus'] = "if (this.value == 'First Name') {this.value = '';}";
    // Alternative (HTML5) placeholder attribute instead of using the javascript
    $form['field_first_name']['und'][0]['value']['#attributes']['placeholder'] = t('First Name');

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

    $form['actions']['submit']['#value'] = t('JOIN US FREE');
  }
}

function mytheme_validate_register_form(&$form, &$form_state) {
  if ($form_state['values']['field_first_name'] == 'First Name') {
    form_set_error('firstname', t('Please enter your first name.'));
  }
}

So the problem I am having is that with the above, every submission is throwing the error. Even if something other than "First Name" is entered. For some reason if ($form_state['values']['field_first_name'] == 'First Name') is returning true no matter what the "field_first_name" value is.

I've looked into using https://drupal.org/project/clientside_validation, but it just seems like overkill for what I'm trying to do.

Thanks for any help.

In your code these two lines may make issue. remove/comment these lines and try.

$form['field_first_name']['und'][0]['value']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'First Name';}";
$form['field_first_name']['und'][0]['value']['#attributes']['onfocus'] = "if (this.value == 'First Name') {this.value = '';}";


views filter: problems with the query object I am trying to get my filter query ready, but I don't understand how any of the query object works. my actual SELECT query looks like this:

SELECT nid
FROM `field_data_field_verein` verein
LEFT JOIN `ds_vereine` ON ds_vereine.tid=verein.tid
WHERE ds_vereine.plz IN
  (SELECT ds_plz_distance.plz_first
  FROM `ds_plz_distance`
  WHERE ds_plz_distance.distance < 20
  AND ds_plz_distance.plz_first=ds_vereine.plz)
OR ds_vereine.plz IN
  (SELECT ds_plz_distance.plz_second
  FROM `ds_plz_distance`
  WHERE ds_plz_distance.distance < 20
  AND ds_plz_distance.plz_second=ds_vereine.plz)
OR ds_vereine.plz IN
  (SELECT ds_plz_ort.plz
  FROM `ds_plz_ort` ort
  WHERE ds_plz_ort.kreis=306)

I honestly do not know how to use $this->query->add_where() function to incorporate this query. All it gives me is a fatal sql error.

you can see my views filter handler functions here: views filter: broken filter - but what's broken about it?

thanks!

Edit

Following Countzero's advice I took the plunge and delved deep into the views-api/code. Two problems I struggled very strongly with were a) joining the required tables the right way and b) implementing the subqueries. I'll shortly explain what I found worked for me.

a) I followed the api-docs and told views my used tables in hook_views_data. Don't. Instead join it in your filter. In short:

$join = new views_join();
$join->construct('table','left_table','left_field','field');
$this-query->ensure_table('table',$this->relationship,$join);

b) It is actually not a problem at all to nest conditions and thus subqueries. It was quite difficult to find out what you have to pass as an argument in the add_where function, so I tell you here for your convenience (;)):

$subquery=db_select('table','table_alias')
  ->fields('table_alias',array('field'))
  ->condition('table_alias.condition_field',20,'<')
  ->where('table_alias.condition_field=base_table.bt_field',array());
$this->query->add_where($group,'base_table.bt_field',$subquery,'in');

Note: The key lies in constructing the select query without executing it and passing it as a value directly.

Your add_where syntax doesn't follow the documentation given in Views code. Here is a paste :

/**
   * Add a simple WHERE clause to the query. The caller is responsible for
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
   * the table already exists in the query.
   *
   * @param $group
   *   The WHERE group to add these to; groups are used to create AND/OR
   *   sections. Groups cannot be nested. Use 0 as the default group.
   *   If the group does not yet exist it will be created as an AND group.
   * @param $field
   *   The name of the field to check.
   * @param $value
   *   The value to test the field against. In most cases, this is a scalar. For more
   *   complex options, it is an array. The meaning of each element in the array is
   *   dependent on the $operator.
   * @param $operator
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
   *   = otherwise. If $field is a string you have to use 'formula' here.
   *
   * @see QueryConditionInterface::condition()
   */
  function add_where($group, $field, $value = NULL, $operator = NULL) {

So basically you cannot inject a complete query like you tried to, but you must use the different methods provided by the objects to carefully construct the different parts.

The less clear part is the group argument : it refers to the groups defined in the filters part of Views UI, the one created when you use Create new groupin the filters contextual menu.


Adding Profile2 fields to user registration I have a custom module that overrides the /user/register page so that in addtion to username and email it also asks for about 10 or so Profile2 pieces of information.

The code I have so far:

    $form['hi'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
      '#title' => t('Additional Info'),
    );

    $form['hi']['l'] = array(
      '#type' => 'fieldset',
      '#prefix' => '
',
      '#suffix' => '
',
    );

    $form['hi']['r'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',

    );

    $form['hi']['l']['h_ph'] = $form['profile_memberlist']['field_home_phone']['und'][0];

The form renders a space for username, email and Home Phone.  I fill out the form, and submit, and I get the following:

  Thank you for applying for an account. Your account is currently pending approval by the site administrator.
  In the meantime, a welcome message with further instructions has been sent to your e-mail >address.

Error message

Notice: Undefined index: profile_memberlist in profile2_form_submit_build_profile() (line 471 of /var/www/html/example/sites/all/modules/profile2/profile2.module).
Warning: array_merge(): Argument #1 is not an array in field_default_extract_form_values() (line 36 of /var/www/html/example/modules/field/field.default.inc).
Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be an array, null given, called in /var/www/html/example/modules/field/field.default.inc on line 38 and defined in drupal_array_get_nested_value() (line 6608 of /var/www/html/example/includes/common.inc).

I've double checked and the memberlist is the name ( machine name) of the profile2 I am trying to get populated.

I had this in my module:

unset($form['profile_memberlist']);

Which is what I needed to do so I could override and theme the way the form elements were presented.  I commented that out but then I got a dual display of form elements, which I was able to disable with the follwing code:

$form['profile_memberlist'] = array(
      '#type' => 'hidden',
);


Is there a module for automatic menu translation? I need to automatically translate menu items into all enabled languages when created.
Is there a module for that or how can I do it programmatically ?

Short answer: no

Long answer: I wouldn't recommend to try to 'automatically translate' any of your content – especially not translating the navigation while keeping the content in the original language. You will probably rather quickly have lots of frustrated users (or no users at all) that don't find content in their language, even when they are 'clicking the right link'.

Additionally you will probably be penalized by search engines for duplicate content.

Maybe you should ask over at the ux forum what people think of the idea? I suppose hardly anybody would recommend to have that type of mis-leading navigation structure on a website.

There are however various modules to tranlate menues (and fields and taxonomies etc.) on the fly, while you are creating new content items – but that you probably already know – and that's probably not what you were looking for.


Entity reference views with Exposed filters I have created a content type Subjects with following fields:

Student ID
Subject Title
Subject Code
Subject teacher

I have also created an entity form for accepting comments from students about subject they study and subject teachers.

I am trying to create an entity reference view and also want to use exposed filter. Reason for using exposed filter is that I want student to provide his student ID so that subjects which he is studying is updated in a select list. I am unable to achieve this.

I am also using Entity Reference autofill module to display the value of Subject Code and teacher in my entity form. The value of Subject code and teacher will be populated based on Student ID and Subject code. Please note one student will be studying more than one subject

I have already created a few contents of type subjects.
My question may appear a duplicate question but I read mostly all answers but nothing is matching my case.

I don't have drupal on me atm to try this out. So consider this an educated guess.

in RELATIONSHIP add student_id referenced entity and click on force relationship.

Then hope that in filters, there is a new option to add referenced entity.


Are rules limited by user roles? I'm looking a bit into the Rules module and it seems to have a lot of possible uses.

However, one thing isn't really clear to me. Are Rules dependent on the current user's permissions?
For example, if a user doesn't have permission to change a certain content node, but he can do something that triggers a rule that changes that content node, will the node be changed or not?

With other words, are rules executed from "administrative" permissions or from the current user's permission?

Update: I've tested out 2 permissions. Creating a content node and editing a content node by using rules when the user doesn't have permission to do so directly. In both those cases Rules doesn't follow the current user's permission and creates/edits the node without a problem. Of course this is by no means exhaustive testing, but for simple node-related operations Rules isn't hindered by the user. (Using the latest version of Drupal and Rules)
If it ever is, I've selected the answer that bypasses the problem.

I've definitely run into problems with this before and it's pretty annoying..

One possible way out of it is to create an extra role with the required permission and in rules, add it, force save user, do stuff, remove role.


Why doesnt my JavaScript run? I'm trying to change the background color of a Colorbox (in which nodes are presented) based on the clicked node. See https://stackoverflow.com/questions/18173943/change-background-color-of-colorbox-using-js-based-on-node-id?noredirect=1#comment26626591_18173943

This doesn't work, although I've confirmed it working for others, and on Fiddle: http://jsfiddle.net/nevster/YSgMx/

Why doesn't this work?

The site is built on latest Zen and I've added the JavaScript code in the script.js file (inside the function that says I should put it there) and added the file in the theme .info file.

JavaScript:

$(document).ready(function () {
$(".colorbox-color").colorbox({
    onComplete: function(){
        var bg = $.colorbox.element().data('bg');
        $('#cboxWrapper').css('backgroundColor', bg);
        $('#cboxLoadedContent').css('backgroundColor', bg);
    }
});
});

I'm using Drupal 7 with Views to show the nodes, together with Colorbox and Colorbox Node.

You shouldn't include the ready function, the latest Zen wraps your script in a custom behavior.  Try putting your code directly inside the custom behavior that is already included in the script.js file.

(function ($, Drupal, window, document, undefined) {

Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {

    $(".colorbox-color").colorbox({
      onComplete: function(){
        var bg = $.colorbox.element().data('bg');
        $('#cboxWrapper').css('backgroundColor', bg);
        $('#cboxLoadedContent').css('backgroundColor', bg);
      }
    });

  }
};

})(jQuery, Drupal, this, this.document);


Give a CCK field a non-editable value? Is it possible, not only to give a CCK field a default value, but also make it non-editable by the user?

I used jquery to do just that.

(function($) {

$(document).ready(function() {

// make the number field uneditable!
$('#edit-field-entry-custom-id-und-0-value').attr("disabled", "true");
});

}(jQuery));

to be safer however, in case someone disables javascript you could add this to your themes template.php

function YOURTHEME_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'YOUR_FORM_ID') {
  $form['FIELD_NAME']['#disabled'] = TRUE;

  // YOU CAN UNCOMMENT THE BELOW FOR EXTRA HELPFUL DETAILS
  // GET FORM ID UNCOMMENT BELOW
  // drupal_set_message("Form ID is : " . $form_id);
  // GET ALL FORM ELEMENTS UNCOMMENT BELOW
  // drupal_set_message(dprint_r($form, TRUE));
 }
}


Hiding Menu Links Based on URL Is there a way to hide menu links on the main menu based on the URL?

For instance, if my URL is 'example.com/undergraduate', the main menu links would be different than if I were to go to 'example.com/graduate'.

This obviously can't be too hard? A module would be awesome.

If you want to have page specific menu system, you can create different menu blocks and put them appropriately.

Considering your example

Main menu is nothing but a menu block, so instead of using main menu block you can have two different menu blocks let say Menu block A and Menu block B

So in block configuration for Menu block A you will put the block visibility to show on "undergraduate" only and similarly put for Menu block b put it as "graduate"

Remember to put the menu blocks in same region as your main menu. You are just toggling menu block visibility on basis of URL.