Show a Unique Header Image based on Path in Drupal 7 I'm trying to customize the header with an image for each path; if not, put a default image. I found a way to do Lullabot, but it is for Drupal 6.

Is there any option for Dupal 7?

theme-settings.php

/**
* Implementation of hook_settings() for themes.
*/
function MYTHEMENAME_settings($settings) {
    // This ensures that a 'files' directory exists if it hasn't
    // already been been created.
    file_check_directory(file_directory_path(),
        FILE_CREATE_DIRECTORY, 'file_directory_path');
    // Check for a freshly uploaded header image, save it to the
    // filesystem, and grab its full path for later use.
if ($file = file_save_upload('header_image',
    array('file_validate_is_image' => array()))) {
$parts = pathinfo($file->filename);
$filename = 'MYTHEMENAME_header_image.'. $parts['extension'];
if (file_copy($file, $filename, FILE_EXISTS_REPLACE)) {
    $settings['header_image_path'] = $file->filepath;
    }
}

// Define the settings-related FormAPI elements.
$form = array();
$form['header_image'] = array(
    '#type' => 'file',
    '#title' => t('Header image'),
    '#maxlength' => 40,
);
$form['header_image_path'] = array(
    '#type' => 'value',
    '#value' => !empty($settings['header_image_path']) ?
    $settings['header_image_path'] : '',
);
if (!empty($settings['header_image_path'])) {
$form['header_image_preview'] = array(
    '#type' => 'markup',
    '#value' => !empty($settings['header_image_path']) ?
        theme('image', $settings['header_image_path']) : '',
    );
}
return $form;
}

template.php

/**
* Implementation of hook_preprocess_page().
*/
function MYTHEMENAME_preprocess_page(&$variables) {
  $settings = theme_get_settings('MYTHEMENAME');
  if (!empty($settings['header_image_path'])) {
    $vars['header_image_path'] = $settings['header_image_path'];
  }
  else {
    $variables['header_image_path'] = path_to_theme().'/head.jpg';
  }
}

I tried using the Header image module but it is not working; the other option I have is to make a content type with a view and relate them to the nid.

Which option do you recommend?

If you want to define your header image in appearance settings form:

theme-settings.php

**
 * Implements hook_form_system_theme_settings_alter().
 *
 * @param $form
 *   Nested array of form elements that comprise the form.
 * @param $form_state
 *   A keyed array containing the current state of the form.
 */
function YOURTHEME_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  // We are editing the $form in place, so we don't need to return anything.
  $form['YOURTHEME_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('YOUR THEME Theme Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  // display settings
  $form['YOURTHEME_settings']['display'] = array(
    '#type' => 'fieldset',
    '#title' => 'Display options'
  );

  $form['YOURTHEME_settings']['display']['header_type'] = array(
    '#type' => 'select',
    '#title' => t('Type of header'),
    '#default_value' => theme_get_setting('header_type'),
    '#options' => array(
      'default'   => t('Default header'),
      'christmas' => t('Christmas header'),
      'easter'    => t('Easter header'),
    ),
    '#description'   => t("Select type of header"),
  );
}

template.php

/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$variables) {

  // header image
  switch (theme_get_setting('header_type')) {
    case 'christmas' : $variables['header_image'] = path_to_theme() . '/header-christmas.jpg';
      break;
    case 'easter' : $variables['header_image'] = path_to_theme() . '/header-easter.jpg';
      break;
    default: path_to_theme() . '/header-default.jpg';
  }
}

Alternatively
You can use css to define header image paths, so instead preprocessing page variables, use template_preprocess_html to provide appropriate body classes:

/**
 * Override or insert variables into the html templates.
 */
function YOURTHEME_preprocess_html(&$variables) {
  // add holiday classes to body
  switch (theme_get_setting('header_type')){
    case 'christmas' : $variables['classes_array'][] = 'header-christmas'; break;
    case 'easter' : $variables['classes_array'][] = 'header-easter'; break;
  }
}

css

/* HOLIDAY HEADERS */
.header-christmas #page_header { }
.header-easter #page_header { }


Why does default .gitignore suggest ignoring config directory? In Drupal 8, perhaps the most anticipated feature is separation of configuration from content. It achieves this by storing configuration changes in a sites/default/config_* folder.
Why then does the default .gitignore file suggest ignoring this directory?
If I make changes to the site, I want those changes to be tracked to push them to the live site, or merged with another developer's changes.

You are supposed to put that in a separate repository, I suppose. Note that the best practice workflow is to export the configuration and git the staging directory. You are not supposed to edit the active directory to the best of my understanding.

Edit: since writing this answer the default storage is now in the database and there's no more active directory.


Cannot add content to panels pages (stuck in overlay) When I try to edit the content of panels pages, I click the add content link in the drop down menu an  drag and drop down menu. The progress indicator appears and turns for a while and then nothing happens. The screen remains with the semi transparent overlay (screenshot below).

Also, drag and drop for reordering the content does not work.

Assuming it is related with an ajax call I checked the chrome console but there seems to be no error.

I am using:
panels 7.x-3.3
ctools 7.x-1.3
jQuery v1.8.3
jQuery UI 1.8.7
jQuery UI Draggable 1.8.7
jQuery UI Droppable 1.8.7

I have been searching for hours now but could not find a related post anywhere.

Any ideas?

(a note: I do not have firebug or facebook modules installed. they are reported to cause a similar problem)

So it turned out to be a jquery version problem.

In case somebody else needs it, here is how I managed to solve it.

Installed the jQuery Update module
went to the module's configuration page (admin/config/development/jquery_update)
selected jQuery Version 1.7

and all my troubles faded away :)


Call to a member function getLoginUrl() on a non-object in fbconnect.pages.inc on line 230 I'm using the Facebook connect module to give the users the possibility to log in in my website with their Facebook account. The configuration of the module is good, but when I click on "Log in to NameSite with Facebook account" I get this error message:

  Fatal error: Call to a member function getLoginUrl() on a non-object in fbconnect.pages.inc on line 230

I am using Drupal 7.

You need to set up the app with Facebook. The current link for doing so is https://developers.facebook.com/apps.

See http://drupal.org/node/1944522.


How to move commerce kickstart database to other domain How to move commerce kickstart database to another domain.

When i copied my files and database tables and edited the settings.php the site just redirects to install.php

It is showing the install.php file because it doesn't recognize your settings.php file - you need to check that this is in the correct sites folder (ex. 'default') and has read permissions for your web user.


Contextual filter on a path alias I am trying to create a page view that will display content by Content:Title which is part of the node's URL.
I have 3 content-types: Movies, Books, and TV Shows.
Each content type has a path alias matching the [node:content-type:machine-name]/[node:title]/[current-date:custom:Ymd] pattern.
I successfully created a view called movies with a filter on Movies that displays all the nodes with www.example.com/movies/ in the URL. If I click on a node in the Movies view, it displays the content using the node.tpl.php template file.
I added a contextual filter (Content: Title) using Scott Edmonds suggestion.
Contextual Filter for: Content: Title ). When filter is not in URL -> Provide Default Value -> Raw Value from URL -> Path Component=2. Use Path Alias=Checked. Then, When Filter Value is In URL: Specify Validation Criteria= "PHP Code" with the following PHP code: $handler->argument = str_replace("-"," ",$argument); return true; That did the trick. the PHP code converts the dashes to spaces so it can be evaluated correctly.
The result is that when I click on the "Star Trek is Great" post link I am taken to the correct URL, www.example.com/movies/star-trek-great/20130702,  but node.tpl.php is the template used instead of views-view--movies.tpl.php.
When I copy the title and paste it into the url, as "www.example.com/movies/Star Trek is Great/20130712" the views template page comes us.
Some where along the way I am missing something.  Any help out there?
FYI - I also have simply set the contextual filter on Content:Title with
Display all results for the specified field
Checked "Override title" and added %1 as the first argument
Seleced "lowercase" for the Case PATH
Selected "transform spaces to dashes in url"
But nothing worked :(

The issue is the following:

When you go to www.example.com/movies/star-trek-great/20130702 Drupal sees that this is a path alias to node/#, and it displays that node.  It won't use Views at all.

When you go to www.example.com/movies/Star Trek is Great/20130712, this does not map to any URL, but rather to the View sitting at www.example.com/movies with an contextual filter of Star Trek is Great (and 20130712 most probably).

You may have some other issues to work out as well:

Pathauto is taking out the is (and other small words by default) so there will be a bit of a hard time mapping star-trek-great to Star Trek is Great.

Also, what happens if you have a title of Star Trek is Great!!! that maps to star-trek-great as well?


Programatically is it possible to list up all the path aliases that my site has? A site has many path aliases generated using the Pathauto module, or from the user interface.

I want to get all the aliases the site has. how can I achieve this?

I got a fresh installed d8.1 and a fresh pathauto 8.1.x-dev.
I got the url_alias table in my database by installing the module.

the table schema is [pid | source | alias | langcode]

I guess what you want to do is something like this:

$query = db_select('url_alias', 'ua')
  ->fields('ua', array('alias'))
  ->execute();

that should give you the result you want.


How do I define a template file for a specific node paragraph ID? I would like the ability to override a template for only 1 paragraph.  Is it possible to override just one paragraph like we can with nodes node-{nodeid}.html.twig?

This can be easily achieved by implementing hook_theme_suggestions_HOOK_alter from within a custom module or your theme. After that you can override paragraphs by adding templates like paragraph--123.html.twig to your theme's template directory.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE/MYTHEME_theme_suggestions_paragraph_alter(array &$suggestions, array $variables) {
  $paragraph_id = $variables['elements']['#paragraph']->id();
  $suggestions[] = 'paragraph__' . $paragraph_id;
}


Image based on node taxonomy terms Here is what I am trying to do.

If there is an empty image field on a node I want it replaced based on what taxonomy terms are on the page, but the key is I want to apply it site wide so it will affect not only the tpl files but Views as well. I'm guessing this needs to be done via mytheme_preprocess_field in template.php but I'm not quite sure how to do it.

I can easily do this in node.tpl.php but I need it done site wide, not just in the node-type template.

VID 1

TID 1
TID 2
TID 3
TID 4

VID 2

TID 5
TID 6
TID 7

VID 3

TID 8
TID 9
TID 10

Here is what I am trying to do.

// Set Variables
$term1 = $content['field_term1'][0]['#markup'];
// Must use if statement or else there will be an error
if ( isset( $content['field_term2'][0]['#markup'] ) ) {
  $term2 = $content['field_term2'][0]['#markup'];
}
// Must use if statement or else there will be an error
if ( isset( $content['field_term3'][0]['#markup'] ) ) {
  $travel_type = $content['field_term3'][0]['#markup'];
}
if (isset($content['field_node_image'][0]['#item']['uri'])) {
  $image_path = file_create_url($content['field_node_image'][0]['#item']['uri']);
} else {
  switch ($term1) {
    case 'TID 1':
      switch ($term2) {
        case 'TID 5':
          $term_type = '5';
          break;
        case 'TID 6':
          $term_type = '6';
          break;
        case 'TID 7':
          $term_type = '7';
          break;
      }
      break;
    case 'TID 2':
      $term_type = '2';
      break;
    case 'TID 3':
      switch ($term3) {
        case 'TID 8':
          $term_type = '8';
          break;
        case 'TID 9':
          $term_type = '9';
          break;
        case 'TID 10':
          $term_type = '10';
          break;
      }
      break;
    case 'TID 4':
      $term_type = '4';
      break;
  }
  $image_path = '/sites/all/themes/themename/term-images/' . $term_type . '.jpg';
}

I used to use the Taxonomy Image module. It has full views integration as well.

Features:

    Image configuration happens within existing admin/taxonomy menu structure.
    Admins can add custom tags to <img> markup when displaying images.
    Allows one-to-one term-to-image relationships.
    Allows many-to-one term-to-image relationships.
    Admin-permitted users can disable the images.
    Administrators can force images to be a standard size.
    May use the ImageCache module if it is available.
    Works with Views.
    Utilizes core file.inc and taxonomy.module APIs.
    Small module with specific, focused functionality.
    Add-on modules that virtually eliminate the need for theme changes.


How to find users with password same as their username How do I find users which their password is equal to their username in Drupal 7?

If you are trying to do this while they are registering, there are good modules for the task, a simple search finds Password policy module, It is also on S.O:

  A password policy can be defined with a set of constraints which must be met before a user password change will be accepted. Each constraint has a parameter allowing for the minimum number of valid conditions which must be met before the constraint is satisfied.

However for already registered users, you have to hash their username as a password and compare it to their actual hash stored in database, if they are the same, you have cracked their password!

Hashing the passwords, The Druapl way user_hash_password()like this:

$user = user_load($id_of_user);
if($user->pass == user_hash_password($user->name)) {
  block_and_punush_lazy_user($user);
}

// maybe use it like this:
for($uid=2; $uid< MAX_UID_IN_DB; $uid++) { // FROM 2 ONLY!!
  if($user = user_load($uid) {
    if($user->pass == user_hash_password($user->name)) .... // Punish
  }
}

A more quick solution is to do it solely in database using it's hashing functions. You should check the password.inc in user module and extract the hashing algorithm. implement the same function in mysql and do a:

SELECT `uid` FROM `users` WHERE `pass` = MY_CUSTOM_HASH_FUNC(`name`);

And DO make a backup of your database before doing these stuff.


Create themable field group I have a custom entity with several fields. Now I would like to group the fields and give each group it's own twig template so that I would be able to compose a page (my custom entity) containing several sections (field groups).

How would you do that? Do I group the fields in the entity preprocess function and give each group it's own '#theme', do I have to change my hook_theme or should the grouping already happen in the controller? Or maybe create a computed field to store the other fields?

Thank you in advance!

The field group module is designed to solve this exact problem The Drupal 8 version is reasonably up-to-date.

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

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


Migrating SQL dump from Drupal 5 into Drupal 7 My site went recently down, and all the data were lost (PHP installation of Drupal 5). What I am left is simple SQL dump from PHPMyAdmin.

I would like to "use" this disaster and finally migrate to Drupal 7. Because of this, I do not know how to continue.

Should I install Drupal 5 first, import SQL dump, and then upgrade?

Is there any way how to save stored data from Drupal 5 (SQL dump) to Drupal 7? If the answer is yes, can you please point me to correct procedure?

There isn't any other way to update to Drupal 7, if not following the steps you listed. I would rather update to Drupal 6, and then to Drupal 7.
Probably, you could avoid installing Drupal 5, if you restore the database tables used from Drupal 5; you could start with updating to Drupal 6, if you have a copy of the setting.php file used from Drupal 5 (or you can rebuild it). I have never tried this; it could be working in theory, but have some practical problems I didn't think of.

Updating the data from Drupal 5 to Drupal 7 means to execute the update functions Drupal runs to update itself. There isn't any other method, since Drupal executes the updates in a specific order, and hook_update_dependencies() implementations change that order.


How do you check if table is empty before resetting the auto increment? I have a database table that a user can add to and remove data from within my drupal module. What I would like to do is automatically check to see if the table is completely empty after every delete, in which case I would like to run an "ALTER TABLE" to reset the auto increment to 1. However I am having trouble building a function that does this for me.

How can I implement a function to automatically detect if all fields are empty, and automatically reset the increment without the need to go into the database and apply ALTER SQL manually?

Here is some of the code...

function achievementlist_entry_delete($form, &$form_state) {
foreach(($form_state['values']['table']) as $rows) {
    $num_deleted = db_delete('achievements')
    ->condition('achvmntID', $rows)
    ->execute();
}
    //Here I would like to check the "achievements" database, as well as ALTER TABLE
    //it is empty
}

Important: This is a risky thing to do, particularly on a production site.
It could possibly cause problems with your database so be sure that you know your database schema very well and are fully aware of the implications of doing this.

You already use db_delete() so you seem to be familiar with database interaction.

So you just need to query to check for any values. You could use something like:

SELECT COUNT(*) FROM achievements

and make sure the result is zero, or

SELECT 1 FROM achievements LIMIT 1

and make sure that no rows are returned.

You can use db_query().

Then you can use db_query() again to reset the increment.

For example in mysql it would be:

ALTER TABLE achievements AUTO_INCREMENT = 1

Since it seems you already know drupal db this isn't really a drupal question.
It breaks down into:
How do I check a database table is empty and how do I reset an auto increment field.

In both cases searching google for that will get lots of results, including stack exchange answers or your chosen database's manual pages.


Merge two fields using Display suite, like views inline fields Is there a way to merge two or more fields using Display suite, like Views inline fields? What I mean is - if I have the fields "Author", "Publication date" and "Article series", then I would like to display them as "Author1 | 01-May-2012 | Learning series" etc.

Here's a list of possible approaches:

Code field: You can accomplish this with a custom code field in Display suite. A code fields supports usage of tokens and html. Additionally, you can use a Display Suite code filter to use php itself. More info found here: http://www.youtube.com/watch?v=mvFP16PJt4c
Use a Custom formatter: If you need more heavy processing you can utilize the custom field formatter module.
Preprocess Field: Additionally, you can access variables that are preprocessed via a "preprocess field". A preprocess field will print out the value of the key in the $variables array. Lullabot has an example on using the preprocess field.
Entity Views Attached: This might be a bit extra overhead but if you download the eva module you can create views and pass the current NID in and combine fields through views. This is often helpful if you need to create various different photo galleries with different fields, etc.


How to send a mail to a user with views rules when a date is passed? I have created a date field for all users (in Drupal 7). This date is the end of the user's subscription. When the date of this field is passed, I want to send a mail to the user to tell him he can subscribe again (to access our website).

So, I have created a view with a display rules (with module views rules). I have listed all users who have the field date not empty and filter to have only date passed. I have 2 fields in this view (user name and date). I have edited field info and enable my 2 fields (Data type : user and data type : date) :

After, I have created a rule wich react on the event "Cron maintenance tasks are performed" and created a view loop on the display rules of my view. In the loop i have added 2 actions : change the date value to exit the user from the view, and send a mail to this user :

When I Launch the cron, nothing happen. The date is not changed, and the mail is not send. I don't know what configuration I have forgot. Do you have an idea please ?

Thank you for help me.

My rule in export format:

{ "rules_relance_e_mail" : {
"LABEL" : "Relance e-mail",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "cron" : [] },
"DO" : [
  { "VIEW LOOP" : {
      "VIEW" : "dates_de_relances",
      "DISPLAY" : "views_rules_1",
      "ROW VARIABLES" : {
        "name" : { "name" : "Nom" },
        "field_date_de_relance" : { "field_date_de_relance" : "Date de relance" }
      },
      "DO" : [
        { "data_set" : { "data" : [ "field-date-de-relance" ], "value" : "+1 year" } },
        { "mail" : {
            "to" : [ "name:mail" ],
            "subject" : "Test relance",
            "message" : "Test mail",
            "language" : [ "name:language" ]
          }
        }
      ]
    }
   }
  ]
 }
}

Part 1: Sending an eMail

Your view needs refinement ...You seem to have 1 Views result (row) for each user to be eMailed, which is OK. But that view must have fields (columns) for each of the fields that you want to use in your Rules Action to create your eMail. So the [name:mail] and [name:language] in your Rules Action should be replaced by some column in your view to make those available. For that you might have to also add a "relationship" in your view to the "user object" (so that eg the eMail ID becomes available).

Have a look at these answers for some more details:

How to make fields available in Rules using the Views Rules module?
How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?

Part 2: Saving the changed date

You may have to add an extra Rules Action to "save an entity", because you need to remind the Rules module to also save the date you've updated.


views-view-field.tpl.php - How to print multiple values? I've created a views template (based on views-view-field.tpl.php) because I want to exclude a certain value ('o') from being displayed.  I came up with the following code:

$data = $row->field_my_field;
$raw_value = $data[0]['raw']['value'];
$rendered_value = $data[0]['rendered']['#markup'];

if ($raw_value == 'o') {
}
else {
  print $rendered_value;
}

This works fine for a single value, but this field allows for multiple values (up to about 20).  How can I modify the code to print all of the values except, if present, 'o'?

You can do it in the template itself quite simply, something like:

<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

This is a custom template for that particular field, and so should only be used with it (which can be done via preprocess). You might also need to be careful about the name of the field changing if the field's changed in the View.

The nicest approach I can think of is probably using hook_field_attach_view_alter():

function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'field_test';
  $to_hide = array('o');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_hide)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}

That will work for Views and a normal entity view. AFAIK you can use $context to detect whether you're in a View or not, but I can't remember what you'd check for exactly. (And if you later find you do want to display the field like this outside of Views, it's painless to change.)

HTH


Whats the proper way to preprocess field collection items to add first and last class names? How to add 'first' and 'last' class names in addtion to 'odd'/ 'even' for field collection items in preprocess functions?

You would normally do this in MYTHEME_preprocess_field_collection_item(), but field collection items don't have their own preprocess. Fortunately, they're entities, so you can use entity preprocess to create your own field collection preprocess function:

/**
 * Implements template_preprocess_entity().
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = 'MYTHEME_preprocess_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Field Collection-specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_field_collection_item(&$variables) {
  $variables['classes_array'][] = 'your-class-here';
  // Plus whatever other preprocessing you want to do.
}


Error running BrowserTest (Drupal\Core\Config\Schema\SchemaIncompleteException: No schema ...) I am working on a module Rate Limiter and trying to improve the deprecated SimpleTest with BrowserTest. While doing so, I get the following error.

  C:\Project\Sites\devdesktop\drupal8>.\vendor\bin\phpunit -c .\core\phpunit.xml.dist --filter testRateLimitConfigPageVisit .\modules\custom\rate_limiter\tests\src\Functional\RateLimiterConfigFormTest.php
  PHPUnit 6.5.7 by Sebastian Bergmann and contributors.

Testing Drupal\Tests\rate_limiter\Functional\RateLimiterConfigFormTest
E                                                                   1 / 1 (100%)

Time: 56.75 seconds, Memory: 6.00MB

There was 1 error:

1) Drupal\Tests\rate_limiter\Functional\RateLimiterConfigFormTest::testRateLimitConfigPageVisit
Drupal\Core\Config\Schema\SchemaIncompleteException: No schema for rate_limiter.settings

C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Config\Development\ConfigSchemaChecker.php:88
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher.php:111
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Config\Config.php:227
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Config\ConfigInstaller.php:334
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Config\ConfigInstaller.php:134
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\ProxyClass\Config\ConfigInstaller.php:75
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Extension\ModuleInstaller.php:268
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\ProxyClass\Extension\ModuleInstaller.php:83
C:\Project\Sites\devdesktop\drupal8\core\lib\Drupal\Core\Test\FunctionalTestSetupTrait.php:437
C:\Project\Sites\devdesktop\drupal8\core\tests\Drupal\Tests\BrowserTestBase.php:1026
C:\Project\Sites\devdesktop\drupal8\core\tests\Drupal\Tests\BrowserTestBase.php:490
C:\Project\Sites\devdesktop\drupal8\modules\custom\rate_limiter\tests\src\Functional\RateLimiterConfigFormTest.php:32

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

The Schema file is: https://github.com/aneek/rate_limiter/blob/develop/config/install/rate_limiter.settings.yml

And the Test File is: https://github.com/aneek/rate_limiter/blob/develop/tests/src/Functional/RateLimiterConfigFormTest.php

What I am missing?

The Schema file is: https://github.com/aneek/rate_limiter/blob/develop/config/install/rate_limiter.settings.yml

No, that is not the schema file, that is the config file for which you need to create a configuration schema.

Tests by default enforce that your configuration has a schema, which is useful for supporting configuration translation and additional upcoming functionality like validation.

See Configuration schema/metadata for more information on how to create that.


Add mini pager and infinite scroll to a view I have a view where at first 1 item has to show. On click of 'load more' next item has to show and so on. For this i have installed 'infinite scroll module' in drupal 8. Now after showing four items, 'load more' has to change to ' show less' and hide all four items. I am not sure how to do this as infinite scroll module doesn't have this option.

Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

I am not sure how to do this. Any help will be appreciated.

You're description is a bit ambiguous because first you write

  Now after showing four items, 'load more' has to change to ' show less' and hide all four items

but then below you write

  Also, once there are four items are displayed, pagination with 'next' (on click showing next 4 items) has to appear.

Sounds to me like once there are 4 items displayed, you want to have a show less AND a next button to be displayed?

What's safe to say though, is that you can't get that show less button using views infinite scroll.

I'd probably try to add pagination using views infinite scroll that shows/loads additional 4 items when you click the load more button. The show less button you'll probably have to implement as custom JS wrapped inside a Drupal behavior .

You may also consider to override the JS behaviors of the views_infinite_scroll module to achieve the show more/show less functionality if it's not possible in a custom behavior because you depend on views_infinite_scroll's JS code to run first or so


Batch API: What am I doing wrong? I am trying to import some videos into a 8.0.5 site (yes, I know I should upgrade)
I have over 200 videos that neeed to be imported into their own individual node. It seems like a perfect opportunity to get my head around the batch api.

After getting all the videos as objects in a sigle array, I then chunk this into batches of 10 using array_chunk() and then set each chunk as its own opperation.

I would have thought that the batch api would have sent each data array as a signle array to my process function. However, it seems that only the first video from each batch is getting processed.

If I add the &$context variable to my process function and dump it out, it just shows me the next object.

Please, can anyone point out what I have done wrong? :(

public function batchStart() {

ini_set('max_execution_time', 0);
$directory = drupal_get_path('module', 'drp_broadcast_videos_importer') . '/broadcast-videos';
$videoImporter = new VideoImporterController();
$videosArray = $videoImporter->getVideosFromDirectory($directory);
// Chunk up the array.
$videoChunks = array_chunk($videosArray, 5);

foreach ($videoChunks as $chunk) {
  $operations[] = [
    '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
    $chunk,
  ];
}

$batch = [
  'title' => t('Processing Batch'),
  'operations' => $operations,
  'finished' => '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::finishedBatch',
  'init_message' => t('Batch is starting.'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('Batch has encountered an error.'),
];

batch_set($batch);

return batch_process('/');
}

static function processBatch($video, $context) {
  try {
    $file = (new VideoImporterController())->createNewFileEntity($video->video, $video->filename);

    $broadcastNode = Node::create(['type' => 'broadcast_video']);
    $broadcastNode->setTitle($video->title);
    $broadcastNode->setOwnerId(\Drupal::currentUser()->id());
    $broadcastNode->setCreatedTime($video->date);
    $broadcastNode->set('field_broadcast_pack_name', $video->pack);
    $broadcastNode->set('field_videos', ['target_id' => $file->id()]);
    $broadcastNode->save();

    $context['message'] = $video->title . ' processed.';
    $context['results'][] = $video->id;

  }
  catch (EntityStorageException $exception) {
//              \Drupal::logger('broadcast_videos_importer')
 //                ->error($this
//                  ->t(
//                    'The broadcast video @title could not be uploaded',
//                    ["@title" => $videoObject->title]
//                  )
//                );
//              drupal_set_message($this->t(
//                'The broadcast video @title could not be uploaded',
//                ["@title" => $videoObject->title]));
    }
  return $broadcastNode->id();
 }

$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  $chunk,
];

In the above, $chunk is the list of parameters that will be passed to the batch process method. So if $chunk is an array of 5 videos, your method signature would need to look like this to match.

static function processBatch($video1, $video2, $video3, $video4, $video5, &$context) {

That's probably not what you're hoping for. To fix, just wrap $chunk in array:

$operations[] = [
  '\Drupal\drp_broadcast_videos_importer\Controller\ImportController::processBatch',
  [$chunk],
];

Now your process method signature looks like this:

static function processBatch($videos, &$context) {

And you just need to loop through the videos in each operation.


Use Views to display unpublished nodes to authors, but not to other users Say [User A] creates, but does not publish [Node 1]. [Views V] aggregates all of the content type that [Node 1] belongs into. [User B] should not be able to see [Node 1] listed on [Views V], but [User A] should be able to see his own unpublished [Node 1], all through [Views V] which lists out the specific content type.

Currently, if I change the Filter to not filter for Published or Unpublished nodes, then regular members can see the title of unpublished Nodes through the view, despite not having permission to access it (if the user clicks on it, then access denied message is shown). I do not wish for this to occur. However, I can't explicitly filter out unpublished nodes, since I want authors of said nodes to be able to see them (and access/edit them before publishing).

So is it possible to have Views filter out nodes based on the access permission of the current user?

I am using Drupal 7, and Views 3.

Just to save anyone else some time and trouble, there's a filter under Views called, "Content: Published or admin." This will do precisely what is needed.


drupal login not working offline because of reCAPTCHA I have installed a drupal site completely offline on my local machine I have it running on mysql and apache2. When I got to the localhost/user/login to edit changes because I want to do it on my machine and not on the actual site. I get a recaptcha error because the site key isn't registered for localhost. Is there anyway I can bypass recaptcha so I can login and make changes?

Thank you

edit:
As suggested below I have tried using drush when I run the drush pmu recaptcha command I get the below error:

The drush command 'pmu recaptcha' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you have installed new extensions

I have tried running:

sudo drush cache-clear drush

as they suggest but it does nothing.

uninstall recaptcha, can easily be done with drush

cd path/to/project
drush pmu recaptcha

drush is a command line utility for drupal and can be easily installed following this guide's setup drush section
I can't backup my website on a shared server because memory runs out. What can I do?


form validation messages are not rendered immediately I have a form, with multiple (ajax) components. I have added a simple button in the middle of this form, to validate custom fields.

$form['fieldset_2']['forward'] = array(
  '#type' => 'button',
  '#value' => t('Forward'),
  '#name' => 'btn_forward',
);

As expected, button call validation function in which I check if all values are correct.

The validation messages are not rendered immediately. I have to refresh page to get the error messages. The button doesn't use ajax.
I have a field type radios and form_set_error doesn't color the element with red or something.

The problem is that Drupal has already finished setting messages for the current request when it gets to processing your form. To get things working properly call drupal_get_form in template_preprocess_page:

function myThemeOrModulename_preprocess_page(&$variables) {
  // For node templates.
  // $variables['node']->my_form = drupal_get_form('form_name');
  // For page templates.
  $variables['my_form'] = drupal_get_form('form_name');
}

Then render the form in your template file:

<?php print render($my_form); ?>

There was another issue for which I don't know the cause of currently, but adding $variables['messages'] = theme('status_messages'); (see theme_status_messages) inside the same preprocess_page function solved it.


Is there a way to supress particular messages or a class of messages on the screen? Is there a way of suppressing a particular class of messages from being displayed on the screen, such as the one displayed below?

  Deprecated function: Methods with the same name as their class will
  not be constructors in a future version of PHP; GeSHi has a deprecated
  constructor in require_once() (line 837 of
  {site_root}/sites/all/modules/libraries/libraries.module)

It comes up all the time and it belongs  to the php and severity debug class of error messages.

I don't want to turn off the display of messages on the screen, just a particular class of message which come so often they are a nuisance.

It is possible to toggle their display on and off when required but still log them to the database?

You can use Disable Messages or look how they do it. Among other features you'll get a permission to specifically hide all messages of a given type from any role.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.

  Features

  Filter out messages that match a full text string exactly.
  Filter out messages that match a regular expression.
  Permissions to specifically hide all messages of a given type from any role.
  Disable all filtering for specific users.
  Disable all filtering for specific paths.
  Apply filtering only for specific paths.
  Debug system to get messages in the HTML without showing it to the end users.

Apart from that I found this little gem:

function MYMODULE_preprocess_status_messages(&$variables) {

  // The exact message you want to filter.
  $message = 'Further instructions have been sent to your e-mail address.';

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {

      // Limit it to a certain type if you want to.
      if ($type == 'status') {

        $pos = array_search($message, $messages);

        if ($pos !== FALSE) {
          unset($_SESSION['messages'][$type][$pos]);
        }
      }
    }
  }
}

Source: https://api.drupal.org/comment/51793#comment-51793

Here's another alternative to filter all messages of a certain type.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  $hide_types = ['status', 'error', 'warning'];

  if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $type => $messages) {
      if (in_array($type, $hide_types)) {
        unset($_SESSION['messages'][$type]);
      }
    }
  }
}

You could also easily get the $account = global $user and check its roles to tighten this request if you need.

Last but not least – not recommended - you can remove or if-wrap the <?php print $messages; ?> variable in your theme's page.tpl.php. But editing templates for this kind of logic should be considered bad practice.


Preview with another theme I'd like to preview using a different theme, but I'd like the admin theme to be used for everything else related to content editing and creation.

I've tried out the "pageview" module, but it does not work the way I expect it to.  This could be related to a conflict with other modules related to themes, such as Role Theme Switcher and Mobile redirection tools.

You may find the ThemeKey module useful.  This module allows you to define arbitrary rules to determine when to show each theme.  You can make as simple or as complex a configuration as you want.

From the module page, the following features are supported:

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server

See the documentation for more details.


Drupal7 REST Basic Authentication not working (Postman) I configured my rest with services and installed the Basic authentication module.

I used Postman and selected basic authentication gave username and password, I got "Missing required argument username"

An important note is that If I change it to "no Auth" and send my username and password as JSON object it's authenticating, can someone help me? Thanks.

Everything seems fine, as the response says, 'username' name/key is missing from the request. So construct a body request like follows or else follow the screenshot

{"username":'myusername', "password":"mypassword"}


Placeholders and the query builder? I read on the drupal.org site: "Never put a literal value or variable directly into a query fragment, just as literals and variables should never be placed into a static query directly (they can lead to SQL injection vulnerabilities) http://drupal.org/node/1848348

$query = db_select('node', 'n');
$query -> condition('node', $nid);
$nodes = $query
-> fields('n', array('title'))
-> execute();

Does this also apply to queries written with the query builder, like the one above? If so, how should it be re-written?

Thanks

To clear out the confusion, a static query usually refers to a raw mysql query that you use through db_query() function. You write the entire query and pass it as the first parameter of the db_query function.

Dynamic queries, like the one you have in your question, is called dynamic query which makes it really easy to build the query dynamically. Think about a query that you need to iterate through a dynamic list of conditions. You will need to fight with string related functions to build the query, that you can now use the query builder to do for you!

If you use something like this:

$result = db_query('SELECT n.title
FROM {node} n WHERE n.uid = :uid', array(':uid' => $uid));

It's considered safe against SQL injection (when you query the node table for users, always pay attention to their access permissions).

But this:

$result = db_query('SELECT n.title
FROM {node} n WHERE n.uid = ' . $uid);

is bad! We can't make sure that $uid will be completely safe to throw into the database.

  Does this also apply to queries written with the query builder, like
  the one above?
  With Query builder, you will not need to use these parameters (:uid from above "good" example) in most queries. WHERE, ORDER BY and other clauses have their own methods that you can use in the query builder. Your code in the question is in the correct format.

In case you need to use a variable in the query, do use parameterized pattern.

Correct:

$query = db_select('node', 'n');

$table_alias = $query->join('users', 'u', 'n.uid = u.uid AND u.uid = :uid', array(':uid' => 5));

Wrong:

$query = db_select('node', 'n');

$table_alias = $query->join('users', 'u', 'n.uid = u.uid AND u.uid = ' . $uid);

(I'm aware that above query couple do not make any sense :D Just copied from the linked page in your question)


Content Type with Tabular Data to be Input I'm building a content type that is going to require tabular data to be input. Here's a mockup of what the table should look like:

Rows 1 and 2 are fixed headers, 3-6 are data.

I am at a total loss as to how I should build this. I've experiemented with a few modules (like TableField... which is not really what I'm looking for).

Am I approaching this the wrong way? Is there a module that I'm not aware of that can do this?

did you try to use field_collection? (separate the E.Coli in 2 fields EColiB and EColiE ... and maybe some CSS to style it) - perhaps this is not a solution, I am posting it here since I am couple of points short and cannot leave comments for additional info under the original post


Unique domain for each organic group Im trying to make it that each OG has its own URL eg. www.group1.com, www.group2.co.uk etc There was a module to do this apparently but not for D7. You'd think it streight foreward but it isnt. Probably due to path module. Everything I try gives me permission errors. Im using D7 and Cpanel. Any help would be really appreciated.
Thanks
Steve

You can accomplish this with the Rules module, and the Domain Rules module.

  Adding Rules module actions related to Domain Access module.
  Allowing automation of different actions needed to create/modify/delete domains.

  First version includes:

  rules_action_create_domain - create new domain using given arguments
  rules_action_delete_domain - delete existing domain
  rules_action_set_user_defaults_domain - set a given role access to a given domain
  rules_action_set_node_domain - set domain to a node
  rules_action_set_domain_theme - set a theme to a given domain


Form validate & submit functions not firing on form loaded with AJAX I've created a form that is loaded with ajax when clicking on a button, but the form validation doesn't work (and so is my custom submit function).
The regular (Drupal's) form validation did work when I used MENU_NORMAL_ITEM and entered the form to a test page, but now when I'm using the current code it's not working.

I guess that when I'll manage to "fix" Drupal's form validation I'll also be able to use my custom submit function.

My code:

function MYMODULE_menu() {
  $items['ajax/my_ajax_page'] = array(
      'title' => 'My title',
      'page callback' => 'MYMODULE_my_ajax_callback',
      'type' => MENU_CALLBACK,
      'access arguments' => array('access content'),
  );

  return $items;
}

function MYMODULE_my_ajax_callback() {
  print render(drupal_get_form('my_form'));
  drupal_exit();
}

Thanks.

Well im not so sure about exiting...

i would try in my ajax callback:

function MYMODULE_my_ajax_callback() {
  $commands = array();
  $form = drupal_get_form('my_form');
  // im doing a replace command as an example, this could be another command invoked..
  $commands[] = ajax_command_replace('#container-to-append-form', render($form));

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


Build taxonomy categories with views, only children I am trying to build a menu with taxonomy terms and views.

Lets say that I have a tree of taxonomy terms

Parent-1

child-1.1

grandchild-1.1.1

greatgrandchild-1.1.1.1
greatgrandchild-1.1.1.2

grandchild 1.1.2

child-1.2

grandchild 1.2.1

greatgrandchild-1.2.1.1
greatgrandchild-1.2.1.2

grandchild 1.2.2

I am having problems viewing only the children of the taxonomy menu. I want to exclude the current level, and only see the children, not the grandchildren of an item. So for instance.

When I am viewing child-1.1, I only want to see grandchild-1.1.1 and grandchild-1.1.2, not any of the great grand children. I don't want to see child-1.2 or the parents.

Thank you very much for your help!

Can you set up your Taxonomy view to accept the argument Parent term and pass it the current term? I don't know how complex your view is, but I got it to work in this basic example:

View type: Term
Add arguments: Taxonomy: Parent term
Action to take if argument is not present: Hide view / Page not found (404)
Validator: Taxonomy term
Argument type: Term ID
Add fields: Taxonomy: Term Term

That will display only the current term's children, i.e. those that have the current term as a parent.


Add fields to user roles I'm using Drupal 7 to create a project linking organizations to volunteers. My initial approach is to use profile module to create different profiles for each role (volunteer & organization). Is it possible to create new fields which would attach only to a selected role?

This is a great example use-case for the Profile 2 module.

As listed on the project page:

  Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)


Make a copy of an installation I am trying to create a copy of a Drupal installation in a different folder.

I want to copy the site that is located on https://my-url/drupal to http://my-url/copy. I copied all the files in the Drupal root to the copy folder and I exported and imported the database in a new database and also changed the database configuration of the copy site using settings.php (copy/sites/default/settings.php).

When I put the main site on maintenance mode though the copy site is also put on maintenance mode.

Am I missing something here?

Thanks to @Clive giving me an indication that is something to do with memchache I followed these steps to resolve my issue.

Disabled the memcache module.
Commented out the memchache configuation settings in the settings.php of the copy site.

This resolves the issue.


Determine the row number of an unformatted row in views I'm using the Views module with the unformatted style with full content, and I'm using node.tpl.php to style the row. I'm looking for a way to determine what row it is (e.g. I want to style the first row different than the subsequent rows).

Is there any variable that is available to the template? Is this something I would have to add into the template.php (via a pre-process function, or something of that nature)?

Views already wraps each row in all sorts of CSS classes, like views-row, views-row-#, views-row-first, views-row-last, etc, so if all you want to do is STYLE things differently, you can use these classes.  Now, if you want to re-arrange the CONTENT of your node, that's a whole 'nother story...


Removing header region I am completely new to drupal. I am trying to customize the Acquia Marina theme to suit my upcoming site. The original layout is as shown in the screenshot:

I want to remove the white band that is the header region and move the logo and title down to the blue band right below it. Basically, have the blue strip function as the header. Is that possible. I have tried removing the header and header-top regions from the info file but that did not make any difference.

You need to change the html structure for this. Open page.tpl.php then remove the header section from there.


How to use Tamil language in my website? I have installed the language selection page module. I have Tamil, English language to be chosen by users.

If user chooses English means site will appear in English Language. If user chooses Tamil language means site will appear in Tamil language.

So, how can I install Tamil language in Drupal 7.34?

Use Internationalization module to make your site multi language. It gives you translate interface for every language you select in configuration.

After enabling the module you have to add Tamil as language under admin/config/regional/language/add.


How to hide a field (cck) based on a date field? I am looking for a way to hide a content field based on the nodes date field.

Example:

Event Name: Some Name Here

Event Date: 12/12/2012

Event  Location: Somewhere

Buy Tickets: ticket.com

If the date has passed I would like the Buy Tickets field to not show ... any help would be appreciated.

The solution is very simple. In template.php file implement MY_THEME_preprocess_node(). Example:

function MY_THEME_preprocess_node(&$variables) {
  //  dpm($variables);
  if($variables['type'] == 'MY_CONTENT_TYPE') {
    $date_field_value = $variables['content']['field_DATE_FIEL_NAME'][0]['value']; // find the correct value of your field

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($variables['content']['field_DATE_FIEL_NAME']);
    }
  }
}

you can also use hook_node_view:

function MY_MODULE_node_view($node, $view_mode, $langcode) {
  if($node->type == 'MY_CONTENT_TYPE') {
    $date_field_value = $node->content['field_DATE_FIEL_NAME'][0]['value'];

    $converted_date = strtotime($date_field_value);

    if(time() > $converted_date) {
      hide($node->content['field_DATE_FIEL_NAME']);
    }
  }
}


Outputting main menu in full in page.tpl.php I'm using the code below to print my main menu in page.tpl.php:

<?php
$main_menu = menu_navigation_links('main-menu');
print theme('links', array(
'links' => $main_menu,
'attributes' => array(
'id' => 'main-menu',
'class' => array('links', 'clearfix'),
),

'heading' => array(
'text' => t('Main menu'),
'level' => 'h2',
'class' => array('element-invisible'),
),
));
?>

However, it is only outputting the top-level menus of my navigation. Is there a piece of code I can add that will output submenus too?

Calling menu_navigation_links() with only the menu name by default provides only the top level links.  To delve deeper you need to provide the second $level argument, eg:

$main_menu =menu_navigation_links('main-menu', 1);

will provide the top and next level links, and:

$main_menu =menu_navigation_links('main-menu', 2);

will provide one level deeper.


Redirect after user login I would like to redirect users after they log in. Is it possible to use hook_user_login() to make the redirection? How do I add the parameter for the redirection?

You need to alter the login form and add a submit handler which will take care of the redirection. You cannot use $form_state->setRedirectUrl() directly in the form alter, since it will be overwritten by UserForm::submitForm().

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
  $form['#submit'][] = 'mymodule_user_login_submit';
}

/**
 * Form submission handler for user_login_form().
 *
 * Redirects the user to the dashboard after logging in.
 */
function mymodule_user_login_submit(&$form, FormStateInterface $form_state) {
  $url = Url::fromRoute('mymodule.dashboard');

  // Check if a destination was set, probably on an exception controller.
  // @see \Drupal\user\Form\UserLoginForm::submitForm()
  $request = \Drupal::service('request_stack')->getCurrentRequest();
  if (!$request->request->has('destination')) {
    $form_state->setRedirectUrl($url);
  }
  else {
    $request->query->set('destination', $request->request->get('destination'));
  }
}


How to add JS Confirmation popup when clicking an #AJAX button in custom module? $form['button4'] = array(
'#value' => 'RESET',
'#type' => 'submit',
'#submit' => array('form_test_form_button4'),
'#ajax' => array(
  'callback' => 'ajax_example_submit_driven_callback1',
    'progress' => array('type' => 'none'),
    'wrapper' => 'deletevalue',
    'event' => 'click',
),

);

This is the RESET button I want to ask Are you sure?.

AJAX submit also working fine. But POPUP Confirmation not working properly.Please anyone guide to me?

If user click the OK button the data will be reset.

JS

$('#edit-button7').on('click', function(){
var r = confirm("Are you sure you want to reset?");
});

If user click the CANCEL button also data was reset.

I could have sworn it was on so somewhere. But I could not find it quickly. You can try this using the form API in your button. Found here

 '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}')

You can of course use JS as you were. I think you were missing the return false;


Getting the name of a tag I've noticed that in using the default Drupal 8 API to get a feed of articles (using the REST View) the Tags field is returned as the following:

"field_tags" : [{
  "target_id" : "1",
   "target_type" : "taxonomy_term",
   "target_uuid" : "4d2cac04-a0a6-4c0a-8c13-34ba44a474f0",
   "url" : "\/site\/taxonomy\/term\/1"
}]

This returns an entity reference, but you never get the actual name of the tag. In the above instance, the name of that tag is actually Lorem. I can't seem to find a way of adding a property into the field_tags object to include the actual name of the tag. Is there a way?

What @Clive said is the right answer as far as core goes. You have to make another request.

There are some contrib projects that provide more flexible interfaces. One of them is https://www.drupal.org/project/graphql, which allows you to execute a query and specify what data you want to have shown. I believe it's still fairly experimental though.


Exclude nodes referenced from another content type's node I have two content type:

Content type A
Content type B

In content type B I have one reference field which referencing Content type A.
Now I want to build a list of Content type A, which is not reference yet (from content type B).
I was did it in drupal 7 by RELATIONSHIPS (referencing field_name), and FILTER CRITERIA (NID Is Null /(empty)
But in drupal 8 its not working, I search everywhere but didn't able to solve this issue. So I am here for your help.
Thank you so much.

In content type B (basic page), I named the refence field field_ref_article
1) Create view of content type A (article)
2) Add relationship "Content Using [field_name]"

3) Leave require unchecked

4) Add FILTER CRITERIA of [field_name]

5) Set relationship to [field_name] and operator is empty (null)

Overall should look like this


Commerce Kickstart: How To Add Sort Fields To Search API? I've been playing with the Search API and I can add new Facet Displays and filters, but no matter what I try I can't get any fields other than Price, Latest and Title to appear as Sort options. What's the 'trick'?

For other travelers, the answer is that it's a bug with a patch that has not been made part of the official distribution as of 26 Sep 2014. See #6 for the patch.

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


How can I change the precision in the decimal field of CCK? I have a decimal field.  The field has a minimum precision of 10. Can I change this precision?  I need that the numbers allowed have the next format:  19.1, 20.3.  In other words that the number be  of  2 integers and one decimal.

I select one decimal in the configuration of the decimal field , however the field accepts big numbers.  How can I change this, the solution can be with form_alter.

Thanks.

yeah, _node_validate is a flexible way. an alternative to a custom module, can be use a Rules module and integration with Rules Forms support module. Also will be useful use a more flexible CCK field, then, this will allow to validate whatever number with the model that you want.
.1. install the modules.
.2. then we need now is indicate to rules in what form must work. You must go to Rules > Form events and enable the option Enable event activation messages on forms. then go to the respective form and click in the Activate events for.. (the name of the form)
.3. go to rules and add a new rule and select in the Event: the respective event on which you want to evaluate this rule. (to this case Rules Forms modules will include the name of your form in the Rules Forms section on the Event select list.
.4. In a condition of rule add a numeric comparison (or whatever other condition that you want, for example a custom php code):
example with numeric comparison:
field Number 1 (php code): $number= $form_state['values']['number'][0]['value']; if ($number < 10 || $number > 100) { echo 1; }
Field Comparison: Equal to
Field Number 2: 1
.5. in the action option, of your rule, add an action like a form error message to warn about change the syntax of the number. in Form element ID add the ID of the field, for example field_color (you can review the name in the list of fields CCK of the content/node type).
.6. Create a new rule if is necessary, like $number= $form_state['values']['number'][0]['value']; if (...) { echo 1; } and add the respective error message.
do not forget enable the rule, to see working your rule!.
(I hope that this information be useful)


Create dependent dropdown in views exposed filter I've created a view of users. It includes two exposed filters as drop downs to filter the list. One is for the city and the other for the squadron. The squadron drop down is related to the cities as cities is a taxonomy vocabulary that gets added to squadrons. I would like to find out if it is possible, that when someone selects a city, to automatically filter the squadron drop down filter by that term.

I did this in a form for creating squadrons using ajax (node/add - with help here: see Dynamic select list in the form (dependent dropdown)) but don't know how to do it (or if it is possible to do) in a view exposed filter.

Many thanks in advance

(edit: I'm using D7 and Views 3)

I haven't check but

{
  $form['computer_stats']['os'] = array(
    '#title' => t('Operating system'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array('', t('OSX'), t('Linux'), t('Windows'))),
    '#ajax' => array(
      'callback' => 'input_os_verify_ajax_callback',
      'wrapper' => 'input_os_verify_wrapper',
     ),
  );

  // Setting an empty element with a wrapper to be populated.
  $form['computer_stats']['os_verify'] = array(
    '#type' => 'markup',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // When submitted, check for value of OS, and populate os_verify.
  if (isset($form_state['values']['os'])) { // Fixed this line, was throwing an error in the original video code.
    $form['computer_stats']['os_verify']['#type'] = 'checkbox';
    $form['computer_stats']['os_verify']['#title'] = t('Are you sure you are using @os?', array('@os' => $form_state['values']['os']));
  }

  ...
}

function input_os_verify_ajax_callback($form, $form_state) {
  return $form['computer_stats']['os_verify'];
}

from How to Build Beautiful Forms in Drupal 7 (Video Presentation) might help


How to organize my content as timeline I've started learning Drupal a few months ago and I can say that the community is great and that I haven't had the need to ask a question here until now.

I've started to work on a project and I have a problem with one part.

I need to create something like timeline. There is a requirement for a line where the titles of nodes would be listed according to the date of creating, and I need to list some of the fields of those nodes (like text, image...).

The main problem for me is that I have to show the nodes through views because of some additional filters. I've tried a few available modules and they work great, but the problem with them is that they are vertical, and what I need is a horizontal timeline.

I've tried A Simple Timeline and Ajax Timeline module.

Is there maybe some other module that I haven't found and that could be useful for what I need?

Off course, It would be great if someone more experienced could give me some idea from which I could start working.

I just want to mention that I'm using the latest Drupal version (7.34) and I installed the latest version of Views module (3.8).

Thanks in advance.

I did build a fancy timeline using module 'jQuery timelinr integration', which only is a style for Views letting you render your data as a timeline.

Check the library demo : http://www.csslab.cl/ejemplos/timelinr/latest/horizontal.html

Here the full project : http://www.csslab.cl/2011/08/18/jquery-timelinr/


Create a block with information regarding the number of comments and contents created in a specific group I am using Drupal commons 3.31.
I would like to know how many contents and how many messages are written within a group and  make a block out of it. Also be able to see how many comment,page a specific user has created.

Thank you

It sounds like this can be accomplished using the views module. Create a view of content from the group you are wanting, and then turn on aggregation. For each field, you can set it to display a count() of the field results.

For the per user part, just set up a filter/contextual filter for the UID.


What is the difference between hidden and value types in form API? In Drupal's Form API page mentioned both hidden and value will not display to user.

What is the difference between them?

With the hidden form element, the HTML output in the form is <input type="hidden" /> (plus other HTML attributes), while with the value form element nothing is output for the form. The value is simply kept in the cache Drupal uses for forms created with the form API, but nothing is sent to the browser. (In other words, the value is kept on the server side.)

Generally, the "hidden" form element is used when the value is used from JavaScript code, but it is not a value editable, or visible in the form.


Exposed form for contextual filters when using non-taxonomy filters? I have a View with some contextual filters which works great. I also need to provide my users with some way to change the filters once they're on the page.

I've tried using exposed filters but I'd rather use path arguments over query string parameters and there is the conflicting issue between exposed filters and contextual filters which the Views Filter Harmonizer module address but in my case this doesn't work as I'm using some non-taxonomy filters.

So basically what I'd like to do is have a form which allows users to select values which could be passed as contextual filters.

Any help/guidance?

To find "... some way to change the filters once they're on the page ..." (as in your question), it may help if you take a look at the (free) video about Contextual filters with paths. It covers these topics:

Using contextual filters for filtering Views result.
Using input from the view path to set contextual filter values.
Using contextual filter values for changing the view title.

You may also want to watch some (or all?) of these related videos, also about contextual filters, sometimes called "arguments" also (quotes are from the links mentioned):

Action if no contextual filter value is present, with these topics:

  Different views behaviours if no contextual filter value is present.
  Some words about why 'provide default value' is a bad concept.
  The provide summary option.

Contextual filters and menu tabs, with these topics:

  Using contextual filter values inside a path (instead of at the end of it).
  Re-using existing site paths to get contextual filter values.
  Creating menu tabs in Views.
  Creating a menu tab on user pages, to display all articles created by the user.

Default menu tabs, with these topics:

  How to use the default menu items in Views.
  How to create sub tabs.
  How to use default menu items together with contextual filters in the path.

Validation of contextual filter input, with these topics:

  How to validate input for contextual filters.
  Some options for how to validate the input.
  Why it is a good idea to validate contextual filter input.
  Views behaviour if the filter input doesn't validate.
  Some words about not being able to validate contextual filter input with multiple values.
  Perhaps some words on filter validation being able to alter the filter value.

Contextual filters and default values, with these topics:

  What default contextual filter values are.
  How to set default contextual filter values.
  Some examples of extra settings for default contextual filter value.
  Some words about why it is a bad idea to let the view make assumption about the context where it is embedded.
  Some more words about why it is a bad idea to let the view make assumption about the context where it is embedded.
  Some words about using default contextual filter values when creating Views blocks.


How to change taxonomy term path for table and grid view I am using taxonomy term module. I have categories vocabulary and in term so many categories and I have created the view using taxonomy term.

With two page first is in table format and another is grid format and in both view page header I place the two icon one is list icon and another is matrix icon.

My issue are that when I click on list icon the page redirect to table view and path are show taxonomy/term/% but I want show the path in this format [vocabulary name]/[term name]/[tid]/list

In Pathauto, for taxonomy term paths, put

[term:vocabulary]/[term:name]/[term:tid]/list

Then click on the Bulk Update tab and check mark Taxonomy term paths and then click Update.


How to sort name by alphabetically in drupal views? I have created view in this drupal 7 views,there are Two pages are created in that view.

page 1:Images page
page 2:List view page

here i have tried in List view page by using sort criteria of Name field(ASC or DESC). but Names are sorted in List view page correctly.

When i am click Name field for sorting in second page(List view) automatically that fields are sorted in first page(Images) page also.
That sorting is not working in views.
First page taking only default sorting order.

Here is screen shorts

Here sorting values are not stored database permanently.If i click refresh button views default sorting behavior is added to that pages.
Is it possible to sort the two view pages permanently?

we have a module called Views Glossary once u install the module we have to enable in stucture->views->glossary view like archive for dats and months


Update user email in custom module : validation API returns "Your current password is missing or incorrect" Users can update their email and user name in a form (Form API) in a custom module. The reason is it also updates an external service.
It works well but I’ve noticed an error during our test if a user enter an existing email (which is forbidden).
So I’ve added a validation $user->validate()
Now, I have this error message :

Your current password is missing or incorrect; it's required to change
the email/.

I don’t know how to proceed. Should I retrieve the user password  and send it again $user->setPassword($password); ? I've search on SO, Drupal Doc, etc. but I didn't find the correct way to do this.
Here is my code :
$uid = \Drupal::currentUser()->id();

// Get user storage object.
$user_storage = \Drupal::entityManager()->getStorage('user');

// Load user by their user ID
$user = $user_storage->load($uid);

 /**
 * Validation API
 * https://www.drupal.org/docs/8/api/entity-validation-api/entity-validation-api-overview
 */

  // Update email
  $user->setEmail($new_email);

  // Update username
  $user->setUsername($new_email);

  $violations_user = $user->validate();
  if ($violations_user->count() > 0) {
       $violation = $violations_user[0];
       drupal_set_message($violation->getMessage(), 'warning');
       // Here is the message "Your current password is missing or incorrect"
  } else {

      $user->save();
  }

The violations you're seeing come from core's ProtectedUserFieldConstraint. The constraint is applied when the current user tries to update their account fields without supplying a password. The validator method has a built-in flag to disable this check when needed (e.g. when a user resets their password).
To set the flag, set the _skipProtectedUserFieldConstraint to TRUE (e.g. $user->_skipProtectedUserFieldConstraint = TRUE;) and the validator won't enforce supplying a password when changing the current user fields.


"Limit list to selected" and default to all selected? When I set up an exposed filter with the "Limit list to selected items" option enabled, and select a subset of items in the "Options" list, when the view is presented, non of the selected items are selected by default.

If I turn off the "Limit..." option, then all items (checked and not) are shown, with the checked items selected by default.

Sorry if I'm not describing it more clearly, but I would like a limited list displayed, with all of its items selected by default.

Suggestions?

BTW - I'm using Better Exposed Filters to display the selection items as checkboxes and the exposed form is shown in a block.

Thanks.
Bill

If you want to define a default value for a limited list of items in a Views exposed filter, you can achieve it by altering the exposed filter in a custom module:

function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  $filter_field_id = 'my_filter_identifier';
  if (isset($form[$filter_field_id])) {
    $options = array();
    $options['First option value']  = 'First option label';
    $options['Second option value'] = 'Second option label';
    $form[$filter_field_id]['#type'] = 'select';
    $form[$filter_field_id]['#options'] = $options;
    $form[$filter_field_id]['#default_value'] = 'First option value';
  }
}

In order to make it to work, you need to uncheck the "Limit list to selected" option in the Views exposed filter. Of course, you also need to know the real values of your list items.

If your Views default value includes multiple options from the list, and you do not want to allow the user to select multiple options at once, you will also need to add a new filter blocking the other undesired options.


How to embed fields from a view to another view´s exposed filter I am stuck with this problem. I created a view (type=term) with exposed filter. Thanks to http://leanderlindahl.se/en/dynamically-filter-content-drupal-view/ I managed to display the exposed filter as a list of "buttons."

Now I want to display fields of content with these taxonomy terms in the exposed filter.

My knowledge of php is very limited, sorry for newbie mistakes. I learn new things every day.

my .module:

function exposedfilter_buttons_form_alter(&$form, &$form_state, $form_id) {
if ($form['#id'] == 'views-exposed-form-test-lektori-page') {
$form['#attached']['js'] = array(
  drupal_get_path('module', 'exposedfilter_buttons') . '/js/exposedfilter_buttons.js',
);
$links = $form['tid']['#options'];
$newlinks = array();
$my_value = views_get_view_result('lektori', 'block_1'); //trying to obtain results of the second view

foreach ($my_value as $key => $result) { //trying to assing results to $key
}
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
   $newlinks[] = array('data' => '' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '', 'class' => array('pop-filter-label'));
}
}

$prefix = theme(
  'item_list', array(
  'items' => $newlinks,
  'type' => 'ul',
  'attributes' => array('id' => 'pop-filter-list'),
  'container_id' => 'scope-list-wrapper',
));

$form['links'] = array(
  '#type' => 'markup',
  '#value' => $prefix,
  '#markup' => $prefix,
);
}
// extra submit form handle
$form['#submit'][] = 'exposedfilter_buttons_form_submit';
}
// handle form submition
function exposedfilter_buttons_form_submit($form, &$form_state){
$values = $form_state['values'];
}

What I need: $my_value[$key]->node_field_data_field_workshop_lektor_title should have $key obtained as a value 0 or 1 or 2.... so it will display correct name according to $key.

Image to make things more clear:

Any help is highly appreciated.

I think you made a mistake in the foreach loop:

foreach ($my_value as $key => $result) { //trying to assing results to $key
}
foreach ($links as $tid => $term_name) {
if (taxonomy_term_depth_get_by_tid($tid) == 1) {
   $newlinks[] = array('data' => '' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '', 'class' => array('pop-filter-label'));
}

should be something like

$view_results = array_keys($my_value);
foreach ($links as $tid => $term_name) {
  if (taxonomy_term_depth_get_by_tid($tid) == 1) {
    $key = each($view_results);
    $newlinks[] = array('data' => '' . $term_name .'  ' . $key . /*so we directly see its value for control */' '. $my_value[$key]->node_field_data_field_workshop_lektor_title . '', 'class' => array('pop-filter-label'));
  }
}


How to attach/upload a file to node using restws? I've got a content type with "File" field and "File" widget. I am successfully able to create a node without a file using restws. But, if I want to attach a file to it, it just doesn't allow me to do that. I've tried many different things, but with failure.

Also, when accessing a node with file already attached to it, using get request (e.g. {domain_name}/node/219.json), the file field is displayed as an empty element, even though file is existing and is displayed fine when viewing the node in edit mode from admin area.

E.g.

JSON:

"field_simple_file":[]

XML:

<field_simple_file/>

The node array without file field, that succeeds is as below:

$new_node = array(
    'body' => array(),
    'type' => 'simple',
    'title' => 'Content created with restws',
    'language' => 'und',
    'status' => 1,
    'promote' => 0,
    'sticky' => 0,
    'author' => 1
);

And content-type:

'Content-Type: application/json'

But I think, I am not 100% sure on how to include a file in it (have tried few different things), which might be leading to failure. Can anyone provide me with guidance for attaching/uploading a file with restws please?

Here is the URL to access a node with file already attached to it

{domain_name}/[end-point]/node/219.json

Here 219 is the nid of the node.

Here is the sample JSON format to attach a file to node (node create).

{
    "title": "title_of_node",
    "type": "bundle_name",
    "field_samplefile": {
        "und": [{
            "fid": "17",
            "filename": "changes.txt",
            "uri": "public://changes.txt",
            "filemime": "text/plain"
        }]
    }
}


How to get all users with a specific permission Is there a way to retrieve all users with a specific permission (eg "Post comments").
I only found the possibility to get them by their role:

Drupal::entityQuery('user')
->condition('status', 1)
->condition('roles', 'administrator')
->execute();

or

Drupal::service('entity_type.manager')
->getStorage('user')
->loadByProperties(['roles' => 'administrator']);

I had to get the roles that had a given permission to get users with a permission, example:
$roles = user_role_names(FALSE, 'example_permission');
$rids = array_keys($roles);

$uids = Drupal::service('entity_type.manager')->getStorage('user')->getQuery()
  ->condition('roles', $rids, 'IN')
  ->execute();

Apparently thats what Drupal core does in the permission filter for views, see:
\Drupal\user\Plugin\views\filter\Permissions
Hope that helps some!


How to redirect to a node/add page after clicking on a flag link I want to set a flag to link to a node creation page - i.e., when a user clicks on the flag ("Apply for this Job") they should be redirected to a Job Application creation page where they can fill out an application for the job.

So for flag action I selected the "Redirect to URL" action and entered node/add/job-application. But when a user clicks on the flag there's no such redirection, the user is never sent to the node creation page. Am I missing something or just using the wrong method?

Ok, I myself test this for you, please first install and enable Rule and Rules UI  ,after it (I suppose you have a flag with 'myflag') .
Go to dmin/config/workflow/rules  and Add new rule ,set your name and in  React on event  in flag group select A node has been flagged, under "myflag"  save it ,after it in Actions section  choose Add action , in Select the action to add in system group choose Page redirect ,after it set your path want to redirect it in Value. (is better check Force redirect).
I hope works for you correctly.


How to check if a field has more than one value I am working on a field template to display images in a carousel (I'm using BootStrap). My field is named “galerie”
I copied field.html.twig from the core and saved it as field--field-galerie.html.twig
I managed successfuly to add the necessary markup for BootStrap carousel to work.

The wrapping markup displaying the carousel and its control shows up when there is only one image. I thought it would not. It opens after a {% if multiple %} condition and closes before the {% else %}.
My understanding is that {% if multiple %} only checks if the field is set to accept multiple values.

I don't know how to write an condition in twig checking if the field contains one image or more, to trigger (or not) the carousel thingee.

Use the length filter, which also works on arrays:

{% if items|length > 1 %}
  field contains more than 1 item
{% endif %}


Does Views RSS display deals with relationship I have a content type "Event" which has a relationship with the content type "Category", via the node reference field 'category_ref'.

The "Category" content has a field "Image".
I have figured out how to display the field "Image" in a page view listing the "Events" node, with relationship option on "Image" field.

It works just fine, except that I would like now to create a feed for this view, to export it on Facebook. But then, as there is no field to set up for RSS feed, I don't know how to fetch the image from "Category" and get it in my RSS.

The point where I'm stuck is that the relationship is set on the RSS display tab, but the image does not show.

Is there a way to do fetch datas from another content type than the one of the views via the RSS display of the Views interface?

It sounds like you want the Views RSS module.  It will add a new plugin that will allow you to map arbitrary fields to RSS elements at the channel and item level.

So, if your view is fielded out with the proper relationships already, you can just add a new display, map the fields, and assign it to a path, all in about 10 min.

The help in the module is also excellent.


How to enable users editing their CiviCRM profiles details from their Drupal user page? I have a new Drupal7 instance with CiviCRM integrated. I have successfully linked CiviCRM contacts (specifically CiviMember members) to users in Drupal with the role of 'member'.

I want members to login and edit their CiviCRM profile. How do I go about doing this?

Create a CiviCRM Profile (or reuse one of the existing ones) by going to Administer >> Customize Data and Screens >> Profiles and set it to be enabled on "View/Edit Drupal User Account". Then the user will be able to edit their details from their Drupal user page.

See this Demo Profile on CiviCRM Demo site and notice that "View/Edit Drupal User Account" is checked. Take a look at this tab on the Drupal user page. The fields in the Profile can be edited.

For more details see: the CiviCRM book section on Profiles.


What options are there to allow users who have not logged in to see content on the home page? I have a site where users must log in to access content.  For the home page, I'd like these anonymous users to be able to view this content and the login box.  Below are the ways I have done this in the past, but I'm looking for comments on how others may do this.  Especially for ways that it could be done without touching templates or code.

Modify page-front.tpl.php when a user is not logged in.  This allows me to remove the "Access denied message"
Create a block that is displayed on the home page for anonymous users.  However, this still displays the "Access denied message"
Implement Taxonomy access and have a term that allows anonymous access.  This would eliminate the "Access denied message"

Are there other better methods to do this with as little code as possible?  What is the best way?

Thanks.

What kind of permission module are you using ? Is it possible you implement yourself these permission ?

I would restrict node access to anonymous user using a custom module implementing hook_node_access() and allow them to see the nodes on the front page (using the function drupal_is_front_page()):

function MYMODULE_node_access($node, $op, $account) {
  if ($op == 'view' && $account->uid == 0) {
    if (drupal_is_front_page()) {
      return NODE_ACCESS_ALLOW;
    } else {
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}


Changing block position in Bartik theme I am using bartik theme to develop a website.I need the User menu and search block to be beside the logo and main menu block to be below the logo.
But all the menu and search blocks appear below the logo.How can I move the user menu and search block to right top corner of the page.

Thank you in advance.

you can change a position of menu and search block from structure > block link and assign it to * custom made region *, also use custom css can fix your problem.

also you can Demonstrate  the all region of theme from admin/structure/block/demo/bartik

hope this will help you


A hook that would check if the module is enable? I'm not looking for hook_enable (which would trigger when the module is been enable).

I have a module that would work alone (lets call it custom_module_1) and I have another module which is an add-on (lets call it custom_module_2) to that module to the custom_module_1. I want to be able to have a different behavior on the custom_module_1 if the custom_module_2 is enable.

So I'm looking for a hook that would be be using on custom_module_1 and would check if the custom_module_2 is enable.

Or how can I check if there is a module enable as a function to have a different behavior on another module ?

module_exists($module) will do that for you.  From the API:

Parameters
string $module: The name of the module (without the .module extension).
Return value
bool TRUE if the module is both installed and enabled, FALSE otherwise.


What is the best way to make a page that filters a content type using Ajax I tried to use Finder module, but I had some issues with pagination and some weird issues when I parameter it to use Ajax, some friends told me that I can use the Views module, but they couldn't tell if it supports or could be hacked to support Ajax calls. (I mean by hacked being extended)

I'm new to drupal, it's been like a two days learning and practicing, and I would appreciate any proposition.

Assuming you are using Drupal 7 Views is easily used and AJAX enabled. Advanced > OTHER > Use AJAX on the view edit screen. There are lots of documents, answers and functions to help you on your way.


Custom content translation links I have a multilingual Drupal site in english & french. At the bottom of every page is the content translation link, however I want to place this in a custom location on page.tpl.php.
So if I hide the content translation links in the configuration, how do I call it via a function on the page template?

This worked for me. Incase there was no translation node, I send the user to the homepage.

$tpath = translation_path_get_translations($_GET['q']);
if ($language->language == 'en') {
    if (array_key_exists('fr', $tpath)) {
        $tlink = "Français";
    } else {
        $tlink = "Français";
    }
} else {
    if (array_key_exists('en', $tpath)) {
        $tlink = "English";
    } else {
        $tlink = "English";
    }
}

print $tlink;


Displaying a list of all the content types I need to display a list of all the content types which links to their respective page, displaying the contents of that type.

I tried a bunch of wild guesses like $row->content and couldn't manage.

How should I achieve this?

I have done something similar using Views and the Summary option for Contextual filters.
I added the Content Type as a contextual filter with the following options:

The end result was a view that displays the following, if you have not specified a Content Type in the URL as an argument:

The only issue I found is that I won't display Content Types that have no content.


How can I add a header and footer field to all drupal generated blocks? I have a number of blocks that are created by drupal core, modules and views. In views blocks I can add a header or footer using the views UI, but I would also like to do this for other blocks not created by views. e.g. core search block. I would like to add a user configurable header and footer field to every block generated by drupal. This way a user can add arbitrary content above or below block content using the block UI. Doing this for all views blocks would be great as well as I would not have to give the client permissions and train them how to use the views UI to make changes.

EDIT:

Each block needs to have their fields configurable in the UI. I can't have laypersons digging into the tpl files.

Switching to an entity based block replacement such as the BEAN module is not an option. I need to keep the core block architecture and it also must be able to add headers and footers to core and module generated blocks (which are not beans, boxes etc)

You can use block.tpl.php

  Default theme implementation to display a block

And add html in the same template file.


CSS not loading on Chrome for drupal site after moving to https I have a Drupal site which has huge content. Recently I moved my dev content on production and also changed the site URL from http to https.
The problem is that the site is working fine on all browser except Google Chrome.
It is not loading the CSS. I can see the content but its without CSS.

I have the same setup for dev site and production site but still it is not showing any css.
If anybody has a solution please let me know.

Also I am using the same theme for dev and production.
In the site information it is showing the following message:

  This page includes other resources which are not secure.

The warning which you see is because some of the contents are not secure, which means they are fetched using http instead of https.
As per the limited information provided by you, I'd suggest you to follow the following steps:

Inspect the source code of the page, by pressing CTRL + U, in Chrome.
Check to see if there are links present in the content(specially the <head> section) are using the pattern http://... instead of https.
Find the resources (css/js/images) which are loaded using http.
Identify which part of the site (module or a theme function) adds that resource.
Make the necessary changes to make sure the resources are loaded securely i.e. via https.


Add new menu item in drop down admin menu I have a node. I would like to create a link to the node in the administration menu. Adding an item in the administration menu is not working. Is this not possible? How can i do that?

You can create more admin menu link from navigating to Management Menu, which you will find at this location -- admin/structure/menu/manage/management


Drupal 7 - Node specific template not working I have done some research and everything I see to create a node specific template says to name the template file, for example, page--node--676.tpl.php

However when I clear the cache and load the file it still shows the old template. What could I be missing?

If you haven't already done so, I'd recommend enabling theme debugging feature of Drupal 7.

In the settings.php file, or preferably in settings.local.php file if you have one, add the following line, and clear the cache once more.

$conf['theme_debug'] = TRUE;

  When debugging is enabled:
  - The markup of each template is surrounded by HTML comments that contain
    theming information, such as template file name suggestions.
  - Note that this debugging markup will cause automated tests that directly
    check rendered HTML to fail.

  For more information about debugging theme templates, see
  https://www.drupal.org/node/223440#theme-debug.

  Not recommended in production environments.

This should give you the available template name suggestions in the generated HTML.


How to require a JS library in a composer.json file I'm trying to require a 3rd-party JS library in my module. Unfortunately, the library is not available as a composer package.

I tried to define the library in my module's composer.json file like the following:

{
  ...
  "require": {
    "VENDORNAME/PACKAGENAME": "1.2.3"
  },
  "repositories": [
    {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    },
    {
      "type": "package",
      "package": {
        "name": "VENDORNAME/PACKAGENAME",
        "version": "1.2.3",
        "type": "drupal-library",
        "dist": {
          "url": "https://github.com/VENDORNAME/PACKAGENAME/archive/1.2.3.zip",
          "type": "zip"
        }
      }
    }
  ]
}

But, composer did a bit of complaining about that, and didn't even install the module:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for drupal/MYMODULE 1.x-dev -> satisfiable by drupal/MYMODULE[1.x-dev].
    - drupal/MYMODULE 1.x-dev requires VENDORNAME/PACKAGENAME 1.2.3 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

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

I should mention that I base this on Webprofiler module (Devel's sub-module). Though, in its README, it instructs defining those packages in the main composer.json file.

I want to define the JS library as a module requirement in module's composer.json file.

How can I require a code from a Git repository as if it is a composer package, and use it in my module's composer.json file?

The instruction in Webprofiler completely right and it's referral to composer.json in the root directory, here another example to add react to Drupal:

    {
        "type": "package",
        "package": {
            "name": "facebook/react",
            "version": "v16.3.2",
            "type": "drupal-library",
            "dist": {
                "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                "type": "zip"
            }
        }
    }

After that, I run:

composer require --prefer-dist facebook/react:16.3.*

Completely works fine and the package was download to libraries folder.

From what you posted I can see that you did not add the package information.

This need to be changed VENDORNAME/PACKAGENAME so in the above example:

VENDORNAME is facebook

PACKAGENAME is react

here is how you get this information, the attached image from React Github repository

also, you can find that information in the repository URL.

here is the full repositories part I have it in one of the projects I'm working on:

 "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        {
            "type": "package",
            "package": {
                "name": "d3/d3",
                "version": "v3.5.17",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/d3/d3/archive/v3.5.17.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "facebook/react",
                "version": "v16.3.2",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/facebook/react/archive/v16.3.2.zip",
                    "type": "zip"
                }
            }
        },
        {
            "type": "package",
            "package": {
                "name": "components/highlightjs",
                "version": "9.7.0",
                "type": "drupal-library",
                "dist": {
                    "url": "https://github.com/components/highlightjs/archive/9.7.0.zip",
                    "type": "zip"
                }
            }
        }

    ]

If your module defines external dependencies which not hosted on Packagist or Drupal.org then Drupal core will not automatically discover or manage these dependencies.

You must use the wikimedia/composer-merge-plugin package to accomplish this. This plugin is installed with Drupal core.

Thats why in Webprofiler module they add the instruction to readme not to the composer.json in Webprofiler directory.


display a node in the sidebar region of another node I'm a huge fan of annotating content in the margins of my real paper books.

In drupal 7, I want to be able to annotate a book page content type by showing a child of that page in the space beside the main page.

Has anyone done anything like this before in Drupal? Any links?

You might describe it like putting comments next to the page but I would prefer to use child pages if at all possible.

Thanks for any suggestions or help.

You could in your template file just render the comment section in your sidebar.


How to load jquery cookie library for anonymous user It seems  with login user jQuery Cookie added and worked correctly but when I visit my website with not login user(anonymous) then  I faced with TypeError: $.cookie is not a function. Why This happened and how can I attach jQuery cookie libraries for not logged in users by default?

Notes:
My theme is based on Drupal Bootstrap theme

For available Jquery and Jquery cookie for anonymous user, it should add it on  theme libraries dependencies , as example if your theme name is themename  on themename.libraries.yml add

  dependencies:
    - core/jquery.cookie