The correct and optimal way to check language and print field depending on language, without affecting performance I have a multilingual site, and for many reasons (don't ask why) I'm not using the Entity Translation module. Instead, I have 3 separate description fields for each language, and I want to print those depending on the current language. I just wanted to ask if this is the correct and optimal way to print render those fields, and whether or not it will have major implications on site's performance?

Inside my custom node--content-type.tpl.php at the top I put:

<?php hide($content['field_description_nl']); ?>
<?php hide($content['field_description_fr']); ?>
<?php hide($content['field_description_en']); ?>

and later inside the teaser and then again inside the full node I've put:

<?php
global $language;
$lang_name = $language->language;
if($lang_name == "nl") {print render($content['field_description_nl']);}
if($lang_name == "fr") {print render($content['field_description_fr']);}
if($lang_name == "en") {print render($content['field_description_en']);}
?>

Will this work or will it dramatically slow down the site when the traffic starts pouring in?

That's a reasonable way of implementing an alternative language switcher for specific field output.

To keep the logic out of the template, you could add it to hook_preprocess_node instead.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node(&$variables){
  global $language;
  $lang_field_name = 'field_description_'. $language->language;
  if(!empty($variables[$lang_field_name])){
    $variables['description'] = render($variables[$lang_field_name]);
  }
}

Then you can just use print $description in the node--content-type.tpl.php file.

Make sure your cache is different for each language.

See also field_attach_preprocess for how field language translations are added in core.


Column not found: 1054 Unknown column 'revision.revision_user' in 'field list': after Update from 8.2 to 8.4 I'm encountering an error when updating from 8.2 to 8.4, in my case it seems to be related to block_content and maybe also commerce. I've found others with similar issues, but no solid resolution. Has anyone experience this?

Here is the error in the error log:

Uncaught PHP Exception Drupal\Core\Database\DatabaseExceptionWrapper:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column
'revision.revision_user' in 'field list': SELECT revision.revision_id
AS revision_id, revision.langcode AS langcode, revision.revision_user
AS revision_user, revision.revision_created AS revision_created,
revision.revision_log AS revision_log, base.id AS id, base.type AS
type, base.uuid AS uuid, CASE base.revision_id WHEN
revision.revision_id THEN 1 ELSE 0 END AS isDefaultRevision
FROM
{block_content} base
INNER JOIN {block_content_revision} revision ON revision.revision_id =
base.revision_id; Array
(
)
" at /core/lib/Drupal/Core/Database/Connection.php
line 686

When I try to run drush entity-updates, it errors out with this:

block_content entity type :
  The Revision create time field needs to be updated.
  The Revision user field needs to be updated.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while
performing a schema update. [error]
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'revision_created' in 'where clause':
SELECT 1 AS expression
FROM
{block_content_revision} t
WHERE revision_created IS NOT NULL
LIMIT 1 OFFSET 0; Array
(
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage-
>wrapSchemaException() (line 1513 of /core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Fatal error: Cannot use Drupal\entity\BundleFieldDefinition as
BundleFieldDefinition because the name is already in use in /modules/commerce/src/ConfigurableFieldManager.php on
line 8
Drush command terminated abnormally due to an unrecoverable error.
[error]
Error: Cannot use Drupal\entity\BundleFieldDefinition as
BundleFieldDefinition because the
name is already in use in
/modules/commerce/src/ConfigurableFieldManager.php,
line 8
The external command could not be executed due to an application
error.

Any help is appreciated, the site is down

As per this comment, this could be related to Dynamic Entity Reference module as per this bug report.

The solution is to apply this patch or upgrade to the latest version of this module.

To fix the problem manually, you need to rename the field in the database from revision_user to revision_user_int.

Another suggestion from here says to add: $settings['update_free_access'] = TRUE; into your settings file and run /update.php to invoke the database updates again.


Facebook style micro publsher I have been implemented Facebook style micro publsher in my project and now i can post text/media as like Facebook while updating status. Now i need to create a view that contains all posts from every user in a single page . How can i create a view like that ?

There is an default view called statuses_all/facebook_status_all(D6) in statuses/facebook_status(D6) module itself, You can use that one.

When you're enabling FBSMP module it will automatically add FBSMP themed attachment field to all the default views of Statuses/facebook_status(D6). So that view will list down all the statuses with media(If its available.)


Ajax is not working for Drupal comments form I have created two content types slideshow and slides. I am assigning slides to slideshow with the help of node references. One slideshow can contain n number of slides. When I am showing slideshow I am using ajax to show the slides on the slideshow page there are two buttons one is Previous and second one is Next so that user can navigate to the next or previous slides and user can comment on slides means while navigating to the slides user can comment on slides. I have altered the comment form with the help of hook_form_alter so that page get not refreshed at the time when user comments on the form( I am using ajax api for this ). Everything is working for the first slide means ajax is working fine for the first slide and page is not getting refreshed and for the other slides it is not working.
There is one more problem when I was on the second slide and clicks on the previous slide first slide will be displayed and on this page when submits the comment page is getting refreshed.

I searched on the google and other forums I am getting some information related to the Drupal.attachBehaviors() function but I dont know how to use this function.

function lcl_ajax_comment_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'comment_node_article_form') {
     $form['actions']['submit']['#ajax'] = array(
      'callback' => 'lcl_ajax_comment_callback',
      'wrapper' => $form['#id'],
     );
   }
 }
function lcl_ajax_comment_callback($form, $form_state) {
  // Return the actual form if it contains errors.
  if (form_get_errors()) {
    return $form;
  }
  lcl_comments_remove_status($_SESSION);
  $comment = $form_state['comment'];
  $node = $form['#node'];
  $comment_build = comment_view($comment, $node);
  $notify_text = variable_get('lcl_ajax_comments_notify', '') ? theme('lcl_ajax_comments_notify_text') : '';
  // Append comment to root comment wrapper.
  $comment_output = drupal_render($comment_build);
  $commands[] = ajax_command_append('#comment-wrapper', $notify_text . $comment_output);

  // echo "<pre>"; print_r($form_state['values']); echo "</pre>";exit;
  $node = $form['#node'];
  $new_form_state = array();
  $new_form_state['build_info']['args'][] = (object) array('nid' => $node->nid);
  // Don't pull from cache.
  $new_form_state['input'] = array();
  $new_form_build = drupal_build_form($form['#form_id'], $new_form_state);
  $new_form_output = drupal_render($new_form_build);

  $commands[] = ajax_command_replace('#' . $form['#id'], $new_form_output);
  // $commands[] = ajax_command_replace('#comments', $new_form_output);

  return array('#type' => 'ajax', '#commands' => $commands);
}

I had a similar issue with ajax pagination provided by views. I was equalising the heights of the columns using javascript but it was only working on the first page. Any columns loaded via ajax weren't having equal heights calculated. The solution to my problem was to stop using jQuery's once plugin in my behaviour. This was making it execute only once but I needed it to execute infinitely.

Usually a behaviour looks like this:

Drupal.behaviors.ajax = {
    attach: function(context, settings) {
      $('.your-target-element', context).once('ajax', function(){
       var $this = $(this);
       // do stuff with $this
      });
    }
  }

But you want to drop the once plugin like this:

Drupal.behaviors.ajax = {
    attach: function(context, settings) {
       // do stuff
    }
  }


How can I add variables from a preprocessor function to be used in an unformatted view template? The variables I'm adding in my preprocessor function are not visible in the template for the unformatted view I've written. This seems to work fine if the template is formatted (the default).

That is, in template.php I set some variable $foo in the preprocessor…

function themename_preprocess_views_view(&$vars) {
  // Do view-specific preprocessing in here because of http://drupal.org/node/939462
  if ( $vars['view']->name === "viewname" ) {
    $vars['foo'] = 'bar'; // set $foo to be used in viewname templates
  }
}

…such that I can use it in views-view--viewname.tpl.php, <?php echo $foo; ?>. This works just fine.

However, $foo is undefined in views-view-unformatted--viewname.tpl.php.

Why is this? How can I store the results of my preprocessing in a variable I can then use in the template for my unformatted view?

Doing the preprocessing in a function specific to the unformatted view doesn't work because

such a function, themename_preprocess_views_view_unformatted__viewname(), will not be called due to a bug, and
working around the bug by defining its behaviour in, or calling it from, themename_preprocess_views_view() doesn't work

as above, where I seem to make changes to $vars that should be accessible in all viewname view templates,
nor can it be repeated specifically for the unformatted view templates because there's nothing in $vars that can be used to discriminate the unformatted from the default view.

Any help?

Your problem is that the output for the view is built up from the inside-out.  So, the views-view template already has the processed results from the views-view-unformatted template.

You should just be able to implement a template_preprocess_views_view_unformatted(), and do a manual check:

function mytheme_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];

  if ($view->name == 'viewname') {
    $variables['foo'] = 'bar';
  }
}

I don't typically use unformatted output, but I do it somewhat often at the field level.


Should I define all my variables in the module.settings.yml file? With the new Configuration Management System we can create a module.settings.yml file with all the variables that we will use in our module.

Now just to made a test I delete all the content inside my module.settings.yml file (leaving the file empty), I reinstalled the module and it works, so I deleted my module.settings.yml file and I reinstalled my module one more time and, the module works, I can set the variables (the configuration is created) and I can use the variables, even I can export the configuration.

In this scenario I see that you don't need to define your variables even the file is not needed (or maybe I missing something). So, should I define all my variables in the module.settings.yml file?

Talking of the configuration file in config/install, its purpose is setting the default values for the configuration used from the module.

Deleting its content could probably not make much difference if the default values are FALSE, NULL, or an empty string. In the other cases, its content would make a difference.


Webform email component created programmatically I am trying to build an email confirmation utility into a web application. For some other project I might just use jQuery to insert a new text field beneath my email field and compare their input as soon as the user finishes typing into the created textfield.

The problem is the email authentication will fail if a user does not have javascript enabled on his/her browser.

To overcome this problem, I want to use code to programmatically create and insert a second textfield immediately after the actual email field and compare their input when the user submits.

What I don't know is what webform hook(s) I can use to create an email component.

Can anyone help with some information and/or code samples, please?

$email = array(
  'nid' => $node->nid,
  'email' => 'name@example.ch',
  'subject' => 'default',
  'from_name' => 'default',
  'from_address' => 'default',
  'template' => 'default',
  'excluded_components' => array(),
);
webform_email_insert($email);

Check this post for more info.


how to set up checkbox value while creating a node Here is my code. I have a problem with while creating node. There are three checkboxes which user have to select; only the last checkbox of data (black color) is saved for node.

What is wrong with my code?

$node = new stdClass();
$node->type = 'product';
node_object_prepare($node);

$node->title    = $title;
$node->language = LANGUAGE_NONE;

$node->field_operator['und']['0']['tid'] = 135;// white color
$node->field_operator['und']['0']['tid'] = 136;// blue color
$node->field_operator['und']['0']['tid'] = 162;// black color

node_save($node);

Supposing the field can accept multiple values, the code should be similar to the following one.

    $node->field_operator['und'][0]['tid'] = 135;
    $node->field_operator['und'][1]['tid'] = 136;
    $node->field_operator['und'][2]['tid'] = 162;


Module for fedex shipping for drupal 7 I am using Drupal Commerce version 7.

I came across requirement for FEDEX shipping module. I installed it but in it's requirements, uc_quote is missing. I didn't find this module for Drupal 7.

I searched for this but it is supported only in Drupal 6.

uc_quote is a part of the main Ubercart module. You can find it in the directory structure of ubercart at ubercart/shipping/uc_quote. And it is obviously present for Drupal 7 (as part of Ubercart 3.1).
For commerce shipping there is a sandbox project, but I haven't tested it.


How to prevent a Rules Action to happens twice using Rules Event User account validated? I've set up a rule that sends you an HTML email when you activate your account. It seems to throw back a notification about:

  Notice: Undefined variable: attachment in SmtpMailSystem->mail()

But it seems to send the email anyway, but what I don't understand is that I receive 2 emails everytime I test it. I've checked the log files and it seems to log that an anonymous user has used the validate URL to confirm their email address, then sends the email. Then it opens up a session for this new user, and then sends them the email again.

I've set the rule to run on 'When the user account is activated' and if I turn the rule off I get no emails, so it isn't that there is anything else sending an email too, it is only this rule, it just seems to do it twice.

Can anyone offer a solution?

I'm using the SMTP, Mimemail and Mail System modules

If anyone needs me to post any specifics about the rule, or the error or the email text etc, just ask, I just didn't want to flood the post with huge blocks of code if it might not have helped.

EDIT1

Log file output (obviously I have flipped the order for it to make sense, log files are recent most recent first)

New user: unset_username (fake@email.com). // When I create a new account
Sending mail to: "Firstname Lastname" // Emails out the verification request
E-mail validation URL used for Firstname Lastname with timestamp ...
Sending mail to: "Firstname Lastname" // Emails out the confirmation email once
Session opened for Firstname Lastname.
Sending mail to: "Firstname Lastname" // Emails out the confirmation email again

EDIT 2

Determined the issue is nothing to do with the emails, tried re-creating the rule but sending an output to the page rather than sending HTML email, it was confirmed that this rule runs twice (and hence nothing to do with emails in particular) by the fact that the message was output twice as well.

UPDATE

As Molot has pointed out this isn't anything to do with emails, just the rule happening twice. I'll leave the text above incase anyone else is trying to send out emails on verification and they come to the same conclusion I did, so they can find this and understand whats happening.

Understanding what's happening

Your question seems like a variation (IMO not a duplicate) of the question 'Why is my rule that reacts on event "After updating an existing user account" firing twice?'. The accepted answer in that question might help to understand your issue (what's causing it) also, ie:

  some other module code is calling a user_save on hook_user_update triggering the rules event a second time.

If I was to debug this, I'd disable all contributed modules (except "Rules" and "Entity API") to check if it's indeed a contributed module (I don't expect it to be core). And then re-enable the contributed modules one by one until the issue comes back. As soon as it comes back, you pinpointed the contributed module causing the issue, and you can start working on a possible remedy for that.

Workaround 1

That question also has another answer with a very interesting workaround, with an image which looks like so (a picture is worth more then 1000 words):

Workaround 2

Another workaround to prevent this issue from happening, is to improve your existing rule to make it similar to the rule included in my answer to "How to implement a Rules Condition like [account:last-login] = never?". More specifically:

Add a Rules Condition like: User does NOT (!!!) have a role with role id = "4".
Add a Rules Action like: Grant User the role with role id = "4".

So this improvement of your rule will check if the user does not yet have some (designated) role with role id = "4" (adapt to whatever role id that fits your case, and make sure this role is NOT yet granted when activating a new user id). If that's the case, then the user is granted that role. With this improvement to your existing rule, this is what will happen:

The 1st time your Rules Actions will still be performed (and grants the designated role).
the 2nd time not ALL of your Rules Conditions will be satisfied (since the designated role was granted before), and therefor your Rules Actions will no longer be performed.

In other words: "this will prevent your Rules Actions to happen twice" (as in your question).


Drupal 7 and Ubercart - admin approve sale before payment Drupal 7.36 & Ubercart 3.0-rc4.

My client needs to vet users purchasing products from an Ubercart shop. The idea is that when the user completes the checkout, the user does not go to a payment gateway - but instead, the admin receives an email notification saying someone wishes to make a purchase. the admin then goes on to the site and authorizes the sale, sending an email to the user telling them they can now return to the site and complete the purchase and pay.

I've looked at rules, but it appears for fall slightly short of what i need.

Are there any contrib modules, or and know workarounds for this?

I think you can do this by using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

You need to create a rule with below condition :

  Condition : Data comparison for the order state "Approved by admin" with
  a Negate option (checkbox in bottom).

So if you change the order state to "Approved by admin" this rule will not trigger anymore because this condition will return FALSE.


What are Drupal Apps? I've been seeing the use of Apps. What are drupal apps?

Are they just glorified Features with a backend UI? What are the differences between the two on a lower level? The apps project page only gives a pretty high level understanding.

Have you read the Open App Standard http://groups.drupal.org/open-app-standard/oas ? Here's an excerpt that might help:

  What is an app? Before we say what an App is it’s helpful to know who
  it’s for: An App is for the end user, typically a non-technical user
  of a Drupal site such as the site administrator....

  ...Technically, an App is a collection of new or existing Drupal
  functionality, including Modules, Features, and Themes along with some
  simple additional code that publishes the existence of the App to the
  rest of the App infrastructure.

  What distinguishes an App from a Module or Feature is that the App
  includes all of the additional polish, end-user UI, configuration UI,
  sample content, and documentation that are needed to fully meet a
  specific need. Whereas Modules and Features are more developer-centric
  and provide building blocks for larger functionality, Apps are larger
  blocks of completed functionality.


Testing field value in twig template In my twig theme - I'm attempting to test the value of the field "field_left_image_front" - which is either "Yes" or "No"

{% if content.field_left_image_front.0 == "Yes"  %}

{% else %}

{{ content.field_left_title.0 }} {{ content.field_left_image_front.0 }}

{{ content.field_left_body }}

{% endif %}

A few bits of info:

field_left_image_front is a select list/list item in the CMS
I'm testing the value by outputting it in h1 tag - so I can see that it's "Yes"
Despite being "Yes", it's outpitting the text description and ignoring the image.

Is there something I'm doing wrong with the conditional?

Use node (if this is a node template) to get the field value, see Conditional statement doesn't work in node.html.twig. Another reason in this case is that Yes/No would be translatable in a multilingual site, while the field value from nodeis the untranslatable left key of a select list.

If it is not a node template look at the variables listed at the top of the template, for example paragraph.html.twig:

/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

Here the variable for the entity is paragraph and for the render array content.

So use {{ content.field_example }} to print fields and {{ paragraph.field_example.value }} to get field values from the database.


Taxonomy or database table? My problem is not technical but structural.

The idea is that users can submit an ad (to sell a car for instance) with entityForm, or webform.

To define the car to sell, I want a predefined list to avoid misspelled words.

The first solution I tested was to use Taxonomy like that:

-Audi
--A1
--A3
--A4
-Seat
--Ibiza
--Leon

I used "Hierarchical Select" and then "Simple Hierarchical Select" and even "Term Reference Tree" but my problem is still the same.

When I want to use a view to display the EntityForm Submissions, it shows the car in one column like that:

Car

.Audi
..A1

.Audi
..A3

And I want it on 2 columns like that:

Brand | Model

Audi  | A1
Audi  | A3

Does taxonomy allow that and how?

Should I use a database table with another module?

Thanks for any help!

You don't need any changes to your database, with HS Or SHS you already store enough data to built a template answering your needs.

From my point of view, once your view is configured, you can alter the display of your field while overriding the default TPL file.

From the view edit page, if you go into "Theme: Information", you can find the name of the file you need to create and place into your theme folder.

The file name should look like this:

views-view-field--name-of-your-view--name-of-your-field.tpl.php

As a base for you file, you should use views-view-field.tpl.php (located in sites/all/modules/views/theme). In that template, there's some variables available to help you build what you want (like $row or $field).

If you have Hierarchical Select installed, you can simply render the field, it will display data the way you want.

Here's some untested code:

$field = field_view_field('entity_name', $fully_loaded_entity, 'your_field_name');
print render($field);

For that chunck of code to work, you need to specify if you're working with a node, user or term, pass the loaded entity and give the corresponding field name.

The rendered HTML should be enough to build something like this (made with the exact same method):


Entity filed query for sorting by title and weight both? "i need to display data in alphabetical oredr if weights are in same number(1,1,1)condition ,if weights like(1,2,3) condition need to display data weight based ASC order" i'm using below code alphabetical sorting working good in same weights condition, but weight based condition not working please help me

               $query = new EntityFieldQuery();

               $query->entityCondition('entity_type', 'node')

              ->entityCondition('bundle', 'closing_team')
              ->fieldCondition('field_homebranch', 'tid',   $node->field_closing_team_categories['und']['0']['tid'])
              ->fieldCondition('field_featured','value','No','=')
              ->propertyOrderBy('title', 'ASC');

              $result = $query->execute();
              $nids = array_keys($result['node']);
              $news_items2 = node_load_multiple($nids);
                /*echo "<pre>";
                print_r($news_items2);
                echo "</pre>";exit;*/

             function element_sort1($a, $b) {
             $a_weight = (is_array($a) && isset($a ['#weight'])) ? $a ['#weight'] : 0;
             $b_weight = (is_array($b) && isset($b ['#weight'])) ? $b ['#weight'] : 0;
             if ($a_weight == $b_weight) {
              return 0;
                }
            return ($a_weight > $b_weight);
                }

?>

This is more of a straight PHP question than a Drupal question, but it looks as if you have a bug in your value comparing function. It should return 1 if you want $a to sort greater than $b, it should return -1 for $b to sort greater than $a, and it should return 0 if the items should sort equally. But your function will only ever return 0 or 1. Try replacing your last return statement with return ($a_weight > $b_weight) ? 1 : -1;


How do I resolve this installation error? I am getting the following error while installing Drush with composer require drush/drush.

  Using version ^8.1 for drush/drush
  ./composer.json has been updated
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Your requirements could not be resolved to an installable set of packages.

  Problem 1
  - drush/drush 8.1.0 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.1 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.2 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.3 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.4 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.5 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.6 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.7 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.8 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - drush/drush 8.1.9 conflicts with drupal/drupal [No version set (parsed as 1.0.0)].
  - Conclusion: don't install drush/drush 8.1.12
  - Conclusion: don't install drush/drush 8.1.11
  - Conclusion: don't install drush/drush 8.1.10
  - Conclusion: don't install drush/drush 8.x-dev
  - Installation request for drupal/drupal [No version set (parsed as 1.0.0)] -> satisfiable by drupal/drupal [No version set (parsed as 1.0.0)].
  - Conclusion: remove phpdocumentor/reflection-docblock 3.1.1
  - Installation request for drush/drush ^8.1 -> satisfiable by drush/drush [8.1.0, 8.1.1, 8.1.10, 8.1.11, 8.1.12, 8.1.2, 8.1.3,
  8.1.4, 8.1.5, 8.1.6, 8.1.7, 8.1.8, 8.1.9, 8.8.x-dev, 8.x-dev].
  - Conclusion: don't install phpdocumentor/reflection-docblock 3.1.1
  - drush/drush 8.8.x-dev requires phpdocumentor/reflection-docblock ^2.0 -> satisfiable by phpdocumentor/reflection-docblock [2.0.0,
  2.0.0a1, 2.0.0a2, 2.0.0a3, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.0, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.0a1, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.0a2, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.0a3, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.1, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.2, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.3, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.4, 3.1.1].
  - Can only install one of: phpdocumentor/reflection-docblock [2.0.5, 3.1.1].
  - Installation request for phpdocumentor/reflection-docblock (locked at 3.1.1) -> satisfiable by phpdocumentor/reflection-docblock [3.1.1].

  Installation failed, reverting ./composer.json to its original
  content.

Had the same problem started from D8.4beta1.

Solved by switching to Drush 9 with:

composer require drush/drush:^9


How to create footer links in drupal 6 I am doing a site in Drupal 6, and I need to create footer links which needs to be displayed in the footer.

How can I create it?

Create secondary links in admin/menus/secondary links.

Once completed, go to blocks/list/, look for your secondary links, and place them in the footer block region.


Search API Solr Configured, Content Indexed, No Search Results I'm running a Drupal 8.6.13 site with Search API 8.x-1.12 and Search API Solr Search 8.x-2.7. Everything seems to be properly installed and configured - my Solr admin panel shows a configured core and everything looks fine on my Drupal admin interface. I have the index set to process the body fields of my content and custom blocks using the fulltext type; I have 198 items indexed:

{ "response":{"numFound":198,"start":0,"maxScore":1.0,"docs":[] }}

The problem is that a search for a word that definitely appears in my content isn't producing any results. I'm using the config files from the Search API Solr Search module.

Solr Search Devel shows the request being sent to the server and an HTTP "200 OK" response being received. The logged response was:

{ "response":{"numFound":0,"start":0,"maxScore":0.0,"docs":[] }}

What else could I be missing?

Some more detail:

I can retrieve documents from the index using a command line query, like this:

$ curl "http://localhost:8983/solr/mycore/select?indent=on&q=:"

Here's an example of one of the returned documents:

  {
    "id":"6a1a2p-content-entity:node/100:und",
    "sm_context_tags":["search_api_X2f_index_X3a_content",
      "search_api_solr_X2f_site_hash_X3a_6a1a2p",
      "drupal_X2f_langcode_X3a_und"],
    "tm_body_1":["Ignition Timing (Vacuum advance disconnected, lines plugged) 6° BTDC Dwell Angle 30-33° Point Gap .020\" Spark Plug Gap .035\" Idle RPM * (Manual Transmission, no A/C) 725 Idle RPM * (Manual Transmission, with A/C) 725/500 ** Idle RPM * (Automatic Transmission, no A/C) 675 Idle RPM * (Automatic Transmission, with A/C) 675/500 ** Firing Order 1-5-4-2-6-3-7-8 * Set idle speed with headlights on high beam, air conditioning off. ** Higher RPM, solenoid energized. Lower RPM, solenoid de-energized.  "],
    "spell":["Ignition Timing (Vacuum advance disconnected, lines plugged) 6° BTDC Dwell Angle 30-33° Point Gap .020\" Spark Plug Gap .035\" Idle RPM * (Manual Transmission, no A/C) 725 Idle RPM * (Manual Transmission, with A/C) 725/500 ** Idle RPM * (Automatic Transmission, no A/C) 675 Idle RPM * (Automatic Transmission, with A/C) 675/500 ** Firing Order 1-5-4-2-6-3-7-8 * Set idle speed with headlights on high beam, air conditioning off. ** Higher RPM, solenoid energized. Lower RPM, solenoid de-energized.  "],
    "site":"http://example.com/",
    "sort_title":"PRD2\u0005\u000eRH\u0004NH2.:4:.*P:FDN\u0000",
    "_version_":1630197909793275904,
    "ss_search_api_datasource":"entity:node",
    "sort_body_1":":6D:P:FD\u0004P:B:D6\u0004\t<8e>T*.RRB\u0004*0T*D.2\u00040:N.FDD2.P20\u0006\u0004@:D2N\u0004H@R6620\t<90>\u0004\u001f\fS\u0004,P0.\u00040V2@@\u0004*D6@2\u0004\u0019\u0013\u0005\u000e\u0019\u0019\fS\u0004HF:DP\u00046*H\u0004\b\u0013\u0017\u0013\tx\u0004NH*L>\u0004H@R6\u00046*H\u0004\b\u0013\u0019\u001d\tx\u0004:0@\u0000",
    "index_id":"content",
    "ss_title":"Tune-Up Specifications",
    "hash":"6a1a2p",
    "ss_search_api_id":"entity:node/100:und",
    "timestamp":"2019-04-07T22:57:56Z",
    "ss_search_api_language":"und"}

So then I tried a query using a term found in the content above:

$ curl "http://localhost:8983/solr/mycore/select?q=solenoid"
{
  "response":{"numFound":0,"start":0,"docs":[]
  }}
$

Why might the second query fail to produce results if the search term is included in the document as shown in the full list of results?

Few observations that might help you.

Term "solenoid" is only listed in 2 fields "tm_body_1" and "spell". Are you sure your solr instance is searching on these fields ?
Can you try creating a view and see if you get some response / results ?
Not sure, but did you copied over the Solr config files that are part of the module(search_api_solr), in your solr instance ?
Which version of Solr you are using, as module version 8.x-2.7 supports 6.x and 7.x version - https://git.drupalcode.org/project/search_api_solr/tree/8.x-2.7/solr-conf.

Hope that helps !!


Can an AJAX form request replace elements of different types? I'm trying to write an AJAX form in Drupal 8. I managed to get a simple example working yesterday, but today, my work fails without error. I was wondering whether anyone here could spot my error.

Here are the relevant excerpts from my OverviewForm:

public function buildForm(array $form, FormStateInterface $form_state) {

  ...

  $form['job_id'] = [
    '#weight' => 1,
    '#title' => 'Job',
    '#type' => 'select',
    '#options' => $formatted_jobs,
    '#ajax' => [
      'callback' => '::showFiles',
      'event' => 'change',
      'wrappper' => 'jobfiles'
    ]
  ];

  $form['jobfiles'] = [
    '#weight' => 2,
    '#title' => 'Files',
    '#type' => 'html_tag',
    '#tag' => 'span',
    '#value' => 'Please make a selection above',
    '#attributes' => [
      'id' => ['jobfiles']
    ]
  ];

  return $form;
}

public function showFiles(array &$form, FormStateInterface $form_state) {
  $job_id = $form_state->getValue('job_id');
  $elem = [
    '#weight' => 2,
    '#type' => 'item_list',
    '#items' => $this->_files($job_id),
    '#attributes' => [
      'id' => ['jobfiles']
    ]
  ];

  return $elem;
}

The list of jobs populates correctly, but when I select one, the initial jobfiles span isn't replaced with anything. I'd expect it to at least disappear when I select a value from the select. Thanks in advance!

I should try using #prefix/#suffix for wrapper instead the element itself. Also IMHO it's not a good idea mess around with the elements you send during build. Take in mind the the build is done every time you render the form, even for AJAX calls. A possible solution could be hide the second element using Form States API and put the Please make selection in your prior element.

public function buildForm(array $form, FormStateInterface $form_state) {
  // Code excerpt.
  $form['job_id'] = [
    '#weight' => 1,
    '#title' => t('Job'),
    '#type' => 'select',
    '#empty_value' => t('Please select a job'),
    '#options' => $formatted_jobs,
    '#ajax' => [
      'callback' => [get_class($this), 'showFiles'],
      'wrapper' => 'ajax-wrapper',
      'event' => 'change',
    ],
    '#required' => TRUE,
  ];

  // Render a hidden and empty list.
  $form['jobfiles'] = [
    '#weight' => 2,
    '#title' => t('Files'),
    '#type' => 'item_list',
    '#items' => [],
    '#prefix' => '
',
    '#suffix' => '
',
    '#attributes' => [
      'class' => ['invisible']
    ]
  ];

  return $form;
}

public function showFiles(array &$form, FormStateInterface $form_state) {
  $job_id = $form_state->getValue('job_id');
  $form['jobfiles']['#items'] = $this->_files((int)$job_id);
  // Remove the 'invisible' class.
  $form['jobfiles']['#attributes']['class'] = array_filter($form['jobfiles']['#attributes']['class'], function($v) {
    return $v != 'invisible';
  });
  // You could also return the element instead.
  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand('#ajax-wrapper', [$form['jobfiles']]));

  return $response;
}

Hope this may help you.

Update:
Replace $element with $form. Also worth checking the answer provided by @joshua-moore as it is valid too.


Is possible for a module to know when one of its blocks is being output on the dashboard, and change the content of that block? Drupal 7 has a new core module (dashboard.module) that allows users with the right permissions to add blocks defined from third-party sites to the dashboard, which is shown as overlay on the current page.

Is it possible for a module that implements blocks to know when the block is being rendered on the dashboard?
The idea would be to change the content of the block, and make it smaller (for example).

You could check the url argument that the block is displayed on and then if it matches an expected pattern i.e. /dashboard then you can alter the contents of the block. This solution only really works if you've coded the block yourself.

Update: This method will still work, although I'm not familiar enough drupal 7s dashboard module to comment further. The only thing I would suggest is to output page variables and see if there is anything set by dashboard module.


Is it possible to call a function but disable that functions hook calls? In this answer I wanted to alter a URL using hook_file_url_alter(), and within my implementation of that hook I needed to convert the URI to a URL.

Normally this would be done with a call to file_create_url() but that is not possible here as it would trigger my hook causing an endless loop.

I can see at the top of drupal_alter() it is using the static variable $drupal_static_fast which makes me think maybe there is a way of using this to temporarily disable a hook being called, but I'm not sure.

You can't stop the hooks from being invoked unless you edit drupal_alter (or file_create_url) directly.

But you can use static vars to short circuit your own implementation so it only runs once for a given $uri:

function MYMODULE_file_url_alter(&$uri) {
  $processed_uris = &drupal_static(__FUNCTION__, array());

  if (!in_array($uri, $processed_uris)) {
    $processed_uris[] = $uri;

    // Even though this call will re-invoke the current function, the URI has been
    // processed, so no infinite loop.
    $foo = file_create_url($uri);
  }
}


creating a static front page Please bear with me, I am new to Drupal (I've been adding content for 3 years, now been asked to edit some structural aspects of a site.)

I've been asked to add a static frontpage/homepage to an existing Drupal site with no menus, no headers. This would be a very basic HTML page with an image and 2 links which connect to English and French versions of the main Drupal site.

Is the best way to use a module? I see there is a module called Front Page, but it hasn't been updated in almost 2 years (maybe this is normal?). Is there a more basic way to get a static front page in Drupal, without installing another module?

Also, I am concerned about what will happen to the URL of the current front page if I override it with the Front Page module.

Thank you!

You can add page--front.tpl.php in your enabled theme folder and clear the cache


How to use Font-your-face fonts with CKEditor? I am using some Google fonts via the Font-your-face module on my D7 website as well as CKEditor for content editing. To achieve full wysiwyg effect I would like to display the text in editor with these Google fonts. However I can't find the way to to this.

Should I give a try to the appropriate CKEditor plugin or is there a way to solve this on Drupal level? Any ideas?

This looks like a long awaited and unanswered issue - https://www.drupal.org/node/1234030 - however I have found a page that describes how you can manually updated your CKEditor fonts list.

http://www.zyxware.com/articles/3692/drupal-how-to-add-fonts-in-ck-editor

I think this seems a bit too much, you would think that there would be a better system in place to support more fonts dynamically. There are apparently some hooks with the WYSIWYG module and Font Your Face - however as far as my knowledge goes CKEditor works better on it's own than as a part of WYSIWYG.


Layout custom forms using Panels Can I use the Panels module to layout a custom form?

I've created a custom form and I'm loading it in a menu callback using a function like this:

function _MODULE_menu_callback_function() {
  return drupal_get_form('_my_custom_form');
}

My ultimate goal is to use the Panels UI to rearrange the form fields into different panes so that I can easily mix in other elements.

I tried to use Page Manager: Existing Pages to accomplish this, but it simply brings the form in as a whole.  I cannot break the fields apart into different panes using this module.

Is this possible with Panels?

You need to create fieldable entity type to make form as you wish and make your custom form by adding fields to it. Than this fields will accessible in page manager UI.


In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results? In nodereference field of a content type, Is it possible to show the content type name added with the autocomplete results ?

Example :

I have a content type named Article which has a node reference field (Related content -> field_related_documents), So that this article will referenced to other nodes.

While creating an article, by entering 'help' in 'field_related_documents' I am getting autocomplete results (titles of referenced nodes) like below

helpsystems - rules
Decision management Help
Using help menu
Help support glossary

Instead, I like to show results like below

Page | helpsystems - rules
HelpSystems | Decision management Help
Page | Using help menu
Document | Help support glossary

ie) autocomplete results should display title of other nodes added with their related content type.

How should i achieve this ?

I created a new custom Module nodereference_patch with below hook

/*
 * Altering nodereference/autocomplete menu using menu alter
 */
function nodereference_patch_menu_alter(&$items) {
  $items['nodereference/autocomplete']['page callback'] = 'nodereference_patch_new_nodereference_autocomplete';
}

Then, I copied the nodereference_autocomplete function into your custom module, changing it's name to nodereference_patch_new_nodereference_autocomplete.

Then I changed this line:

$matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';

to

$matches[$row['type'] . " | " . $row['title'] . " [nid:$id]"] = '
' . $row['type'] . " | " . $row['rendered'] . '
';

I copied _nodereference_potential_references function from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references

Then I changed the following line as

$references = _nodereference_potential_references_standard($field, $string, $match, $ids, $limit);

to

$references = _nodereference_patch_potential_references_standard($field, $string, $match, $ids, $limit);

I copied _nodereference_potential_references_standard from nodereference.module to custom module and renamed it as _nodereference_patch_potential_references_standard

Then I added 'type' element to $references[]. ie) changed following array from

$references[$node->nid] = array(
    'title' => $node->node_title,
    'rendered' => check_plain($node->node_title),
);

to

$references[$node->nid] = array(
    'title' => $node->node_title,
    'type' => $node->node_type,
    'rendered' => check_plain($node->node_title),
);


How do I ensure the Content-Type header is present? I need to set my Content-Type header to "application/json; charset=utf-8" in Services responses.

I have tried drupal_add_http_header() in my callback, in _services_request_postprocess_alter() and in a custom ServicesFormatterInterface:

class ServicesJSON_UTF8Formatter implements ServicesFormatterInterface {
  public function render($data) {
    // json_encode doesn't give valid json with data that isn't an array/object.
    if (is_scalar($data)) {
      $data = array($data);
    }

    drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');

    return json_encode($data, JSON_UNESCAPED_UNICODE);
  }
}

Sometimes the header gets set, and sometimes it comes back just "application/json" without my addition. Where can I set this to make certain my header makes it into the response?

Try this ( at the end of Your service callback function ):

drupal_add_http_header('Content-type','application/json; charset=UTF-8');

echo drupal_json_encode($response);


Output JSON views_field_view with Services? I am using Services Views to render JSON for a view that has a views_field_view. The JSON output from Services for the views_field_view field is currently a rendered HTML view. How can I make views_field_view render a JSON version of the output to be included with the parent view's JSON output?

UPDATE:

The content in the sub-view has a Geofield, which is causing problems in a Services display.
The view is set as an unformatted list. A Page display looks like this:

node_title: Marquette
Geofield: 44.977297200000, -93.270110200000

Then if I create a Services display with the same view (same fields), the output looks like this:

  stdClass::__set_state(array(
     'node_title' => 'Marquette',
     'nid' => '1335',
  ))

In a Services display, anything I try to do with a Geofield just outputs the nid.

This was an issue with custom fields in Services Views that has been fixed in the latest dev version.

https://drupal.org/node/1647270


Setting up permissions for non-registered users How do I set permissions for non-register users?

Step 1: I registered Drupal 7 in my system.

Step 2: I wrote a module for user_register().

Step 3: When I call the menu callback an access denied error  is shown.

How should i set permission to non-register users to register?

In your menu item definitions, you can specify TRUE as the access callback to make the item always accessible.

<?php
  function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'access callback' => TRUE,
    );
    return $items;
  }

?>

See http://api.drupal.org/api/function/_menu_check_access/7

Hope this helps,
Mark


Running a queue worker without using cron tasks I implemented hook_queue_info() with the following code.

function ecc_general_queue_info() {
  $queues = array();
  $queues['adding_checklist'] = array(
    'worker callback' => '_ecc_general_apply_queue',
    'time' => 60,
  );
  return $queues;
}

I create  items for the queue with the following code.

$queue_factory = \Drupal::service('queue');
$queue = $queue_factory->get('adding_checklist');
$queue->createItem([$node, 'insert']);

The callback function is the following.

function _ecc_general_apply_queue($item) {
  // Some code here.
}

I want to run this callback for each item in the queue. How can I process the queue to execute its worker callback for each item?

I don't want to use cron tasks for processing the queue.

Queue is processed by cron through core. You can also use Drush and Drupal Console to run queue items as well.

Drush:

drush queue:list to get the available queues.

drush queue:run to run a single item.

drush queue:delete to clear a queue.

Drupal Console:

drupal debug:queue to debug your queue.

drupal queue:run <name-of-the-queue> To run a single item.


How do I redirect users to an external URL? I implemented a controller class in Drupal 8, which redirects to an external site.  If I use \Symfony\Component\HttpFoundation\RedirectResponse, I get this error.

  Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

Using \Drupal\Core\Routing\TrustedRedirectResponse, I get this error.

  The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
  Returned object class: \Drupal\Core\Routing\TrustedRedirectResponse

What should I do?

Define a controller and redirect to external URL.

Use TrustedRedirectResponse class in case you know that you want to redirect to an external URL. Example below:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
class ExampleController extends ControllerBase {

  public function example() {
    return new TrustedRedirectResponse('https://google.com');
  }
}


Regenerating images after new image style I created a new image style. When I inspect my code, the image style has been applied but it doesn't find the image. The image and the new folder in sites/default/files/styles hasn't been created?

Whats wrong, how do I generate my new image(s)?

Drupal creates derivatives images "on the fly" based on a defined image style. The act of creating a new style does not generate any images. Rather, the first time an image is requested using that style it will be generated and saved in sites/default/files/styles/{stylename}/path/to/image.jpg.

If you (for example) create a view that displays nodes with images using your newly defined image style, then as soon as you go to a page with that view the images will be generated.


Send email after 100 webform submissions I'd like to be able to send an email to the nth person (or every n people) that submit a specific webform. I've tried utilizing rules for this, but I can't seem to expose webform submission data to rules (using submission id). Any thoughts on how this could work through rules? Any suggestions for alternatives?

Have you tried using Webform Rules ?

This should expose webform results to rules, then create a new rule with conditions "if submission ID is 100, 200 etc" then... action: Send email.

You would either need a way to find the nth of 100, or depending on how many submissions you are expecting, just check against a comma separated list, eg "100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200" etc


User activity not showing in the personal log but is in the public log using Heartbeat module I have installed the Heartbeat module (6.x-4.11) with Heartbeat activity and Heartbeat rules enabled. If a user adds a comment to the site the activity is being logged in the database and showing on the public heartbeat page. However, looking at the user's personal heartbeat it shows as "no activity yet."

The uid and uid_target values in the database table are both "0" which I am guessing is not right (surely these should be the user's id).

Is there a configuration setting that controls whether the activity appears against the user?

I'm attempting to use this module as a way of allowing users to see how active other users are on the site; so it is important that the activity appears against the personal heartbeat.

Finally sussed it. I needed to go into the Triggered Rules page and change the "do" behaviour for the "Heartbeat: When a user adds a comment" rule.

Setting "User Id" to "[comment_author:uid]" links the activity log to the author, and "Node context Id" to "[node:nid]" links to the node being commented on. After changing these the activity showed up in both personal and public Heartbeat activity streams.

Hope this helps somebody else who may be struggling with this.


Using form elements for various forms in Drupal 7 I am building a site with several forms that partly contain identical building blocks (for example a fieldset 'payment details'). Ideally, I would like to design my form elements separately and then inject them into each form. My idea was to create functions with &$form as parameter, as in the following code:

function payment_details(&$form) {
  $form['payment_details']['amount'] = array(
    '#title' => t('Payment Amount'),
    '#type' => 'textfield',
  );
}

I then call the function in my form definition.

transaction_form() {
  // ...
  payment_details(&$form);
  // ...
  return $form;
}

While the approach leads to the desired result, Drupal gives me the following warning:

  Deprecated function: Call-time pass-by-reference has been deprecated in drupal_load() (line 1100 of C:\Wamp\www\paradise\includes\bootstrap.inc).

Maybe anyone can give me a better way to reach my goal? At least, can you guys advise on how to fix this problem? I understand from various forum posts that this is a PHP related issue, and that it can be more or less ignored for development. Do you agree?

Your function already accepts the $form variable by reference (function payment_details(&$form)) so you don't have to pass the $form element by reference when calling that function. Just use payment_details($form); in your form builder and you should be fine. Passing by reference is deprecated in recent PHP versions, so that's why you get a warning.


link to node field on another content type I have a field that uploads a pdf, I want to get the uri in another node and content type to create a link.

Is this possible to do without knowing the id of the node (so not using node_load) but by the field name? I tried to create an existing field in my node (see screen) but this seemed to just provide a duplicate field without the already uploaded pdf.

The idea is have the users upload the file in one place.

You should be able to accomplish this using the Linkit module which has access to managed files.


Why doesn't my code work? I am really getting frustrated with this. In my theme I have a script file that is working. I am adding a new function to deal with some div but nothing happen. Cleared the cache...tried different things...nothing is working.

The following code is working perfectly fine when tested in jsfiddle, but in my site...nothing at all.

html code output:

  title

title

     logo

dsfdsfsdfsdfsdfsdfsdfdfs

in my js script:

$(document).ready(function () {

$(".cal-full").mouseover(function() {

        $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_hide');

    });

$(".cal-full").mouseout(function() {

        $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_hide');

    });

});

Any help will be appreciated.
Thanks!

You can't trust JsFiddle when it comes to running Javascript in Drupal, because Drupal uses the Immediately Invoked Function Expression (IIFE), a well known pattern in JS. Raw code you supply the fiddle with may not always work in the application.

See managing JS in Drupal. Your code needs to be wrapped first. My guess? You have console errors regarding $ is undefined.

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(".cal-full").mouseover(function() {

        $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_hide');

    });

$(".cal-full").mouseout(function() {

        $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_hide');

    });
    });
    }
  };
})(jQuery, Drupal);

If this is Drupal 8, you will also need to require jQuery and related dependencies from your module or theme, so they are attached to the page before your script.


Programmatically add a footer to a view I need add a footer to a view based on certain conditions. I followed this article and as per my understanding this should work. But this is not giving me any result.

Here is my code:

function utility_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  $item = array(
    'id' => 'area_text_custom',
    'table' => 'views',
    'field' => 'area_text_custom',
    'relationship' => 'none',
    'group_type' => 'none',
    'admin_label' => '',
    'empty' => NULL,
    'tokenize' => NULL,
    'content' => array(
      'value' => "Footer content is great.",
      'format' => "basic_html",
    ),
    'plugin_id' => 'text',
  );
  $view->setHandler($display_id, 'footer', 'area_text_custom', $item);
}

Update: Using the above hook the footer is getting called but renders as Array

I was able to add a Views footer with some code in a custom module.

use Drupal\views\ViewExecutable;
function YOURMODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_machine_name' && $display_id === 'view_display') {
    $options = array(
      'id' => 'area_text_custom',
      'table' => 'views',
      'field' => 'area_text_custom',
      'relationship' => 'none',
      'group_type' => 'none',
      'admin_label' => '',
      'empty' => TRUE,
      'tokenize' => FALSE,
      'content' => ‘Footer content is great.’,
      'plugin_id' => 'text_custom',
    );
    $view->setHandler('view_display', 'footer', 'area_text_custom', $options);
  }
}

Reference: Drupal 8: Programmatically Adding a Views Footer


Altering views exposed form - Adding select list separator causes error Problem

I want to break the select list on my exposed form into chunks using select list dividers.

However this breaks my search.

Any attempt to search with values from that select list removes all results and attempts to navigate to the next page display the following error:

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

What is going on?

Set-Up

I have an exposed view form. It has a select list field as one of the filter options.

There are a lot of options in the select list, so I've reordered it (away from alphabetical) to leave the five most popular at the top. This seems a little random so I then altered the form to add in un-selectable dividers. (see top picture)

How to add separator option in Form API 'select' element? (this is for creating forms, I put it into a form alter)

function mymodule_form_alter(&$form, $form_state, $form_id) {
    if ($form_id === 'views_exposed_form') {
      'Most Popular' => array (
          1 => 'China',
          2 => 'Thailand',
          3 => 'Japan',
          4 => 'Spain',
          5 => 'Saudi Arabia',
      ),

      'Countries' => array (
          6 => 'Afghanistan',
          7 => 'Aland Islands',
          8 => 'Albania',
          9 => 'Algeria',
          10 => 'American Samoa',
          ..
       );
    }

Is it somehow appending "Most Popular" or "Countries" onto the select list data value, invalidating the select list and throwing errors?

Allowed values in my select list looks like:

China|China
Thailand|Thailand
Japan|Japan
Saudi Arabia|Saudi Arabia
Spain|Spain
Afghanistan|Afghanistan
Aland Islands|Aland Islands
Albania|Albania

EDIT --

Alfred-Armstrong's answer has fixed the first problem. I now get search results. But the form alter is still breaking my ability to change pages.

This does however depend on what I search for. If I choose a country it works otherwise it breaks on a blank search.

Any more insight would be fantastic.

EDIT--2

Thanks again to Alfred I figured out what the other problem was. I was getting slightly different paths in my views with and without hook_alter_form.

The reason is I have two exposed forms for the same view. This means I have two views with the same path and both have exposed forms. One is on the home page the other on the search page.

The exposed forms have the same $form_id, so I when I alter one using hook_form_alter I alter the other. However I'd altered one exposed form in the views UI and not the other and because they have the same $form_id Drupal tries to pass data between them but can't.

The key values in the field are strings but in your altered version they are numbers. Change 1 to China etc.


Show/Hide Column in Views Table Is there any way I can show/hide entire column in Views Table?

Exclude from Display completely excludes the column which is not possible to show again, so, I am using Views Dynamic Fields Module to exclude the column initially and showing it when the filter is checked. Like in the picture, the initial view when Column is hidden using Views Dynamic Fields module.

When the Nick Name checkbox is checked the column is shown like:

However, I want to hide the Name Column entirely when Nick Name is shown.

I initially tried it with jQuery like:

// Hide the Name Column when Nick Name is shown
$('#edit-dyfield-field-girls-nickname').change(function() { // id of checkbox
                if ($('#edit-dyfield-field-girls-nickname').is(':checked')) {
                    $('.views-field-title').hide(); // Title points to Name field so all the th td have this class in Name
                }
            });

But it hides both Name and Nick Name for a while, and shows both fields again.

Any solution Drupal based or some tricks with jQuery/JavaScript would be fine, thank you.

I am not sure if this is The Drupal Way to fix this, but I fixed it with jQuery hide() and show().

// Hide the Name Column when Nick Name is shown
$('#edit-dyfield-field-girls-nickname').change(function() {
                if ($('#edit-dyfield-field-girls-nickname').is(':checked')) {
                    $(document).ajaxStop(function() { // Forcefully stopping Ajax function in the page as other ajax load was main culprit in my case
                        $('.views-field-title').hide();
                    });
                }

                if ($('#edit-dyfield-field-girls-nickname').is(':not(:checked)')) {
                    $(document).ajaxStop(function() {
                        $('.views-field-title').show();
                    });
                }

            });

Note: In the above example jQuery toggle() doesn't work, so, I have to put 2 if(){} statements for Check and UnCheck.


Limit filter operators Is there a way to limit the operators for views-filtering for users. I want them to only have "starts-with", "contains" and "same". But not the rest. Do I have to form_alter with a custom module? Or is there some intern way to achieve that?

I don't think there is an option to sort the exposed operators.

You can do it with a custom module using hook_form_alter().

Example:

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

  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view_name') {
    unset($form['field_name_filter_op']['#options']['empty']);
    unset($form['field_name_filter_op']['#options']['not empty']);
  }

}

You can find the form details using "dpm()" from devel module.

dpm($form_id);
dpm($form);
dpm($form_state);


Translated Nodes Redirect To Homepage I'm using Drupal 8.6.9 and have four languages setup:

English (Default)
Spanish
German
French

When I create a node of any content type and publish it as each one of these languages, everything seems fine when logged in. When I log out and view these pages they're fine again, but only for the default language. If I try to view a translated version of a node I just get redirected to the site's root back on the default translation.

I'm using URL detection which works when logged in fine.

There are no custom permissions setup and everything is properly published.

I can see that the redirect is a 308 Permanent Redirect from looking at the dev tools.

I've tried rebuilding permissions, clearing the cache etc with no success, any help would be much appreciated!

Thanks

Solved. The issue was arising from a change I'd made to the KernelRequestSubscriber where I was redirecting users that hit the homepage that wasn't on the actual root of the site (to stop the homepage from being accessible from multiple routes - duh).


How to pass additional arguments in $form['#after_build'] function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
$form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';

}

I need to pass $element across #after_build function, how I can implement it?

Most of callbacks like #after_build will received automatically 2 arguments: $elements and $form_state, like this :

my_callback_after_build($element, &$form_state){
//...
}

So you simply have to push your var in the form_state var from where you add your callback :

function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   $form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';
   $form_state['foo'] = 'bar';
}

And you'll get it in the form_state var of your callback like this:

function custom_third_level_auto_suggest_widget_selection_afterbuild($form, &$form_state){
   var_dump($form_state['foo']); //will print "bar"
}


how do I make Drupal Zen sub theme mobile friendly? I have changed over to using the Zen theme (instead of Omega) on my drupal site, I have a Superfish menu configured with default settings for SF Small Screen plugin to enable on browser width (screen width 768px which is default). It worked perfectly on Omega where i had exactly the same settings, but now with my Zen sub theme, the menu doesn't change to a mobile friendly version when i reduce the browser width on safari. I have my site installed on localhost and looking at view source it shows:

<meta name="MobileOptimized" content="width">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width">

Yet using the same site with omega theme it shows:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" >

Am i missing a setting on Zen to enable mobile responsive?

I have ticked all these settings on my zen sub theme:

Add HTML5 and responsive scripts and meta tags to every page.
 Add Respond.js JavaScript to add basic CSS3 media query support to IE 6-8.
 Add HTML5 shim JavaScript to add support to IE 6-8.
 Add meta tags to support responsive design on mobile devices.

Can anyone help?

I have just checked the Superfish project status and there are bug reports that Superfish breaks with jQuery versions 1.9 and above. Check what version of jQuery is loading and check if there are any Javascript errors in your browser console.

If that is the problem, you may have to wait for the next version update, or roll back to jQuery 1.8 for the time being.

Superfish jQuery 1.9 Bug Report


How to show block on pages with URLs containing a question mark ( 'searchquery' )? For example I end up with url's like

example.com/viewname?f=[0]field_name=%3A21

I want to make a block visible on pages like the above but not when only the view is displayed.

Only the view will looks like this: example.com/viewname

So my thought was to set the block visibility setting to be only visible on:

example.com/viewname*

That didn't work ( block did not show up ) so i tried:

example.com/viewname?* , example.com/viewname?f* and example.com/viewname/*

No success.

EDIT:

There are some options:

1) Creating a block in custom module could be a solution.

1a Setting visibility to 'none' by unsetting the block content and title ( which I have chosen to use for now )

1b Enabling the PHP filter module and adding a block setting visibility restrictions like so:

/**
  * Implements hook_block_info().
  */
function mymod_block_info(){
  $blocks['mymod_job_agent'] = array(
    'info' => t('block description'), //The name that will appear in the block list.
    'cache' => DRUPAL_CACHE_PER_ROLE, //Default
    'region' => 'sidebar_first', // assign block region
    'status' => 1, // enable the block
    'visibility' => BLOCK_VISIBILITY_PHP, // set visibility to use the result of pages
    'pages' => '<?php return TRUE; ?>',
  );
  return $blocks;
}

Drawback: since hook_block_info is called upon module install only you cant change your code without reinstalling the module. And putting php code in de pages just doesn't feel right.
So I think we can cross option 1b.

2) Another solution would be to use the Block Conditional Visibility by URI Query Parameters module but I couldn't figure out how to use this for this use case.

Reading the comments this is something that should be done in the theme layer...

Hope this helps anyone searching for a similar question. feel free to edit update my question/answer to improve it!

You can use the Block Conditional Visibility by URI Query Parameters module to control block visibility via query string.

  Controls block visibility by URI Query Parameters. Drupal natively allows blocks to be placed on pages by using their paths, however, this module allows administrators to also display modules based on url query parameters.


View contextual filter only applies to first filter AND/OR group I have a view that returns two different content types in its results. Each content type needs different filters, so I group them using OR and AND. See below:

This view represents a category page and filters the results using a contextual filter. Both content types share the same category field. However, the contextual filter (a taxonomy term based on the URL) only applies to the first group of filters before the "OR". This shows up in the query it generates:

SELECT DISTINCT node.nid AS nid, node.created AS node_created, node.title AS node_title, node.sticky AS node_sticky, node.nid AS node_nid, 'node' AS field_data_field_image_node_entity_type, 'node' AS field_data_field_duration_node_entity_type, 'node' AS field_data_field_slug_node_entity_type, 'node' AS field_data_field_stickybit_expiretime_node_entity_type, 'node' AS field_data_field_ribbon_color_node_entity_type, 'node' AS field_data_field_ribbon_text_node_entity_type, 'node' AS field_data_field_blog_thumbnail_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_segment} field_data_field_segment ON node.nid = field_data_field_segment.entity_id AND (field_data_field_segment.entity_type = 'node' AND field_data_field_segment.deleted = '0')
LEFT JOIN {field_data_field_submitted} field_data_field_submitted ON node.nid = field_data_field_submitted.entity_id AND (field_data_field_submitted.entity_type = 'node' AND field_data_field_submitted.deleted = '0')
WHERE (( (node.type IN  ('story')) AND (node.status = '1')
        AND (field_data_field_segment.field_segment_value IS NULL )
        AND (field_data_field_submitted.field_submitted_value NOT IN  ('2'))
        AND (node.nid IN
          (SELECT tn.nid AS nid FROM {taxonomy_index} tn
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th ON th.tid = tn.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th1 ON th.parent = th1.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th2 ON th1.parent = th2.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th3 ON th2.parent = th3.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th4 ON th3.parent = th4.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th5 ON th4.parent = th5.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th6 ON th5.parent = th6.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th7 ON th6.parent = th7.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th8 ON th7.parent = th8.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th9 ON th8.parent = th9.tid
          LEFT OUTER JOIN {taxonomy_term_hierarchy} th10 ON th9.parent = th10.tid
          WHERE ( (tn.tid = '205') OR (th1.tid = '205') OR (th2.tid = '205')
            OR (th3.tid = '205') OR (th4.tid = '205') OR (th5.tid = '205')
            OR (th6.tid = '205') OR (th7.tid = '205') OR (th8.tid = '205')
            OR (th9.tid = '205') OR (th10.tid = '205') )
        ))
      )
      OR ( (node.type IN  ('blog')) AND (node.status = '1') ))
ORDER BY node_sticky DESC, node_created DESC, node_nid DESC
LIMIT 12 OFFSET 0

You can see that the contextual filter is applied only to the first group, not both. Is there any way to get the contextual filter to apply to both?

Drupal 7.8
Views 7.x-3.0-rc1
Views UI 7.x-3.0-rc1

Updating Drupal to 7.28 and the Views module to 7.x-3.7 solved the problem, as barraponto suggested it might.


drupal_json_output() output ascii I have a module that populate commerce cart product titles.
The function looks like this:

   function spcart_get(){
  global $user;
$order = commerce_cart_order_load($user->uid);
$wrapper = entity_metadata_wrapper('commerce_order', $order);
//var_dump(commerce_line_item_load(176)->line_item_label);
$line_item_id_sp;
$cart_product_array = array();
for ($i=0 ; $i < sizeof($order->commerce_line_items['und']); $i++){
    $line_item_id_sp = $order->commerce_line_items['und'][$i]['line_item_id'];
    $line_item = commerce_line_item_load($line_item_id_sp);
    $cart_product_array[] = commerce_product_load($line_item->commerce_product['und'][0]['product_id'])->title;
}

$output = (object) array('products' => $cart_product_array);
return drupal_json_output($output);
}

but the output of the function is in ascii:
{"products":["\u05d0\u05d5\u05e8\u05d6","\u05d0\u05d5\u05e8\u05d6"]}

I want that the output json will be un regular UTF-8 letters...
What is the problem?

drupal_json_output actually echos out the code its self so you don't need to return it's output, but you do need to exit after calling it:

drupal_json_output($output);
drupal_exit();

I'm not sure if this will fix your problem but certainly won't hurt...


phpunit query database How do I query the database when using PHPunit? This is my current attempt.

 /**
   * Testing to see if table is installed
   */
  public function testTableTest() {
   $connection = $this->getMock('Drupal\Tests\Core\Database\Stub\StubPDO');
    //-- What do I do next to query the database

    $query = $connection->query("SHOW TABLES LIKE {does_my_table_exist}");

    $expected = 'does_my_table_exist';
    $result = $query;
    $this->assertEquals($expected, $result);
  }

When you're using mocks in unit tests (see https://stackoverflow.com/questions/2665812/what-is-mocking), you yourself specify all the interaction that happens with the mocked object. In the simplest example, you can just specify exactly what the mock expects to receive, and what it will return:

$connection = $this->getMock('\Drupal\Core\Database\Connection', []);
$connection->method('query')
  ->with('SHOW TABLES LIKE {does_my_table_exist}') // expect this query
  ->willReturn(
    $this->getMock('\Drupal\Core\Database\StatementInterface')
      ->method('rowCount') // expect the ->rowCount() to be called.
      ->willReturn(1) // pretend that there is exactly one result.
  );

$result = $connection->query('SHOW TABLES LIKE {does_my_table_exist}')->rowCount();
$this->assertEquals(1, $result); // PASS
$result = $connection->query('SHOW TABLES'); // FAIL; unexpected argument.

Note that you shouldn't normally be mocking the StubPDO class; it's only for Drupal's internal DB driver tests. When your code interacts with the database, it does so via the database (\Drupal::database()) service, which you can replace with a mock of \Drupal\Core\Database\Connection.

Edit: A good example of a core unit test that mocks the database and actually simulates interaction is core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php. An excerpt of the setUp() function:

$this->statement = $this->getMockBuilder('Drupal\Core\Database\Driver\sqlite\Statement')
  ->disableOriginalConstructor()
  ->getMock();

$this->statement->expects($this->any())
  ->method('fetchObject')
  ->will($this->returnCallback([$this, 'fetchObjectCallback']));

$this->select = $this->getMockBuilder('Drupal\Core\Database\Query\Select')
  ->disableOriginalConstructor()
  ->getMock();

$this->select->expects($this->any())
  ->method('fields')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('condition')
  ->will($this->returnSelf());

$this->select->expects($this->any())
  ->method('execute')
  ->will($this->returnValue($this->statement));

$this->database = $this->getMockBuilder('Drupal\Core\Database\Connection')
  ->disableOriginalConstructor()
  ->getMock();

$this->database->expects($this->once())
  ->method('select')
  ->will($this->returnValue($this->select));


How to override path of specific page using views I have created a page view which contains files listing.
On existing Page there are three tabs called 'thumbnails' 'files' and 'thumbnail plus' now I want to override on 'files' tab view with my page view.
How do I do that?

Just set the path of the view to the same as the path of the page you want to override.

That's all you need to do, paths that Views takes care of "win" over paths provided by core and other modules. The most famous example of this is probably the taxonomy/term/% page View that comes with the module. Once enabled, term pages aren't handled by core any more, the View takes their place.


How to check the first item/content on Drupal View I'm currently using Drupal Views and I'm trying to figure how to check the first item/content on the view. On a twig template I could write

{% for items in related_content.entity.field_content_items %}

    {% if loop.first %}

    first element

    {% endif %}

{% endfor %}

I tried writing the same condition within the view using {% if loop.first %} but it doesn't work. Is there similar code to achieve this within Drupal Views Custom Text

Have you tried to print other stuff of the loop variable, maybe {{ loop.index }}, did this work? You then could if-request this. As far as I remember loop.index worked fine in Drupal.

Next thing you can try is to iterate over the keys and if-request the key for your logic. Pretty much the same as loop.index.

{% for key, items in related_content.entity.field_content_items %}
  {% if key == 0 %}

Last resort would be to target related_content.entity.field_content_items[0] directly.

But I think the first two suggestions should give you at least one opportunity to do what you want.

Thanks for the clarification. Views custom text only. OK, in that case consider to use 2 views (or just 2 displays of the same view) as outlined here https://drupal.stackexchange.com/a/104608. Then you'd attach the first view (or display) - which is limited to display only 1 row - before your second view (there must be an attachment option somewhere) and your second view then should be configured to have an offset of 1.


Customize output style of views filter fields I have a view associated with many filter fields:

Checkboxes
Listboxes
Three date fields of textbox type.

In admin theme(seven), the date filter fields aligned improperly and I would like to show the three date range filters aligned horizontally next to each other.

I couldn't add any class for filter fields from the admin UI.

Any help/ideas please?

The CSS classes given by Views should normally be good enough, if you don't know how to find them you may using a chrome or firefox browser: right click on the filter field and then inspect element

Or if you want you may install the Better exposed filters module and follow the intructions given in this question

UPDATE:

As per your comment below, how to group filter fields under one div ?, it is out of the scope of the original question and for that you will have to ask another question.

However, I believe that what you are asking for is not doable using the views UI and you will have to write your own custom codes, for that you may find the below links somehow useful even if they are referencing the D7 version:

Wrapping fields together in a views exposed filter
Place exposed filters in a fieldset
Views Grouping field to use a shared wrapper div
Views exposed groups Module for D7


Views listing of content types a user is allowed to create My site allows any user to register but I can verify who they are and then assign a role if I am satisfied.

Can anyone tell me how I can list the content type(s) a user with a particular role is allowed to create? Is this accomplishable via Views?

I also need to detect if they are allowed to create content and display a message to them if they are not.

Thanks.

Like @googletorp said, you can't do this with Views, you will have to create a custom module.  If you are creating your own module, this short snippet will give you an array ($types) with the links to content types the logged in user can create (D6).  If the user cannot create any content types it will show a message:

<?php
  $types = array();
  foreach (node_get_types('types', NULL, TRUE) as $type) {
    if (node_access('create', $type->type)) {
      $types[$type->type] = l($type->name, 'node/add/' . str_replace('_', '-', $type->type));
    }
  }
  if (count($types) == 0) {
    drupal_set_message('You cannot create any content types!', 'warning');
  }
?>


Change language programmatically after login I have a multilingual site and I want to change the language programmatically after user login to his own language to see all the content in his language.

How can I do this?

It should not be necessary to do it from code, as one of the settings present in admin/config/regional/language/configure allows to set the language to the one selected from the users in their user profile settings.


How can I access raw field values in a view template? I am writing a template for a views field in Drupal 8.
How can I access the raw values of a multi-value field in views? I tried this but it doesn't work.

{% for i in 0.. row.field_color['#items']|length - 1 %}
{{ row.field_color[i] }}
{% endfor %}

Since you are using it in views-view-fields--styles.html.twig, it would be {{ fields.field_color.0 }} or {{ fields.field_color.content|striptags }}.


Is the "access" table removed during upgrade? When a site is upgraded from Drupal 6 to Drupal 7 (or any higher version), do the update hooks remove the access table?

I am developing a module that could import the content of that table, and I need to know if after updating to Drupal 7 that database table is not anymore present.

The access rules function has been largely removed from core. From the CHANGELOG:

  Refactored the "access rules" component of user module: The user module now provides a simple interface for blocking single IP addresses. The previous functionality in the user module for restricting certain e-mail addresses and usernames is now available as a contributed module. Further, IP address range blocking is no longer supported and should be implemented at the operating system level.

The upgrade path do not remove the {access} table. It migrates the entries it can to the new {blocked_ips} table, but otherwise keep the content of the {access} table in place. See system_update_7002() and system_update_7003().

Parent issue: http://drupal.org/node/228594.
Possible replacement for Drupal 7: http://drupal.org/project/user_restrictions.


How do I highlight an element in a view result? I have a "Collection" content type, and a "Product" content type.

Each "Product" node has a node reference to a "Collection" node, and a "Collection" node can have several "Product" nodes referring it, while a "Product" node can only belong to one "Collection" node.

I created a view to list all collection as photo thumbs with link to collection node. I display this list as a footer in collection nodes and products nodes.

What I want to do as "special" is to highlight current collection in the collections footer when I display a product node which belongs to this collection. Same thing when I display the collection itself.

Is it possible to do this using views and as possible without Javascript?

First check the thumbnail is passing your condition then simply just add a unique class to that field using the tpl file for that field.


Creating fake (test) data Is there a module or part of devel module that will auto populate (with fake data) a Content Type a create a dozen or so nodes?

If you installed the Devel module, there should be a submodule on the admin/modules page called Devel generate:

Enable it, and you should have some new menu entries in admin/config/development for generating fake conent, menus, terms, users, and vocabularies.


Send email to users, except author comments Hello!

I have node with field [field_users] (entity reference)

I create rule [after saving new comment]
Actions:
Loop for field: [comment:node:field-users]
inside loop i create var [users:mail]
And add action for sending emails...

But problem is:

if comment-author in list of field_users, emails sent also to author comment

Q:
How to remove comment author from loop?

Thanks for any help!

You can install Rules Conditional module, which will give you an option to run conditional logic inside a Rules Action, in your case related to the loop that you created.

So, you'll do a check in the loop as follows:

IF comment:author:mail NOT EQUAL users:mail THEN send email


What might cause drupal to give me Japanese values for the user profile, when the site is set to English? I'm playing whack-a-mole bug edition with drupal yet again.  Recently I've done a number of things including installing the neutral_path module.  I just discovered that now my user profiles (which all have English and Japanese name values) are giving me Japanese values when the site should be in English.  Examining the variable that is passed into MYTHEME_preprocess_user_profile() I see that the field values are in Japanese and that $variables['elements']['#language'] is set to 'ja'

What could be causing this?  What are reasonable steps to take to try and debug this?

I notice that after drupal_bootstrap() runs, I have $language reflecting English, but $language_content reflecting Japanese.

Using a debugger and some spot googling, I finally found an answer for this.  In my language detection and selection options I had session turned on as one of the means of detection, and saw that the query variable used for setting this option was language.  adding ?language=en to the end of my url caused the language to switch back and stay that way, but I am not sure how it got that way in the first place, or how to make sure it doesn't happen unintentionally again without disabling the session option.


How to change the View Mode based on theme? I am using the ThemeKey module to change the theme for mobile users. I have a custom View Mode called Mobile to display different content. I would like to have when my mobile theme is loaded for the node to use the Mobile View Mode that I created instead of the Default View Mode.

I would like to do this in the theme. Either hooking into the theme with a module or just placing the php in a template override.

Thanks!

Ok I found a few items that get my closer to what I am needing. I just can't seem to get it to work. I am testing this idea with the teaser for now.

<?php
$rendered_teaser = render(node_view(node_load($nid), 'teaser'));
?>

By using the node number I am able to get it to print in the page.tpl.php file fine. But I am wanting to get the node I am on and convert the view mode from full to teaser.

<?php
$rendered_teaser = render(node_view(node_load(2), 'teaser'));
?>

I found that information be reading the links below. I am still not able to get it to work but close. For some reason I get errors. I think it has to do with me placing it in the node.tpl.php and the page.tpl.php template file.

http://drupal.org/node/985022
http://drupal.stackexchange.com/questions/36028/getting-the-auto-summary-from-a-node-bodyhttp://drupal.stackexchange.com/questions/23961/print-result-of-a-node-load

And I got it working. Any comments appreciated. I placed this on the top of the page.tpl.php.

<?php
$nid = $node->nid;
if ($nid) {
 $nid = $node->nid;
 $rendered_view = node_view(node_load($nid), 'teaser');
}
?>

And I placed the print rendered_teaser where I wanted the node view to be printed.

<?php
if ($nid) {
 print render($rendered_view);
}
 else {
  print render($page['content']);
 }
?>

Since your mobile theme is a different theme a viable alternative is to just use the same display modes everywhere and then theme that display mode differently by overriding the node.tpl.php file differently in each theme.


How to print only src path of taxonomy image I'm using Taxonomy image 1.6 on D6.19, I'm working on a legacy stack that I can't upgrade, nor do I have direct access to the taxonomy image module. Nice right?

Right now I'm using the taxonomy image in two ways, one is being printed out in the standard functionality of the mod and thats fine, the second is as a popup overlay created by jquery.

The popup is holding it's info in the "data-content" portion of a div, and required that any tag inside using only single quotes. Double quotes end the script early. I need to call the Src of the image so I can dynamically print it into an image tag. or I need to know how to hook into it so I can rewrite it for this particular use.

Any guidance would be welcome.
Thanks
Stephanie

A quick look at a download of the current version of the module (1.7) shows that there is a function based on the $tid that returns a lot of formatted and unformatted information:

/**
 * Function to get an image object with more useful data for custom formatting.
 * @param
 *   $tid - the term tid.
 * @return
 *   image object.
 */
function taxonomy_image_get_object($tid, $recursive = NULL)

with one of the things being returned being the url to the image.  Assuming this function exists in your version, would this work for your use case?  If so, there is even a helper function available as well:

/**
 * Function to get a url for an image, for use in css, html or other client-side code.
 * @param
 *   $tid - the term id
 * @return
 *   The url string.
 */
function taxonomy_image_get_url($tid) {
  $image = taxonomy_image_get_object($tid);
  return $image->url;
}


Add target="_blank" to menu item of type MENU_LOCAL_ACTION How can I add a target="_blank" property to a menu item of type MENU_LOCAL_ACTION ? I cannot do 'options' on MENU_LOCAL_TASK, MENU_DEFAULT_LOCAL_TASK, and MENU_LOCAL_ACTION items.
I tried with jQuery

(function($) {
    $(document).ready(function() {
        $('.page-admin-commerce-reports-incomplete-payments .action_links li a[href]').attr({
            target: "_blank",
            title: "Opens in a new window"
        })
    });
}(jQuery));

But it didn't work.
Thanks!

There seems to be a module for this: Menu target.

In case you need to do it programmatically, you can have a look at the source code for inspiration. As far as I see, the module adds a special class to the menu items you select, and then some JS captures the click and opens a new window:

  $('a.target-blank', context).once('target-blank', function () {
    $(this).click(function() {
      window.open(this.href);
      return false;
    });
  });


How can I add superscript character in a textfield I am looking for a way to use superscript characters in a Drupal textfield. When I copy and paste from a Word document, Drupal changes it to plain text.

Expected Result: m2

Actual Result: m2

What’s the correct way to use the superscript in fields? How can I enable special character support?

On a vanilla drupal 7 site you can set the text format of the field to full HTML and use standard HTML to render the superscript.

For the paste from word functionality, I would recommend adding the WYSIWYG module and following the instructions to get a proper editor like ckeditor. Will be a world of difference.


"Declaration of  must be compatible with " in Drupal 8.6.10 Up until Saturday I had a functioning Drupal 8.6.x instance. The I did

composer update

and Drupal 8.6.10 was installed. Since then I get the following in my error logs:

  Declaration of Drupal\Core\Template\TwigTransTokenParser::parse(Twig_Token $token) must be compatible with Twig\TokenParser\TokenParserInterface::parse(Twig\Token $token)

and Drush fails with

  Robo\Robo::configureContainer() must be an instance of Robo\Config\Config, instance of Drush\Config\DrushConfig given

I use PHP 7.2 on Ubuntu 18.04.

I did a clean reinstall of Drupal 8.6.10 and the same things occur. I've tried to replace 8.6.10 with 8.6.9 and even 8.6.0 but I still get these errors. If it were Java, I would suspect that the interface and the class had been compiled with different versions of the compiler. But I don't know PHP well enough to know where to start. These errors seem to me to be in core: all my code is under modules/xxx.

Any hints?

Steve

It is a global issue on this new Twig version 1.38.0.

I can be temporarily fixed by downgrading its version using composer require twig/twig:1.37.1

You can follow this issue to know when the Twig version can be updated again.


The RTL css file is not working for a menu I wanted to make the CorporateClean theme RTL. Every thing is Ok except Main Menu. It effects alignment for both languages. For Persian is also right and for English as well.
As example: I wrote the following code in RTL Css file

#header-menu ul.menu li {
float:right;
dir:rtl;
text-align:right;
}

It makes the menu RTL for both English  and Persian languages.

you mistake is here     dir:rtl; :(, and correct code will be below "dadash"

#header-menu ul.menu li {
float:right;
direction:rtl;
text-align:right;
}


How to theme a custom object from an external datasource? I am building a Drupal 7 website that has several Content Types (CTs) like Page, Event, Blog etc. For each CT, the full node view mode has been heavily customized using Display Suite.

I am requested to display data (let's say articles) from an external datasource (remote json API) within my website. Each remote article should be displayed in a single page within my website (like full node view modes), should look like (similar if not the same HMTL markup) as in my normal Drupal nodes and should not be persisted.

In a custom module, I have implemented hook_menu and defined a custom page callback, and within my callback, I perform the remote API request for a remote article (let's assume that remote article identifiers are available to me) and parse the json into a php object.

function my_custom_module_menu() {
  $items = array();
  $items['foo/bar/article/%'] = array(
    'title' => 'Remote article page',
    'page callback' => '_remote_article_display',
    'page arguments' => array(3),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function _remote_article_display($article_id) {
  // unrelated remote request and json parsing code
  $article = get_remote_article_by_id($article_id);
  $output = ''; // how to theme $article object?
  return $output;
}

How should I print the proper HTML markup for my $article object without hardcoding it? The fact that my normal nodes are using Display Suite is an additional overhead as at this point I am not even sure how to print the default Drupal html for fields.

You should use hook_theme() for that:

  Register a module (or theme's) theme implementations.

  The implementations declared by this hook have two purposes: either they specify how a particular render array is to be rendered as HTML (this is usually the case if the theme function is assigned to the render array's #theme property), or they return the HTML that should be returned by an invocation of theme(). See Using the theme layer Drupal 7.x for more information on how to implement theme hooks.


How to: Array of field collection items Sorry for being a little bit impudent, bit i would need someone to build an array into a code snippet. As I know nearly nothing about php coding, I managed to adept some code I found to get the urls of video files stored in field collection fields (one is for the .mp4 movie, otherone for the .webm version). So far, the code works well, but - here comes the problem - there is only the first value of each field collection field displayed. So, I Think i would need an array to regenerate the div container containing the  tag with the source paths for each value of the field collection, not only for the first one. I anybody can help me, I would be very, very thankful.... i am working on this since more than 6 hours now...

here is my code:

// get node object
$node = node_load($nid);

// get field collections from node
$field_html_5_video = field_get_items('node', $node, 'field_html_5_video');

// get all fields values if collection exists
if (!empty($field_html_5_video)){
    $field = field_view_value('node',$node, 'field_html_5_video', $field_html_5_video[0]);
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from the field collection
        $field_video_mp4        = $field_wrapper->field_video_mp4->value();
        $field_video_webm        = $field_wrapper->field_video_webm->value(); // an array of image data
        $field_video_description  = $field_wrapper->field_video_description->value();

        // getting the video urls
        $video_url_mp4          = $field_video_mp4['uri'] ? file_create_url($field_video_mp4['uri']) : '';
        $video_url_webm          = $field_video_webm['uri'] ? file_create_url($field_video_webm['uri']) : '';

        print '
';
        print '';
        print '';
        print '<video width="100%" controls>';
        print '<source src="' .$video_url_mp4. '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'>';
        print '<source src="' .$video_url_webm. '" type=\'video/webm; codecs="vp8, vorbis"\'>';

        print '</video>';
        print '';
        print '' .$field_video_description. '';
        print '
';
    }
}

As per @Andrew comment, instead what you have try printing your HTML start a var outside your foreach and then:

$template .= '<html>';

adding to it, then print it out after your foreach has finished looping.

In addition make an array outside the foreach, e.g.:

$newarray = array();

Try not using the entity_metadata_wrapper, as it seems like an extra layer of stuff to deal with.