`composer require` fails because "Source directory docroot/core has uncommitted changes" Symptom: You have a script that fails while executing a composer require command, resulting in output like the following:

$ ./example.sh
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)

In VcsDownloader.php line 242:

  Source directory docroot/core has uncommitted changes.

Attempting to execute the offending composer require command manually results in output like the following:

$ composer require drupal/examples
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
    The package has modified files:
    M core.services.yml
    M includes/install.core.inc
    M includes/install.inc
    M lib/Drupal/Core/Config/ConfigInstaller.php
    M lib/Drupal/Core/Config/ExtensionInstallStorage.php
    M lib/Drupal/Core/Config/InstallStorage.php
    M lib/Drupal/Core/Entity/EntityViewBuilder.php
    M lib/Drupal/Core/EventSubscriber/ConfigImportSubscriber.php
    M lib/Drupal/Core/Extension/ExtensionDiscovery.php
    M lib/Drupal/Core/Extension/ModuleExtensionList.php
    19 more files modified, choose "v" to view the full list
    Discard changes [y,n,v,d,?]?

Conditions: You are using Composer to manage your Drupal site dependencies and applying patches with cweagans/composer-patches. You may be using Acquia BLT.

Explanation: The problem is that cweagans/composer-patches is applying patches to Drupal Core after cloning it, leading Composer to believe you've modified the affected files and therefore to prompt you to overwrite them lest you unwittingly lose work in progress.

Solution: Configure Composer to discard-changes which "[sets] the default style of handling dirty updates when in non-interactive mode... [to] always discard changes in vendors", then modify your script to pass the --no-interaction (or -n) flag. E.g.:

$ composer config discard-changes true
$ composer require -n drupal/examples
Using version 1.x-dev for drupal/examples
./composer.json has been updated
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
Deleting docroot/core - deleted
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/core (8.6.x-dev 8dbf42a): Cloning 8dbf42a90c from cache
  - Applying patches for drupal/core
    https://www.drupal.org/files/issues/2869592-remove-update-warning-7.patch (2869592 - Disabled update module shouldn't produce a status report warning)
    https://www.drupal.org/files/issues/2885441-2.patch (2885441 - EntityReferenceAutocompleteWidget should define its size setting as an integer)
    https://www.drupal.org/files/issues/2018-09-24/2815221-109.patch (2815221 - Add quickedit to the latest-revision route)
    https://www.drupal.org/files/issues/2018-10-12/1356276-531.patch (1356276 - Allow profiles to define a base/parent profile and load them in the correct order)
    https://www.drupal.org/files/issues/2018-07-09/2914389-8-do-not-test.patch (2914389 - Allow profiles to exclude dependencies of their parent)

Writing lock file
Generating autoload files


How to show nodes where the user is (not) in the reference field with Views? I have a content type with a multiple-values user entity reference field.

I need a view that shows (as two pages or within one view) (a) all the nodes where the user IS referenced and (b) all the nodes where the user is NOT referenced.

There is a relationship to the user reference field and a contextual filter (uid of the logged in user). This "positive" works and shows the nodes where the logged in user is referenced

But the view where the user is not referenced does not work. Is there a way to "negate" the contextual filter (uid of the logged in user)?

I have tried it in one view with an exposed filter (current user), but I could not solve the problem of having multiple user references. I tried the VIEWS distinct feature and the views_distinct modules.

You can use exactly the same you did for positive reference but with a single exception. You will see a checkbox contextual field setting names "Exclude". You can check that and the views will exclude the records which have not referenced.


Author Fields into a content type template I'm trying to load some of the information from the author into a node--article.html.twig. So I can provide some information like bio, social media,etc.

Similar to this...

I can easily get the author_name and the author_picture because these two are given by the template. I added extra field at admin/config/people/accounts/fields in this case the only extra field is field_bio

I try to use the include to add this user field into.

node--article.html.twig

{{ author_name }}

{% include('field--user--field-bio--user.html.twig') %}

This what I have on the field template - field--user--field-bio--user.html.twig

  {%- for item in items -%}
      {{ item.content }}
  {%- endfor -%}

Hello

The word "Hello" is been display on the node--article.html.twig; however, the item.content which is my field information is not been load. =(

I also try to dig up into the user variables by using {{ kint() }} to see if there is this information and I did not find it either.

I have seen some example with a module, which I have avoid them because this is for a contrib theme and I do not want to have any module dependency. I have done this many times with DS but I do not want to use any extra module.

So I have couple questions...

Should I use include for this use case or not ?

If I have too, what I'm doing wrong ? Why the item.content is not been load ?
If I should not use it in this use case, what should I do instead ?

Should I use include for this use case or not ?

This is not possible, you can't mix different templates like node and field because they have different variables.

  If I have too, what I'm doing wrong ? Why the item.content is not been
  load ?

item.content is only loaded in field, not in node template.

  If I should not use it in this use case, what should I do instead ?

You should define the user field you need in preprocess, examples for the two fields already defined:

function template_preprocess_node(&$variables) {
  $variables['author_name'] = drupal_render($variables['elements']['uid']);
  $variables['author_picture'] = user_view($node->getOwner(), 'compact');

A basic example to use this in your own hook:

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['user_field1'] = $node->getOwner()->field_field1->value;

And in twig

{{ user_field1 }}


List all bundle types for entity field query? Trying to use entity field query to simplify some times; e.g. a slide show of images.

How does one get the field values for entity field query. Specifically, get a list of all the possible bundle types there are?

E.g.

<?php

function foo_load() {
   $query = new EntityFieldQuery;
   $query
     // What conditions or properties are there?
     ->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'banner')
     ->propertyOrderBy('created', 'DESC');
     ->propertyCondition('status', 1);

}

If as per your example code you are just concerned with nodes then the bundles are just your node types.

If you want to get a list of node types you can use:

node_type_get_types()
or
node_type_get_names()

You can get the bundles from the array keys of the arrays returned from those functions.


Block visible only to the user who created it Is there any module that allows a block to be seen only by the user who created it, and not to any user with the same role?

You can use block visibility settings PHP code to check for specific users.

Please find the sample php code below.

<?php
global $user;
$allowed = array('moderator','administrator'); // Allowed Roles
$allowed_uids = array(1, 5, 10); // 1, 5, 10 are user id's which you want to allow
$valid=FALSE;
foreach($user->roles as $role){
  if(in_array($role, $allowed) && in_array($user->uid, $allowed_uids)) {
    $valid=TRUE;
  }
}
return $valid;
?>

See the screen show below where you need to write above code.


Disable Internal Page Cache And Enable Dynamic Page Caching Can some one let me know how to disable internal page cache and enable dynamic page cache. And also how to enable and configure varnish or memcache in drupal.
Can we enable and use both varnish and memcache ?
Does enabling of varnish or memcache will disable drupal's default dynamic page caching ?

There are two different topics involved here.

You can disable the Internal Page Cache if you want to replace it with Varnish (both are reverse proxies for anonymous traffic, delivering content before the request reaches Drupal, and you don't need two of them).
Memcached on the other hand is a memory based cache backend, that sits behind Drupal caches (you can configure which ones, this can also be the Internal Page Cache if it is still enabled).

  Can we enable and use both varnish and memcache?

Yes, they work independently from each other, one in front and one behind of Drupal.

  Does enabling of varnish or memcache will disable drupal's default
  dynamic page caching?

No, it doesn't make a difference for the Dynamic Page Cache, because it won't see any traffic served by Varnish or the Internal Page Cache and Memcached only makes it faster, but doesn't change how it works.

  And also how to enable and configure varnish or memcache in drupal.

There are modules to configure them. For Varnish to make it invalidate cache tags and for Memcached to set up the cache backend.


'Content Type' link not available for new content type I have created a new content type (I can see in Content type list), but this is not available on "content >> Add Content".

Checked most parameters on creating the content type. No success.

Go to Structure >> Menus >> Navigation >> list links

(/admin/structure/menu/manage/navigation)

Make sure that the content type link is enabled.


How to resolve the error encountered while trying to import a rule using the Rules module? I have created a rule by using php code,i want to import it.When i click on import button it is showing that import block border as red(shown in the fig..)

Image

Code

And my code is shown in below,

{ "rules_send_warning_email" : {
    "LABEL" : "Send Warning Email",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "text_matches" : { "text" : [ "site:current-user:field-warnings" ], "match" : "New litter" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:mail]",
          "subject" : "New litter was born",
          "message" : "[site:current-user] selected new litter",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Your rule is looking for a field on the user entity type called "field_warnings". That field doesn't exist, or can't be found for whatever reason, so the import will fail.

You need to either add the field, or find out why Drupal can't find it, to continue with the import.


How to move a theme to a new location? I have a site (Drupal 8.4.2) that has Bootstrap and a subtheme located in:

/sites/themes/

With the upgrade from 8.3 to 8.4, I have started using Composer, and subsequently used Composer to upgrade Bootstrap. This added it to my composer.json (I'd previously installed Boostrap using drush), but also put the updated version of Bootstrap here (without touching my existing Bootstrap folder):

/sites/themes/contrib/

I removed my existing Bootstrap folder and cleared the cache. However, I can no longer manage the Boostrap theme or my subtheme - I get a 500 error like this:

  PHP Fatal error:  require(): Failed opening required '/var/www/html/drupal/mysite/themes/bootstrap/src/Bootstrap.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/drupal/mysite/vendor/symfony/class-loader/ApcClassLoader.php on line 110

The issue, clearly, is that it's looking for Bootstrap in the old location. The question is - what do I need to do to ensure my site finds Bootstrap in the correct folder? Moving the updated version of Bootstrap from contrib/ to where the original version was located fixes the problem for now, but I'd like to fix it permanently.

I assume there is a config value somewhere that isn't being touched by clearing the cache.

Put your old theme back into the old location.
Enable and set Bartik theme as default theme.
Uninstall the old theme.
Move your old theme to the new location.
Enable the old theme and set as default again.
Uninstall Bartik.

Voilà


How to securely access the data from another Drupal instance? I have a site setup which feels fairly unconventional so please bare with me while I try to explain.

I have 2 Drupal sites based on different servers.

The main site (site A) contains the front-end site and holds user data. The second site (site B) is our internal system and has 2 databases. This is a standard Drupal db and a db that contains other customer data (e.g. sales information, downloads and product info etc).

When a user logs in to their account on the main site, I need to be able to access information on the second database and display this to the user.

I know I can do this without using Drupal with a mysqli statement. However, I need to be able to access this information securely via SSL.

I have very little knowledge of encryption so my initial thought was that if both sites had SSL, the information received would be sent encrypted when using mysqli. However, I think I am very wrong.

My next thought would be to request the information via the second Drupal site perhaps via an API of some sort. However I'm not sure this would offer any more security or if I have missed the point entirely.

Would anyone be able to advise me on the best way access this information please?

The easiest way to do this would be to set up a new MySQL user on Server B that had something like: GRANT SELECT ON serverBdata TO 'serverAuser'@'serverA-IP';

Then you can write a module on server A that connects and retrieves that data.

If that's not going to work, you can look at setting up a menu hook on Server B that delivers the data in a sensible way, such as JSON, over HTTPS.

if you wanted to get really fancy, you could also encrypt the JSON.


View a permanent warning How to display a warning message on all pages of the site, using rules.
When I created a rule with the action "Display a message on the site," it appears that a single time.
I hope it will display permanence and on all my pages.

It depends on what event you have subscribe your rule for.

If you choose event as 'Drupal is initialised' and then choose action as 'Show message on site',the message will be showed on every page request, only thing you would like to make sure is disabled the repeat behavior of message, so that message does not stack up on every page request.

Here goes the export of such rule, that might give you a good starting point.

{ "rules_system_wide_message" : {
    "LABEL" : "System Wide Message",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "Site wide message", "repeat" : "0" } }
    ]
  }
}


How to translate strings available in JS library? I'm showing some images on my site where those are displayed using jquery.magnific-popup.min.js library. I'm not able to translate a string in that library. i.e.

  "%curr% of %total%"

It is not searchable even in the translate interface. How can I translate it?

See the plugin's translation documentation for a list of strings and their option names.
Pass these strings through Drupal.t() when attaching your popup.


Cannot replace html.tpl.php with new template in a single module I am creating a module to handle the reformatting of pages for printing in D7.

The structure of the URL is: /print/{nid}

I need to use a separate template than html.tpl.php as I have to get rid of our global header/footer but I still need our javascript and css to load.

I'm at a loss for how to correctly implement this.

I have created a menu_hook, otherwise I get a 404 page

I have tried using the $vars['theme_hook_suggestions'][] = 'html__print'; but I get no output

<?php
// print.module
function print_menu()
{
    $items  = array();

    $items['print/%node']   = array(
        'title' => '',
        'access arguments' => array('access content'),
        'page arguments' => array(1),
        'page callback' => 'print_process_print',
    );

    return $items;
}

function print_process_print(&$vars)
{
    error_log(__FUNCTION__.' called');
    error_log('node: '.var_export($vars, true));

    $vars['theme_hook_suggestions'][]  = 'html__print';

}

My template file is: sites/all/themes/zen/templates/html--print.tpl.php

Any help is greatly appreciated.

To create your own template override in a module is not the same as doing it in a theme. Look at Overriding a template file (.tpl.php) from a module.

Put this code in your module, and put the template file in a sub-directory 'templates'. Clear the cache.

function MODULE_preprocess_html(&$vars){
  $vars['theme_hook_suggestions'][]  = 'html__print';
}

function MODULE_theme_registry_alter(&$theme_registry) {
  $path = drupal_get_path('module', 'MODULE') . '/templates';
  $templates = drupal_find_theme_templates($theme_registry, '.tpl.php', $path);
  foreach($templates as &$template) {
    $template['type'] = 'module';
    $template['theme path'] = path_to_theme();
  }
  $theme_registry += $templates;
}


Filter with additional form element I have a custom views filter extending Drupal\user\Plugin\views\filter\Name that I am trying to add an additional form element. The existing filter is an autocomplete field that I need to add a checkbox element. I've tried updating ::valueForm.
// Working code that creates the autocomplete field.

$existingElement = $form['value'];

$form['value'] = [
  '#tree' => TRUE,
  'existing_element' => $existingElement,
  'new_element' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox'),
    '#default_value' => FALSE,
  ],
];

It throws this error.

Error: Cannot create references to/from string offsets in Drupal\Component\Utility\NestedArray::setValue() (line 155 of core/lib/Drupal/Component/Utility/NestedArray.php).

It seems to be related to the form state, but I have troubles in figuring out exactly what is missing.

You probably need to override the valueValidate method to tell it about the new structure:
protected function valueValidate($form, FormStateInterface $form_state) {
  $uids = [];
  if ($values = $form_state->getValue(['options', 'value', 'existing_element'])) {
    foreach ($values as $value) {
      $uids[] = $value['target_id'];
    }
    sort($uids);
  }

  $checkbox_value = $form_state->getValue(['options', 'value', 'new_element']);
  // Do something with $checkbox_value here as you're going to lose it

  $form_state->setValue(['options', 'value'], $uids);
}


How to retrieve "profile_" only filelds? Now I load user profile fields of a $uid  by:

$thisuser = user_load(array('uid' => $uid));
profile_load_profile($thisuser);
drupal_json($thisuser);

Is there a quick way to filter only fields with leading profile_ in $thisuser and so drupal_json displays only profile values?

The condition should be preg_match("/^profile_/", $profile). Have look at preg_match.


Creating A Submenu In Drupal Hello I Am New to drupal and i want to create a submenu bar under Menu Navigation So Can ANYONE Suggest And Idea Or Something To Create A Submenu In Other Page Like Shown On Image

Submenu can be created by selecting Parent link for that menu and ordering can be done by weights.
Try reading this in detail at drupal.org


"AND" condition in multiple arguments I am using Views 3 on Drupal 7.

I have a node with multiple terms, and I want to get nodes with all own tids at once.

I configure the contextual filter using the following values:

Specify validation criteria:

taxonomy term
my vocabulary
Term IDs separated by , or +

Checkbox "Allow multiple values" is on.

I try to pass '1,2' as argument to the view, and I get:

  node 1 (tid 1)
  node 1 (tid 1, 2)
  node 2 (tid 2)
  node 3 (tid 2)

By the way, the '1+2' argument gives me the same thing, and it's all right.

Why can't I get a result like the following?

  node 1 (tid 1, 2)

Do you have any suggestions?

The problem is the way this is stored (1 to many relationship). There is no simple way of asking for nodes with terms 1 and 2.

To query for nodes they way you describe you would have to select nodes that has tid 1 and the nid is in a list of nodes that has tid 2. This is possible to do, but not something views support AFAIK.

To get this list, it would be easier to create the query yourself, or resort to hook_query_views_alter, which easily gives problems when maintaining.


Why are the terms filled when they are actually empty? Below is the JSON output of a product I am having the issue with:

  {
     "StkGrupKodu1" : "10090",
     "StokAdi" : "7 Parça Kombine Anahtar Takımı",
     "StkGrupKodu2" : "",
     "SiparisVerilebilir" : true,
     "StokMiktari" : 0,
     "StkGrupKodu4" : "",
     "StokTipiAdi" : "Ticari Mallar",
     "KDVOrani" : 18,
     "StokTipi" : "00000",
     "DovizCinsi" : "EUR",
     "Fiyat" : "34.00000",
     "StkGrupKodu3" : "",
     "StkGrupKodu5" : "",
     "PasifStok" : false,
     "EskiBilgileri" : {
        "EskiStokKodu" : "",
        "DegistirmeTarihi" : "1920-04-23T00:00:00"
     },
     "StokKodu" : "JBM50563"
  },

In this e-commerce system, I am consuming a web service and creating corresponding products. With a few products such as the above and a few others, I am having this dreadful issue. As you can see, StkGrupKodu2 and StkGrupKodu3 are empty but when I go to the edit page of the product, it's not empty. You can see from the screenshot below:

This is the code I am using to associate terms with products

foreach ($excel_products as $e) {
    $req = \Drupal::httpClient()->get("http://mitapp.mitacan.com/b2b/api/vStkLib/GetStkKodlist?UserCode=B2BUSER&StokKodu=".$e->stokkodu);
    $res = $req->getBody();
    $res = json_decode($res);
    $data = $res->Data[0];
    $sid = \Drupal::database()->select("commerce_store_field_data", "csfd")->fields("csfd", ["store_id"])->condition("default_currency", ($data->DovizCinsi == "TRL")?"TRY":$data->DovizCinsi)->execute()->fetchCol();
    $product = Product::create(["type" => "default"]);
    <snip>
    if (!empty($data->StkGrupKodu1)) {
        $tid_1 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu1)->execute()->fetchCol();
        $tid_1 = (!empty($tid_1[0]))?$tid_1[0]:"";
    }
    if (!empty($data->StkGrupKodu2)) {
        $tid_2 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu2)->execute()->fetchCol();
        $tid_2 = (!empty($tid_2[0]))?$tid_2[0]:"";
    }
    if (!empty($data->StkGrupKodu3)) {
        $tid_3 = \Drupal::database()->select("taxonomy_term__field_stok_grup_kodu", "ttfsgk")->fields("ttfsgk", ["entity_id"])->condition("field_stok_grup_kodu_value", $data->StkGrupKodu3)->execute()->fetchCol();
        $tid_3 = (!empty($tid_3[0]))?$tid_3[0]:"";
    }
    $tids = [$tid_1, $tid_2, $tid_3];
    $tids = array_filter($tids);
    <snip>
    foreach ($tids as $tid) {
        $product->field_stok_grup_adi[] = [
            "target_id" => $tid,
        ];
    }
  <snip>
}

What am I doing wrong or missing?

Looks to be a PHP issue and not drupal. You're not clearing your $tid_1,$tid_2,$tid_3 values within your for loop

So when $data->StkGrupKodu1 isn't set for example the value of $tid_1 is still that of the last time $data->StkGrupKodu1 did exist.

You could declare your $tid_1,$tid_2,$tid_3 variables at the top of your foreach loop so they get set similar to what you're doing if the database results null


How do you implement text color on taxonomy terms I want to implement different font colors on my taxonomy terms. I have installed and configured my color module version 7.x-1.0-rc1 but still I can't find any result.

Here are steps you need:

Install jQuery Colorpicker module.
In the vocabulary for terms for which you want to add colours, add a jquery color picker field.
So when you create each term, you also select a colour for it while creating. in this way each taxonomy term will have a colour.
now in the taxonomy term preprocess template, write something like this to grab the color and pass it as variable.

function themename_preprocess_taxonomy_term(&$vars) {
  $colour_code = $vars['taxonomy_term']->field_yourcolorfieldname['und'][0]['value'];
  $vars['colour_code'] = $colour_code;
}

Then copy the taxonomy-term.tpl.php to your theme folder, and you will be having $colour_code variable giving you the colour code of the term. you it to provide an inline css.

Remember, if overriding taxonomy term template is not what you need, or you want to have it elsewhere, whenever you get $term object, you can get the colour code through $term->field_yourcolourfieldname['und'][0]['value'].


links__system doesn't use URL aliases? I'm trying to use the links__system preprocess function to output a menu as a select element, unfortunately though $link['href'] appears to output the URL in a format like:

node/2

Even though the URL alias is set to something like:

nice-url

The code I'm using in my template.php file is as follows:

function THEME_links__system_MENU_NAME($variables) {
  $html = '<select name="" id="dropdown-menu">';
  $html .= '<option class="" value="home">Select Item</option>';
  foreach ($variables['links'] as $link) {
    $html .= '<option class="" value="' .$link['href'].'">'. $link['title'] .'</option>';
  }
  $html .= '</select>';

  return $html;
}

I've had a look at the $variables variable passed to this function, just to make sure I'm not referencing the wrong thing - but it doesn't appear to contain any other items in the array that contain the correct URL alias.

When using the default menu code output by Drupal it picks up the URL aliases and uses them.

What am I doing wrong here?

I managed to get around this by using the drupal_get_path_alias function in the end, so my resulting code was:

function THEME_links__system_MENU_NAME($variables) {
  $html = '<select name="" id="dropdown-menu">';
  $html .= '<option class="" value="home">Select Item</option>';
  foreach ($variables['links'] as $link) {
    $html .= '<option class="" value="'. drupal_get_path_alias($link['href']) .'">'. $link['title'] .'</option>';
  }
  $html .= '</select>';

  return $html;
}

Dissapointed I didn't think to search for such a function in the first place!


How do I rename a field? With Drupal 7 we had the Field Rename module, but this has not yet been ported to Drupal.

So what SQL magic is needed to rename a field in Drupal 8?

I've had the misfortune to need to do this before :P , and my advice would be as follows:

Forget about renaming the existing field; the machine name is scattered across several different hard-to-edit places, and you'll probably miss some and get weird errors. For example, if you just rename the tables and the configuration, the field API will throw a fit when it tries to delete the old tables and finds they're already gone. The schema information is kept in the keyvalue store, and cannot be rebuilt from scratch, so if you make manual changes it's easy to end up in a broken state.

Instead, recreate the field with the correct machine name, then copy over the data with SQL, and finally delete the old field.

INSERT INTO node__field_new SELECT * FROM node__field_old;
INSERT INTO node_revision__field_new SELECT * FROM node_revision__field_old;


Google map in jQuery UI tabs / Drupal behaviors.js As you can see here the google map in the first jQuery ui tab loads correctly but the same map in second / third etc tabs does not load properly or loads off centre.

As mentioned here the problem is that "Any component that requires some dimensional computation for its initialization won't work in a hidden tab, because the tab panel itself is hidden via display: none so that any elements inside won't report their actual width and height (0 in most browsers)."

I have read for example here that the problem is that the map loads after the jQuery UI tabs and so I need a jQuery snippet in my (Drupal 7) theme's behaviors.js to to make the map load before the jQuery UI tabs.

(Please note that the alternative solution of applying CSS to .ui-tabs .ui-tabs-hide  will not work for me because it causes problems elsewhere.)

Can anyone please tell me the code I need for my-theme.behaviors.js ?

my template.php =

<?php
function whitecross_160614_preprocess_html(&$variables){
// some comment here
    drupal_add_library('system', 'ui.tabs');
    drupal_add_js('jQuery(document).ready(function(){
                jQuery("#tabs-x, #tabs-y").tabs({event: "click"});
                jQuery("#tabs-x, #tabs-y").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
                jQuery("#tabs-x li, #tabs-y li").removeClass("ui-corner-top").addClass("ui-corner-left");
            });',
        'inline');
}

HTML =

Map 1

Map 2

Map 3

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2... width="800" height="600" frameborder="0" style="border:0">

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2... width="800" height="600" frameborder="0" style="border:0">

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d2483.645966939501!2... width="800" height="600" frameborder="0" style="border:0">

Further to the comments, here is a jsfiddle of what I was talking about. This is a quick example, but should be easily adapted to your own code. I altered the dimensions on the maps to show the change

CSS:

#toolbar
{
    width:100%;
    height:20px;
    background:#000;
}

#toolbar li
{
    display:inline-block;
    min-width:100px;
    background:#fff;
    color:#000;
    border:1px solid #ffff00;
    cursor:pointer;
}

#maps
{
    position:relative;
    width:800px;
    height:600px;
    overflow:hidden;
}

#maps #tabs-1,
#maps #tabs-2,
#maps #tabs-3
{
    position:absolute;
    top:0;
    left:0;
    width:800px;
    height:600px;
}

#maps #tabs-2,
#maps #tabs-3
{
    opacity:0;
}

HTML:

Map 1

Map 2

Map 3

JS:

jQuery('#toolbar_tabs1').click(function(){
    jQuery('#tabs-1').animate({'opacity':1}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs2').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':1}, 200);
    jQuery('#tabs-3').animate({'opacity':0}, 200);
});

jQuery('#toolbar_tabs3').click(function(){
    jQuery('#tabs-1').animate({'opacity':0}, 200);
    jQuery('#tabs-2').animate({'opacity':0}, 200);
    jQuery('#tabs-3').animate({'opacity':1}, 200);
});


Not saving data after upgrading from 7.26 to 7.35 I recently update my Drupal site and is working fine on my local machine ie: localhost.
After uploading the site to the hosting it is not saving the form/data.
I'm not even able login to system on first attempt, it is not showing any error as well.

1 - I make sure that .htaccess files is moved to the server.

2 - I clear Drupal and browser cache several times.

3 - No javascript/jquery error on console.

4 - Check on different browsers.

I'm lost what else can be doing problem, Please guide me to the right path.

PHP info = http://worldstogethertravel.com/info.php

TIA :)

This worked for me:

Apply the patch from here:
https://www.drupal.org/node/1313912

cd sites/all/modules/contrib/taxonomy_access

wget https://www.drupal.org/files/1313912-5.patch

cat 1313912-5.patch | patch -p1
go here and rebuild permissions.
/admin/reports/status/rebuild
Clear the cache


Set Update Manager to install to sites/all/modules/contrib? I am able to use Update Manager to install new modules, instead of having to manually upload them. I previously put everything in sites/all/modules, but now have reorganized my modules into sites/all/modules/contrib and sites/all/modules/custom (for the modules I write or modify).

However, Update Manager is still installing new modules in sites/all/modules. Is it possible to tell Update Manager to install new modules in sites/all/modules/contrib instead? I looked for a setting somewhere, but can't find one (D7).

To circumvent these (and other) issues, I typically use the Drush command line utility to install and update new modules instead of the Update Manager.

For instance:

drush dl views --destination='sites/all/modules/contrib' # Download views to this path
drush dl uuid --destination='sites/all/modules/contrib' --select # Select other releases
drush en views views_ui  # Enable Views and Views UI
drush up ctools          # Update CTools

Drush also provides a number of other useful commands, and integrates very nicely with other modules. I highly recommend looking into using it if you haven't already!


Change Menu Link Title Dynamically Requirements:

Change the Navigation block link "Add Listing" based on role.
This is the built in Navigation block and I've renamed Add Content to Add Listing

I've tried all the solutions here.  Though I admit I am probably doing it wrong.

Change menu link title dynamically?
How do I modify a menu link title dynamically?
How do I dynamically change the title of a menu link?

I've created a module with the following code:

function mymodule_menu_alter(&$items) {
  $item['options']['alter'] = TRUE;
  $items['node/add']['access callback'] = '_accesscheck';
  $items['node/add']['title callback'] = 'mymodule_title_callback';
    var_dump($items);
}

function mymodule_title_callback($arg1) {
    $title = 'New Title';
    return $title;
}

function _accesscheck(){
  global $user;
  return $user->uid;
}

This is a var_dump snippet of what I'm after:

["node/add"]=>
  array(5) {
    ["title"]=>
    string(11) "Add content"
    ["page callback"]=>
    string(13) "node_add_page"
    ["access callback"]=>
    string(16) "_node_add_access"
    ["file"]=>
    string(14) "node.pages.inc"
    ["module"]=>
    string(4) "node"
  }

Before I attempt to include roles I'm just trying to get the link to change.

Just tried your code (trimmed down) and it worked without any problems. I simply overwrote the "title callback", like you did. I tried it with admin and anonymous account, see the screenshots for the end result below:

I also added, as an extra precaution, a module_implements_alter implementation. With that hook, you can push your menu_alter implementation to the end of the hook_menu_alter list. That way you can make sure it gets executed after every other menu_alter, in case there was some competing implementation there.

<?php

/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  $items['node/add']['title callback'] = 'mymodule_title_callback';
}

function mymodule_title_callback($arg1) {
  global $user;
  $title = 'New Title';
  if( $user->uid == 0 ) {
    $title = 'New Title for anonymous';
  }
  return $title;
}

/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook != 'menu_alter') {
    return;
  }

  $module = 'mymodule';
  $group = array($module => $implementations[$module]);
  unset($implementations[$module]);
  $implementations = $implementations + $group;
}

Hope you can get this to work!


Show title of referenced node in node template I'm working on a node template for my content types and use Entity reference to reference my content with each other. THe machine name of my entity reference field is og_group_ref. In my node template I used print_r(get_defined_vars()) to show all existing varialbes to select variables I need. When I look for og_group_ref I only get the target_id of that reference:

[og_group_ref] => Array
            (
                [0] => Array
                    (
                        [target_id] => 65
                    )
            )

So, my question is how do I get the title of that referenced node?

For example, if I remember node structure right:

Load node by id into $node
Put title to $node_title

$node = node_load(og_group_ref[0][target_id]);

$node_title = $node->title;

All you need is to get og_group_ref object/element


How to attach css classes to the  title attributes if node_is_page() dynamically? To preprocess the node title field is obviously not the easiest. It has its place in the node.tpl.php and in the page.tpl.php by default and it has its own status in Drupal core, which makes it not fieldable as simply as other fields and entities in a given content type bundle.

That's why there are many discussions going on at drupal.org and some little helper modules are also around already, to make the title field more flexible in different scenarios like field translation, label design, field order and much more. So if this is your problem you will easely find a little module helping you.

But what if you don't want to touch the behaviour of the title field as designed in core but only want to preprocess the title to change the markup dynamically? Suddently google keeps silent. Unlike others I agree with some core contributors who explain wisely why the title field has its reasonable difficulties and why the decision to make it simply a "field like others" is not THAT easy to make. So for some reasion I need a solution in template.php

This is how the page.tpl.php looks like in my case:

// page.tpl.php

<?php print render($title_prefix); ?>
    <?php if ($title): ?>
        <?php if ($page): ?>
            <!-- This is where we want to get in with template.php -->
            <h1 <?php print $title_attributes; ?>>
                <?php print $title; ?>
            </h1>
        <?php endif; ?>
    <?php endif; ?>
<?php print render($title_suffix); ?>

And this the place where we obvisously should try to make it happen:

// template.php

function YOURTHEME_process_page(&$variables) {
    if ($variables['view_mode'] == 'full' &&
        node_is_page($variables['node'])) {
            // do something with $variables['title']['attributes'][];
    }
}

But to be honest, I am a little bit lost here, since I only want to change the rendering of <h1> to <h1 class="my_css_class">. Does anybody has an idea of how to achieve this?

The attributes class seems not to exist this way, because I get an Unknown index warning and the class gets not attached. Or maybe I have to point to $title another way? Maybe something like $node->title ? I know how to wrap the title with a new container, or how to change the suffix/prefix. But here would really appreciate your thoughts. Thank you very much ...

Okay, as commented under the question, I've tried out another idea: a little bit dirty since this is far away from the way it is supposed to be, but hiding '$title' in page.tpl.php and removing the IF NOT PAGE condition from the standart node.tpl.php (like in Bartik) makes it possible to access the title-attributes array, since node.tpl.php seems to know title-attributes, but page.tpl.php not...

But in this case I have to reimplement the programmatically "node is page OR node list switch" toggling of h1 and h2 again, since if-page $title in page.tpl.php did this before:

After removing the complete if-title-title part (in Bartik it looks like this, near the $content) from page.tpl.php,

<?php print render($title_prefix); ?>
  <?php if ($title): ?>

      <?php print $title; ?>

  <?php endif; ?>
<?php print render($title_suffix); ?>

... I have added (exchanged) this in the node.tpl.php:

//node.tpl.php

// usually we have something like the following here
/*
<?php if (!$page): ?>
   <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
*/

// but we exchange it with this ...

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

  <?php if ($page): ?>
    <h1<?php print $title_attributes; ?>>
       <a href="<?php print $node_url; ?>">
          <?php print $title; ?>

  <?php endif; ?>

  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>">
         <?php print $title; ?>

  <?php endif; ?>

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

Now I do have my title inside of my wanted scope, where I can theme it programmatically inside the main content container. Thanks to Clive for his support on my question, and special thanks to Digidog from drupal.org, who gave me the final hint per mail.


can't query numeric field I can't seem to query on a field of type "numeric".

From hook_schema:

'id' => array(
  'description' => "ID",
  'type' => 'numeric',
  'unsigned' => TRUE,
  'precision' => 20,
  'scale' => 0,
  'not null' => TRUE,
  'default' => 0,
),

if I do something simple like the following code, I don't get anything.

$query = db_select('tablename', 't')
  ->fields('t', array('nid'))
  ->condition('id', $id, '=');

However, if I execute the following query on PHPMyAdmin, I get a row.

SELECT * FROM `tablename` WHERE id = 195755377227337728;

I did try to type cast the id with (int) $id, but that didn't work either.

Do you have any thought?

Two things that might be causing the problem:

You need to execute the query: $result = $query->execute();
The id you gave is HUGE, and I don't know if it would ever work. Drupal comes with the nid column set to a length of 10.  Even if you've accounted for that, the max INT column size in MySQL is 4294967295 and your ID is 195755377227337728.  Theoretically you could use BIG INT instead of INT.  See: MySQL column type sizes

Also, try this Static Query instead of db_select():

$result = db_query("SELECT nid FROM {table} WHERE nid = :nid", array(':nid' => $nid,));


How to make changes to the database schema? I am trying to follow edits made in a php file to patch a module  and the instructions just say "In your database schema add this", which I could do if I knew where to find the file. When I look up drupal database schema it shows a map which doesn't help me to find the file. What do they mean exactly by in your database schema and how can I access this file in terminal? Is it by editing a table in the database?

I can find the other file alright to edit in /includes/database/mysql/schema.inc file but just not the specific module one.

The instructions for this vchess module patch are here

Your database schema literally just means the structure of your database. It sounds like you're being instructed to manually make a change to this e.g. to add a column, which you could do in something like PHPmyadmin.

Normally a module's database schema is managed in its .install file. The initial schema is defined in hook_schema() and any changes are automated with hook_update_N(), but it sounds like you're being asked to make manual changes instead. Be careful!


How to write a db_select query? How can I  write a query to do the following:

select cid, thread and paragraph_id(I have added this field to comment table) from comment table, and then sort them first based on the paragraph_id and  then based on thread. So for the comments that have the same paragraph_id they will be sorted by thread number.

You probably want to look on the db_select documentation. I strongly reccomend on this comment.


Why file name and uri of the file in database are different? I am uploading the files to the folder by using file_save_upload and file_move to achieve this. Its working fine but a problem arises while saving in database.  I have used FILE_EXISTS_RENAME argument, so in file_managed table filename column and uri column file name is not same. In filename column its not appending the integer value, but in uri column its appending the integer value since the file is already exist. Below is my code:

  for ($i = 0; $i < $num_files; $i++) {
      $file = file_save_upload($i, $validators, FILE_EXISTS_RENAME);
      if ($file) {
        $file->status = FILE_STATUS_PERMANENT;
        if ($file = file_move($file, 'public://feed-files/' . $foldername, FILE_EXISTS_RENAME)) {
          $form_state['values']['file'][$i] = $file;
        }
        else {
          form_set_error('file', t('Failed to write the uploaded file to the selected folder.'));
          return FALSE;
        }
      }
      else {
        form_set_error('file', t('No file was uploaded.'));
        return FALSE;
      }
    }

below is the database values:

So how can achieve that filename and uri  column file name should be same. Any suggestions will be appreciated.

The reason for difference is that multiple files with same name can be uploaded in Drupal, so when you upload a file, it adds a counter at the end of filename so that if a file with same name is uploaded again, then it doesn't replace another one.

Also the filename column contains the exact name of the uploaded file as it is used while downloading the file (the file will be downloaded with this name).


How to render media shortcodes e.g [[fid:1234]] I've written a custom database query to pull out taxonomy data in a specific way, the problem is embedded media shortcodes are outputting the shortcode strings as they stand in the database, rather than the content they represent.

e.g:  [["fid:"1234"]] instead of pdf.

The taxonomy body field can contain:

Embedded nodes ([[nid:1]])
links to other content (node/nid)
embedded media etc: pdfs ([["fid":"6247" "other_props":....]])

I've written regex to parse out the first 2 bullet points, and call _node_embed_replacements() & drupal_get_path_alias() respectively to insert the correct content for them, but i'm having a hard time working out where media module renders embedded shortcodes such as [["fid":"6247"]].

I found the following load_file() and field_view_file() functions which worked a treat for me. I bundled them with a regex search and replace.

Rough abstract taken from my code not tested but the theory remains the same.

preg_match_all('/\[\[{"fid": ?"([0-9]+)".*?\]\]/', $tax_body, $matches);
foreach ($matches[1] as $index = > $fid) {
  $file = file_load($fid); //load the file
  $content = file_view_file($file); // turn it into a render arrray
  $replacement= drupal_render($content); // render it into html string
  str_replace($matches[0][$index], $replacement, $tax_body);
}

Perform a regex for [[{"fid":(???) ..] where the ??? is the file id that is captured in the $matches[1].

Loop through all found instances, lookup the file markup, and then do a search and replace on the entire string replacing the full shortcodes (matches[0]) with the replacement markup.


How do you add a region to a panel Novice question on Panels - I've inherited a D7 site with Panels 7.x-3.9.

I'm using a system page: node_view, with a variant for the content type I'm working on.

The layout has a number of regions - and just to be clear, by regions, I mean the $plugin['regions'] array in the template's .inc file.

What I can't figure out is how to add new regions.

(I want to add group some fields together so I can insert them using $content['foo'] in the template.)

Modifying the existing region names updates the descriptions used  /admin/structure/pages/nojs/operation/node_view/handlers/node_view__panel_context_[UUID]/content

But any extra regions I add don't appear (having done drush cc all) and they also don't appear when creating a brand new variant using the same template.

Am I missing something in the UI (I'm logged in as user 1)?

(Thanks)

I discovered the region is only visible in the variant drag/drop editor after it's been referenced in the template (because in fact you're looking at a site preview, not just an admin page - but that wasn't terribly obvious as none of the rest of theme was visible):

<?php print $content['foo'] ?>


Is there a dummy field to provide additional instructions to the users on node add form? I'm building quite complex node form and I need to provide users with additional instructions how to fill the form. Are there any modules that would allow me to add sort of dummy fields with some HTML that would be displayed when user edits or creates new node? I don't want to save any data for these fields. I would like to be able to provide some HTML that will be displayed among other node form elements. Even plain text would do.

Try the Markup module:

  This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.


Adding a counter within Rules I have created an endless loop within Rules that will evaluate nodes after they are created and reschedule itself as shown here:

I would like the loop to close after three emails have been sent.  A counter could be added to the action set under "Send Email" then the conditions could include a Data Comparison to see if the counter is less than 3.

I have tried creating fields within the content type that would have the Rule Component increase the counter field by one every time the email section was executed then have a data comparison between the counter field and a Email Max field that had a default value of 3.  I wasn't able to get this to work because the counter would not be increased.

Could this be done with an "Execute Custom PHP Code" action?

Going off memory here:

For both if and else, Add Action >> Set a Data Value >> node:field-email-max >> OFFSET: +1  (To get the offset, you will have to click the switch data selection button)

For both if and else >> Add Conditional >> Data Comparison >> node:field-email-max >> Less than 3


How to show "Log in or register to post comments" message when no comments on content? The "Log in or register to post comments" message does not display when there are no comments on a piece of content.

However, it does show when there is at least one comment.

Looking in the comment module code, the "Log in or register to post comments" message is in the code that only runs when there are already one or more comments!

How dumb is that?! Is there a module or an existing approach to making this display when there are no comments?

I can write a hook in my own module to override this but it might be re-inventing the wheel if it's already been done.

this is my temp solution.. i copy the ds-1col template to my ds-1col--node.tpl.php and add this code at bottom.

<?php global $user;
if (!$user->uid) {
print render($content['links']['comment']['#links']['comment_forbidden']['title']);
} ?>


Effecient modules which will give me users location and country information I am using drupal 7. I searched and found lot many modules to give users location and country information. So just wanted to know which is the efficient module which i should use.

Take a look at Smart IP.

  Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($_SESSION) with array key 'smart_ip' and Drupal $user->data object with array key 'geoip_location' of the user but optionally it can be disabled (by role) at Smart IP admin page.


How to preprocess view accordion I'm using D7 and module Views Accordion (V 7.x-1.1) for my view. I've created my custom template (e.g views-view-accordion--[name of my view].tpl.php) for customize my view. However, when I want to add some variables in preprocess function, I created the function mytheme_preprocess_views_view__[name of my view](&$vars), I cannot get into this function.

Am I doing something wrong? Thanks in advance.

You want to use template_preprocess_views_view (see views theme functions)

function MYTHEME_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  if ($view->name == 'my_view_name') {
    // add your variables here
    $variables['YOUR_VARIABLE'] = 'value';
  }
}

$YOUR_VARIABLE should be available in your template file.


Overriding default hashing mechanism: cannot redeclare user_hash_password() I have a project that requires a change in the default password encryption mechanism.

The documentation of password.inc states that this can be overridden using the password_inc variable. I followed the instructions as stated in the documentation but when trying to change a password on the website following error is generated:

  Cannot redeclare user_hash_password() (previously declared in
  /.../drupal7/includes/password.inc:207) in
  /.../drupal7/sites/foo/modules/custom/foo_custom/includes/foo_custom.password.inc
  ...

I have searched the code for a hardcoded include on includes/password.inc but can't find anything.

Any ideas?

Everything in core uses

require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

so I would guess at the cause being a contrib module.

Also just check that the password_inc variable has been updated correctly and not deleted somehow.


Private messages problem In Drupal 6.22, after installing 'User Relationships', APK , Content Profile and some related social modules. Then upgrading the server (Ubuntu), ans saw that private messages stopped being received by the users.

I have disabled UR, APK et al. and updated the database, but it had not fixed the problem. I even dropped the whole database and used a backup from a time prior to adding social modules. No curing effect.

The server still sends out emails and I am pretty sure that privatemsg permissions are set correctly, so that users should be able to send/receive privatemsges.

This might be clue: The users can receive privatemsg from debug (privatemsg test module), but not from other users. Not sure what does this imply.

I have really ran out of ideas and appreciate your hints.

So u upgraded Ubuntu, anything else? Php, apache etc? First verify using VMware it is in fact Ubuntu upgrade only that is causing the issue. You say you redeployed an older version of the db.  I would be tempted to do a full deploy just to try to reproduce including Drupal code. It's an odd problem, my instinct says possibly a difference in php version could potentially cause this.


Adding a new variable to account menu for twig rendering I am trying to add a variable to render in the menu-account.html.twig file.

Here is my preprocess function in my .theme file.

function HOOK_preprocess_menu__account(&$variables) {
    $variables['account_name'] = Drupal::currentUser()->getAccountName();
}

HOOK is replaced with my theme name

And in my twig file I have this snippet:

<div class="welcome-message">
    Welcome, {{ account_name }}!
</div>

So I can edit pre-existing variables but I cannot seem to add a new one.

I was reading that new variables cannot be added in a preprocess function and that the HOOK_theme_registry_alter should be used.

Here is what I attempted and by using xDebug I can tell that it is getting looked at when flushing caches.

function HOOK_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu']['variables']['account_name'] = [];
}

Does anyone know the steps to get a new variable to be rendered in the menu twig file. This my first time using the theme registry hook so I might be doing something wrong there as well.

Thanks,

EDIT: "menu--account.html.twig" was named correctly in my code but mistyped in my question. Thank you to GiorgosK for pointing this out.

In your THEMENAME.theme

function THEMENAME_preprocess_menu__account(&$variables) {
  $variables['account_name'] = Drupal::currentUser()->getAccountName();
}

And in your menu--account.html.twig

<div class="welcome-message">
  Welcome, {{ account_name }}!
</div>

Just tested and it works, so basically what you posted should work but probably you mistyped the twig file name which needs two dashes (--)


How to create a module with forms? I am little stuck with creating a module for drupal.

I would like to show users a link: "Create", then to take them to a page where will be forms.

Can someone post little piece of code so i could see how to implement other...

Thank you!!!

One of the best way to learn how to do develop various common tasks is with Examples module.

Check especially the form_example module which has all necessary instructions and code examples.


How handle large number of images in gallery node Drupal 7 I have some gallery nodes with a large number of images (100+), the upload with Plupload integration module works fine, but after save the node and edit it again the node edit form loads 20+ seconds! How can I reduce the loading time of the form? Somebody have any suggestion for this problem? Lazy Loading of Fields possible? Pagination? Some Module?

Thanks

I do not know the intended site behaviour, or interface, for your galleries.  However, I would restructure the site.  Have you looked at each gallery "entry" being a node with 1 picture field and 1 taxonomy term reference?  The terms would then be your "galleries", you could use views to build the pages any way you want, even lazy load.  You could add sorting, and since you would not have 100+ field entries on any one entity, loading the entity into a variable for the various page build tasks would be far faster.  Gallery nodes work fine if they have less than 30 entries, but it sounds like your data management could use some revision.


How do I get Drupal to 'discover' a new layout .tpl? I wanted to make a slight variation of a .tpl layout a plugin uses. To do that I simply when into the plugins file structure and duplicated one of its layout folders and renamed the files within (.css, .tpl and .inc). I then made the changes to the .tpl file.

In the .inc file I find:

$plugin = [
  'title' => t('Two Col 50/50'),
  'category' => t('Foundation'),
  'icon' => 'icon.png',
  'theme' => 'foundation_twocol_50_50',
  'admin css' => 'foundation-twocol-50-50.css',
  'regions' => [
    'left' => t('Left'),
    'right' => t('Right'),
  ],
];

All I did here was alter these names slightly to:

   $plugin = [
      'title' => t('Two Col 70/30'),
      'category' => t('Foundation'),
      'icon' => 'icon.png',
      'theme' => 'foundation_twocol_70_30',
      'admin css' => 'foundation-twocol-70-30.css',
      'regions' => [
        'left' => t('Left'),
        'right' => t('Right'),
      ],
    ];

I then refreshed my cache and theme registry, but the new 70/30 option does not appear when I go to swap layout for the mini-panel I'm working on.

Is there something I must do to 'tell' drupal this new layout exists?

I assume this is a Panels layout and Drupal won't discover it. You have to manually add it to the theme's .info file like this:

plugins[panels][layouts] = your_new_layout_name


How do I prevent the automatic removal of a database table when a module is uninstalled? In Drupal 7, a database table created through hook_schema() gets created on module installation, and gets deleted on uninstallation.

I would like to prevent the removal of a database table when the module defining it is uninstalled, because the data which I am storing is very important so I want to make sure that even if someone even uninstalls the module for certain purpose than also data retains. Backing up the table before is certainly one solution but I am looking for some better alternative.

Uninstall is there just to delete changes made to database. If you do not want that deletion to happen, do not uninstall. If you need only one table, back it up before uninstallation and restore it after. If you want to remove module from uninstall list, simply delete it's files.

If you need selected module to be always on, you can use hook_modules_disabled() in a helper module, to display message like "Disabling of this module is not permitted" and instantly re-enable it. If module is never disabled, there will be no option to uninstall it. Of course if someone with admin privileges will want to destroy your data, he will, so don't give those privileges to those who can't be trusted with them, but at least it should prevent accidental module removal by developer who is not bright enough to stop and think.

Last but not least, if module's data is of significant importance, you have daily or maybe even hourly backups anyway, so accidental deletion is not a problem at all. Backup and Migrate and Elysia Cron are great help with setting up backups like this, but you should also ask your sysadmin to provide automatic copy to another physical machine, if possible.


How to create sortable checkboxes using the form API? I'm using Drupal 7 and I need the ability for the user to choose from a list of options and put those options in order. I am using type checkbox and passing in an array of options to create the list.

I need to be able to check the options needed and sort them.

The form checkbox creation is fairly straightforward, but doesn't appear to have a weight option for the individual checkboxes or really any attributes except value.

Any help would be appreciated. Thank you.

$form[$key]['articleFields'] = array(
    '#title' => t('article Fields'),
    '#type' => 'checkboxes',
    '#description' => t('Choose the fields you want selected'),
    '#options' => $articleFields,
    '#default_value' =>$articleFields_checked,

);

I was able to get this working using a modified version of the code here http://dropbucket.org/node/204

The adjustments I made were to allow my table to be an element on a parent form and to repopulate the from my variables array...
//TODO bubble checked boxes to top

    $rows = array();
    $row_elements = array();
    $data=array();
    //$shared['articleFields'] values stored in variables table -- loaded in parent form
    //$key is name of my parent form this gets attached to

    $cc=-10; //default weights starting at -10
    //field machine names with titles
    $articleFields = array(
      'title'=>t('Headline'),
      'field_news_categories'=>t('News Categories'),
      'field_text_2'=>t('Subheading'),
      'field_photo_caption_1'=>t('Featured Photo'),
      'body'=>t('Copy'),
      'field_text_4'=>t('Featured Quote'),
      'field_keywords'=>t('Keywords'),
      'field_websites'=>t('Related Links'),
      'field_images'=>t('Additional Images'),
      'field_slideshow'=>t('Slideshow'),
      'field_video'=>t('Video'),
      'scheduler_settings'=>t('Scheduler'),
      'group_alternates'=>t('Alternates'),
      'field_text_1'=>t('Alternate Headline'),
      'field_text_3'=>t('Alternate Subheading'),
      'field_photo_caption_2'=>t('Alternate Photo'),
      'field_longtext_1'=>t('Alternate Copy'),
    );

    foreach ($articleFields as $k =>$v) {
        // Build the table rows.
        $dv="";
        $dv2="";

        //if no values are defined use default weights from -10 up
        if(isset($shared['articleFields']['elements'][$k]['weight'])){
            $dv=$shared['articleFields']['elements'][$k]['weight'];
        }
        else $dv=$cc++;

        //if no value is defined use 0 for enabled value (unchecked)
        if(isset($shared['articleFields']['elements'][$k]['enabled'])){
            $dv2=$shared['articleFields']['elements'][$k]['enabled'];
        }
        else $dv2=0;
        $rows[$k] = array(
            'data' => array(
                // Cell for the cross drag&drop element.
                array('class' => array('entry-cross')),
                // Weight item for the tabledrag.
                array('data' => array(
                        '#type' => 'weight',
                        '#title' => t('Weight'),
                        '#title_display' => 'invisible',
                        '#default_value' => $dv,
                        '#attributes' => array(
                            'class' => array('entry-order-weight'),
                        ),
                    )),
                // Enabled checkbox.
                array('data' => array(
                        '#type' => 'checkbox',
                        '#title' => t('Enable'),
                        '#title_display' => 'invisible',
                        '#default_value' => t($dv2),
                    )),

                // Name textfield.
                array('data' => array(
                        '#type' => 'textfield',
                        '#size' => 50,
                        '#disabled' => TRUE,
                        '#title' => t('Field'),
                        '#title_display' => 'invisible',
                        '#default_value' => t($v),

                    )),

            ),
            'class' => array('draggable'),
        );

        // Build rows of the form elements in the table.
        $row_elements[$k] = array(
            'weight' => &$rows[$k]['data'][1]['data'],
            'enabled' => &$rows[$k]['data'][2]['data'],
            'field' => &$rows[$k]['data'][3]['data'],
        );
    }
     //sort both the rows and the row elements on the weight value

        uasort($rows, function($a, $b) {
            return $a['data'][1]['data']['#default_value'] <=> $b['data'][1]['data']['#default_value'];
        });

        uasort($row_elements, function($a, $b) {
            return $a['weight']['#default_value'] <=> $b['weight']['#default_value'];
        });

    $id=str_replace("shared_", "", $key);
    $id="form-item-shared-".$id."-articleFields";

    // add this to parrent form
    $form[$key]['articleFields'] = array(
        '#prefix'=>'
',
        '#theme' => 'table',
        // The row form elements need to be processed and build,
        // therefore pass them as element children.
        'elements' => $row_elements,
        '#header' => array(
            // We need two empty columns for the weigth field and the cross.
            array('data' => NULL, 'colspan' => 2),
            t('Enabled'),
            t('Field'),
        ),
        '#rows' => $rows,
        '#empty' => t('There are no entries available.'),
        '#attributes' => array('id' => 'entry-order'),
        '#sufix'=>'
',
    );
    drupal_add_tabledrag('entry-order', 'order', 'sibling', 'entry-order-weight');


How to create notifications like Facebook about pending workflow approvals? Is it possible in Drupal 8 to setup notification bar as in Facebook?

Update:

I have different roles and I am using workbench for applying workflow. I have three transition attached with role like draft, approved, published. When user like reporter who have only draft transition going to save content at that time a user like editor who have right for transition like approve will get notify on screen when login.

Have a look at one of the answers to "Notification + Subscription: Can this combination recipe be used to create notification system similar to Facebook's?", which explains how the Menu Badges module can be used for this. The result of using it looks as in this example:

The current status of this module for D8 is like so:

  The 8.x-1.x-dev release includes all the functionality of the Drupal 7 version. However, it is not yet completely working with the new caching that Drupal 8 does. Badges are getting cached and don't change when they should. Once that is fixed, a stable release will be created.

To implement it for supporting what you decribed in your update, you only have to create an appropriate view (using views) with as results the updated content that the editor should be notified about.


How do I get entity_type and entity_id from any entity page? Some pages (paths) represent one entity. For example:

The pages at these paths represent one node entity, entity_id (nid) is XX:

/node/xx
/node/xx/delete
/node/xx/edit

The page at this path represents one search server entity (defined by search api module), entity_id (machine_name) is 'apache_solr':

/admin/config/search/search_api/server/apache_solr

How do you load in the basic data about this entity (id and type) when the hook or function you are in doesn't hand it to you?

The standard way to get the current entity is apparently to use menu_get_object($entity_type,$position_of_id_in_url). This, however, assumes that you are coding for just one entity type: you need to state the entity type programmatically, and, even worse, you the human being need to research and hard code in the url position of entity ids that this entity uses.

The closest I can find so far is getting the underlying system uri for the page (e.g. substr(request_uri(),strlen($base_path))), then writing a monsterous switch list based on something like this suggestion, guessing and then hard coding cases for every possible entity you think a site might ever have. But there must be something better than that, right?

While a general solution from core would be best, I'll also accept an answer that depends on common modules like ctools (page manager, contexts, etc), Entity API, Devel, etc.

My immediate need is for edit forms, within hook_field_widget_form(), for a widget that can (with appropriate config and modules) be attached to any fieldable entity type. So, while a general solution would be best, I would also accept a narrow answer that only works within this function or in forms (The id and data that is specific to entity type appears to be buried in $form, but keyed in an entity type specific way, so getting it out of $form seems like a chicken and egg problem).

------------ EDIT ------------------

Seems some people have difficulty understanding the simple general problem. Here's an alternate use case (another seperate but related problem I'm facing). Suppose you have a view that lists some entities. This view sits as a block/pane on pages that can represent one entity, such as a node page or a user profile (or both). You've got a hook set up that reads the views data and looks through the results (foreach $view->result as...). Let's say it's hook_views_pre_render, which means you just have the $view object. You want to do something (say, remove the row or change some field data) if the view results row has the same entity id and entity type as the page does. You've got the logic down to extract this data from the view results, so all you need is to look up the entity_type and entity_id of the page being generated, to make a comparison. That data is in Drupal somewhere. If it wasn't, Drupal couldn't have figured out that it needed to load this view. So how do you get it when it isn't passed to the hook or function you are in?

In Drupal Core, you cannot do this. The relevant issue to add such functionality is here.

What core itself does is always passing around two arguments:

function($entity, $entity_type)


Pass parameter to node twig template via url The url to display node 100 is <site>/node/100. I want to pass a parameter to this node via the url. For example: <site>/node/100/3.

Question:

What must I do to get Drupal 8 to see /node/100/3 as /node/100 with the parameter 3 instead of just the url /node/100/3 (which fails)?

Efforts:

I've read many posts, but didn't find any that seem to directly address this issue.
I realize this can probably be accomplished via /node/100?param=3. I want to avoid using a query parameter if possible, just for cleanness.
I realize this can probably be accomplished by displaying the node within a view and then using a contextual filter. I want to avoid using a view if possible, again just for cleanness.

try this in twig:

{% set url =  url('<current>')['#markup'] %}
{% set urllast =   url|split('/')|last %}
{{ urllast }}  // 3


Large file uploads stop immediately, 404 error I am having a weird problem with uploading large files in the Drupal admin's file field. I have the size limit set to 500 MB. I also have the php.ini settings for upload size, post size, and memory all set to 500 MB.

When I upload a smaller file like 50 MB everything works perfectly. If I upload a larger file such as 250 MB then the upload fails immediately and I get a 404 error in the Network tab of the Chrome inspector.

The 404 error is on this URL: http://example.com/file/ajax/field_video_file/und/0/form-tpohUDjq_v0b7OcNhtnQl2TaRc5UcFl9zwJQzI3mlwE

The server is running IIS 7.5.

Any ideas what could be causing this?

Thanks!

From: https://www.drupal.org/node/97193

  Drupal's limits on upload file size are determined by your server's
  PHP settings (as well as Drupal specified settings that can be set at
  Admin > Site Configuration > File Upload). The default values for PHP
  will restrict you to a maximum 2 MB upload file size.

  On the settings page for the upload module, Drupal calculates and
  displays the maximum file size that you can set based upon two PHP
  settings: 'post_max_size' and 'upload_max_filesize'. Since
  'post_max_size' is the limit for all the content of your post, many
  people choose 'post_max_size' to be a multiple of
  'upload_max_filesize' to allow multiple files to be uploaded, but this
  is not essential. The upload module limits the size of a single
  attachment to be less than either post_max_size, or
  upload_max_filesize, whichever is smaller. The default PHP values are
  2 MB for upload_max_filesize, and 8 MB for post_max_size.

  Depending on your host, changing these two PHP variables can be done
  in a number of places with the most likely being php.ini or .htaccess
  (depending on your hosting situation).

  For example, to increase the limit on uploaded files to 10 MB:

Add the below to the relevant php.ini file (recommended, if you have access). Note that for some hosts this is a system-wide setting.

  However, for hosts running PHP as a CGI script with suexec (for
  example) you may be able to put these directives in a php.ini file in
  your Drupal root directory.
          upload_max_filesize = 10M
          post_max_size = 10M
      Add the below to your .htaccess file in your Drupal root directory.
          php_value upload_max_filesize 10M
          php_value post_max_size 10M

  The PHP documentation states that the memory_limit setting also
  affects file uploading. Generally speaking, memory_limit should be
  larger than post_max_size. If this is an issue, see the page on how to
  Increase memory available to PHP (3 methods)

  Drupal also allows/enforces its own size limits, independently of what
  PHP allows. These are found in Drupal 6 at "Administer » Site
  configuration » File uploads" ( /admin/settings/uploads ). In Drupal 7
  size limit is controlled on per-field basis. The Drupal settings
  cannot be larger than those permitted by PHP, but may be smaller if
  you haven't updated them, so remember to check there also, after
  updating the php.ini.

Also, make sure your permissions are set correctly from your public/private folders you've set Drupal for file handling. The folders are located at /admin/config/media/file-system


Image-clicking Q&A captcha alternative that is customisable? I'm looking for a simple way to spam-proof new user registration that works along the lines of Confident Captcha (demo, module page).

These work by asking a simple question, then the user clicks on the appropriate image. Very easy for humans, very difficult for bots.

My problem with the Confident Captcha system, however, is that it relies on a 3rd party plugin which isn't customisable. I want to be able to set the questions, images and widget display to match the content and theme of my site.

Note: I'm aware that this approach has accessibility issues for blind or partially sited users. For my project, this can be dealt with manually and isn't an issue, but bonus points for options that have a built-in accessible alternative.

Also, bonus points for options that don't depend on a 3rd-party service.

One related module worth mentioning:

Captcha Questions - totally customisable, but appears to be text only requiring users to do more typing.

Here's one option I've found - Fancy captcha - based on a library which uses icons. Looks like a simpler stack than Confident Captcha, but no stable release on D7.

Pros:

Based on a re-purposed library installed locally, so you can modify the files
Doesn't require a third-party service

Cons:

No stable non-dev release yet (at time of posting)
I can't see any evidence of an accessible fallback for screen readers etc


Trying to programmatically redirect I’m trying to redirect users in Drupal 8 as I was used to do in Drupal 7 with a simple drupal_goto().

This is my code.

$response = new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url($url_redirect));
$response->send();

Executing it, I get the following error:

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route http://mydomain.es/participar?utm_source=RTB&utm_campaign=&utm_medium=banner&utm_term=1
  does not exist.

The alias /participar exists. What am I doing wrong?

See drupal_goto() has been removed.

  Drupal 8 (procedural)

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_menu_callback_foo() {
  //....
  return new RedirectResponse(\Drupal::url('user.page'));
}

  Drupal 8 (properly injected)

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

  If the route name is not known use RedirectResponse with a URL. When redirecting to an external location, use TrustedRedirectResponse.

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return new TrustedRedirectResponse('https://example.com/some/path'); // for eg. Url::fromUserInput(\Drupal::destination()->get())->setAbsolute()->toString();
  }
}


Drupal API to check a particular user is logged-in, or not Is there an Drupal API to check whether a user is currently logged in or not, based on the user ID, such as is_user_login($uid)?

No, there is no function like is_user_login($uid), but you can see how the core block "Who's online" is created (source).
Drupal has a "sessions" table, where all current sessions are stored.


Add JavaScript code to the backend I want to run some JavaScript code during the document ready phase.

Where can I place this code so that it runs each time a page is loaded?
I am using Drupal 7.

The easiest solution would be to add the code in your theme. This is done by adding

scripts[] = path/to/file.js

in your theme's .info file. If for any reason don't want to handle this in your theme, you could instead add the javascript from within a module, using hook_init

function module_name_init() {
  drupal_add_js(drupal_get_path('module', 'module_name') . '/path/to/file.js');
}

For the javascript to execute on document ready, you can either use jQuery's ready event, or use a behavior.

This could look like this:

(function ($) {
  $(document).ready(function() {
    // jQuery's document ready event
  });
})(jQuery);

(function ($) {
  Drupal.behaviors.name = {
    attach: function(context, settings) {
      // Drupal's behavior execute on document ready.
    }
  };
})(jQuery);


Unix time stamp to date I'm displaying a custom table in a view with Data & Schema module.
One of my field in that table is created_date, int of unix timestamp.
The view's page shown as table, how can I display it in a readble format?

You need to describe the table for views to know which handler to use. For that you have to implement hook_views_data_alter. It looks complicated at first, but its definitely worth it :).

EDIT :
Data & Schema should allow you to set the handler, somewhere in the properties of the table. I haven't used it for a while but am quite sure its there :).


How do I disable some available countries in Commerce Shipping? I am using Commerce Shipping and I need to disable all countries, except for Canada and the US. How do I make it so only those two are available in the Shipping Info on checkout?

Easy (assuming Drupal commerce 7.1 in my testing) - you want to just navigate to

Admin > Store > Commerce Profiles > Profile Types > Manage Fields > [Your Address Field] > Edit

Under 'Available Countries', select the ones you want per the instructions 'If no countries are selected, all countries will be available.'

You may also refine the list of available countries that appear in the above-mentioned 'Available Countries' selection list (and any other country chooser in a Drupal 7.x site) with the countries module.


How to modify the commerce price formatter label to match shipping service? Please see attachment. Using Commerce Kickstart 2.

I have a working solution, but I am hoping someone can tell me how to improve it, as it 'feels' poor.

The footer for the default shopping cart view is a footer called commerce_order_total which shows a subtotal for each line item type... typically labeled 'Subtotal' for products and then a generic 'Shipping' label for shipping line items.

That generic 'Shipping' label is hated by our customers. They expect to see the actual shipping service (UPS, Fedex, etc.) So I created a work-around, which I show below, but I fear it is not an efficient solution... basically I just made a tweaked copy of the default commerce code for the price formatter.

What I hope to improve...

Surely there must be a more robust way for the footer to be 'aware' of whether the page being viewed is a cart or an order from history without having to look at the URI, right?
And is there a faster/cheaper way to retrieve the shipping service without loading the entire order -and- all line items?
I was thinking there must be a more granular way to override the description of 'Shipping' in that footer without having to re-invent the entire wheel. I just gave up and did the old cut/paste.

TIA,

---JC

function MYTHEME_commerce_price_formatted_components($variables) {
  global $user;
  $line_item_title = '';
  $order_number = '';
  $path_parts = explode('/', request_path() );
  if( sizeof($path_parts) == 4 && $path_parts[0] == 'user' && $path_parts[2] == 'orders') {
    $order = commerce_order_load($path_parts[3]);
    // dpm($order);
  }
  if( isset($order) && !$order )
    $order = commerce_cart_order_load($user->uid);
  if( isset($order) && $order) {
    foreach ($order->commerce_line_items['und'] as $line) {
      $line_item = commerce_line_item_load($line['line_item_id']);
      $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
      // line item TYPE display title
      $line_item_type_title = commerce_line_item_type_get_name($line_item_wrapper->type->value());
        // for shipping line items
      if ($line_item_wrapper->type->value() == "shipping") {
          // shipping data
        $shipping_data = $line_item_wrapper->value()->data;
          // shipping method display title
        $line_item_title = $shipping_data['shipping_service']['title'];
      }
    }
  }
  // Add the CSS styling to the table.
  drupal_add_css(drupal_get_path('module', 'commerce_price') . '/theme/commerce_price.theme.css');
  // Build table rows out of the components.
  $rows = array();
//  dpm($variables['components']);
  foreach ($variables['components'] as $name => $component) {
//    dpm($component);
    if($component)
    $rows[] = array(
      'data' => array(
        array(
          'data' => ($component['title'] == 'Shipping' && $line_item_title ) ? $line_item_title :  $component['title'],
          'class' => array('component-title'),
        ),
        array(
          'data' => $component['formatted_price'],
          'class' => array('component-total'),
        ),
      ),
      'class' => array(drupal_html_class('component-type-' . $name)),
    );
  }
  return theme('table', array('rows' => $rows, 'attributes' => array('class' => array('commerce-price-formatted-components'))));
}

I think this is equivalent - not sure there's a better way than loading all the line items.

function HOOK_commerce_price_formatted_components_alter(&$components, $item, $entity) {
  foreach ($entity->commerce_line_items['und'] as $line) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line['line_item_id']);

    if ($line_item_wrapper->type->value() == "shipping") {
      $shipping_data = $line_item_wrapper->value()->data;
      $service_title = $shipping_data['shipping_service']['title'];
      break;
    }
  }

  if (isset($service_title)) {
    $components['shipping']['title'] = $service_title;
  }
}

(The title is coming from the price component type - maybe one could use hook_commerce_shipping_service_info_alter() to change the price_component to something per shipping service, and set the title in hook_commerce_price_component_type_info(), but that probably isn't any neater.)


Get the node ID from the "node/add" menu item and hook_form_alter() I want to set a unique 7-digit code to a custom content type and display it in a disabled textfield when a node is created. I created a CCK textfield and set it to disabled in hook_form_alter, great.

I think that a good way to make this unique ID is just to use the node id and fill it out to the required length (eg. 0000012). It doesn't look like $nid is available at the node/add form though. How can I set this ID field to default to the $nid? Can I access the hook_form_alter() as the content is created (on form submission)?

You're right, the nid is not available at this point, it's assigned only after the the node is saved.

The easiest solution is most probably to use hook_node_insert and resave the node after having added the value to the field you have created.


Is the Panels simple cache lifetime a minimum or maximum? In Panels, one can configure caching for blocks/content panes/etc.  The built-in method is Simple Cache, for which two settings can be configured: Lifetime and Granularity.

For Lifetime, one can choose a value from 15 sec to 7 days.

Is this lifetime a minimum or a maximum?  In other words, if I set the Lifetime to 7 days for a content pane, will that content pane be cached for 7 days no matter what?  Or will it be cached for 7 days unless it is updated?

Simple cache, is unfortunately not very clever, hence the name "Simple".

A 7 day cache will be cleared when the first request past the 7 day mark occurs, so it is the minimum lifetime of the cache.

The reason that it isn't smarter than that, is probably that content panes can come in a great deal of forms, and it's not trivial to implement a generic solution to knowing "When something was updated".

Continuing on that, I've implemented Panels cache which attempts to be smarter, but is limited to Content panes based on an entity context. It considers the cache lifetime to be infinitely long, but clears it when the entity that is the context is updated.

It's not terribly well tested, but it was written for a paying client that had it running in production without issues or complaints at least for the months I worked with them.


Is there a way to suppress warnings on the D8 Status Report page? On my D8 status report (admin/reports/status) I have warnings about an issue I might wish to ignore. Is there any way to suppress the warnings on that report page once I have seen them and made my decision?

If it matters, the warnings are about using a CDN instead of installing libraries locally with YAML Form, which produces a wall of ten yellow warning rows in my Status Report. If we decide to continue using the CDNs instead of installing, we'd like to not see those warnings taking over so much real estate on the Status Report page in the future.

Unfortunately there is no hook_requirements_alter yet. As a workaround you may override system manager service which is responsible for invoking that hook.

src/SystemManager.php

namespace Drupal\example;

use Drupal\system\SystemManager as DefaultSystemManager;

/**
 * System Manager Service.
 */
class SystemManager extends DefaultSystemManager {

  /**
   * {@inheritdoc}
   */
  public function listRequirements() {
    // Suppress some unwanted warnings on Status report page.
    return array_filter(parent::listRequirements(), function ($requirement) {
      return $requirement['title'] != t('The message about CDN.');
    });
  }

}

src/ExampleServiceProvider.php

namespace Drupal\example;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Overrides the system manager service to suppress some warnings.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $container->getDefinition('system.manager')
      ->setClass('Drupal\example\SystemManager');
  }

}


How to show filesize when content type contains more than one file? I'm using Drupal 7 and having File 7.14 field installed.I have a content type (named file) containing more than 1 file. I have a view that shows the filesize of all the files of the content of that content type named file.
For doing that I have added  a relationship in Views to "select File Usage: File"
The filesize is nicely shown for content that contains only one 1 file.

However for content containing more than 1 file the filesize is only shown for the first file but not for the 2nd 3th etc.

Here is how my query currently looks like:

SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0

Can anybody explain me how to change the View settings so that the filesizes of the other files are also be visible?

Actually it works fine for me without additional settings

My configuration :

I used content-type : Article and create some fields file
Your first step is good, you need to add a relationship select File Usage: File
Then in your fields section you can add : Content: Title , File: Size, File: Name

I have a listing of all the name of the file with their size.
If you want you can group by Articles.


Hook to change display widget in facet api from template.php In my site i have search api with one block facet option "Display widget" set to "Links with checkboxes"

but now i want to change the value to "Links"

because when the website is displayed on a mobile device i need to change to this option value.

Is there a way to change this option through any hook or another way to get this accomplished?

Maybe put a hook in template.php is my closes approach.

Thanks :)

Create another index and configure facet display differently


How to configure Workbench to allow author to publish own content without moderation? I have author role for creating content. This content is moderated by moderators. Now I would like to add second role super author. Super author can published his own content without moderation. How should I configure Workbench for this?

EDIT

There is a WB Access permission for this:

  Bypass moderation restrictions

Have a look at this issue, it discusses this topic: https://www.drupal.org/node/1338750


From where the execution starts in Drupal Generally in any HTML file execution starts from index.html and PHP file starts from index.php.

But in Drupal from which file the execution is started, i know that it is started from bootstrap file but what calls the bootstrap file ?

What is the execution sequence when i write http://example.com which will load/install drupal ?

index.php inside Drupal root folder is the starting point of execution. It calls the bootstrap functions. Please see the code inside drupal 7 index.php file below.

define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();