Restore the body field I am new to Drupal 8. I had a understanding that, Drupal by default provides you a Title and Body field for content type.

I have an ongoing project, and I realized that one of the content types is missing the body field. How can I restore it?

You can do it through the UI:

Visit /admin/structure/types/manage/CONTENT-TYPE/fields/add-field.
Choose the body field from the Re-use an existing field select.
Click Save and Continue.
Configure the field for that specific content type and save.


Switch between two views by clicking on a menu tab without any page refresh I have created two views on my custom content type as two different blocks. I want to place them in a new page say /node/47. In node/47 there are two tabs...on clicking one of them view 1 appears and on clicking another on of them view 2 appears while view1 goes away...by default any of the view can appear on the page when its first visited..i do not want any page refresh to take place

Thanks

You can try the Quick Tabs module.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content. Clicking on the tabs makes the corresponding
  content display instantly, using jQuery. With the 6.x-2.x branch, this
  can be done in either ajax or non-ajax mode:


How to skip specific tables with drush sql-dump? I have a drush config file ~/.drush/drushrc.php:

if (!isset($options['structure-tables']['common'])) {
  $options['structure-tables']['common'] = array(
    'cache', 'cache_*', 'history', 'search_*', 'sessions', 'watchdog'
  );
}

$options['structure-tables']['common'] = array_merge($options['structure-tables']['common'],
  array('ctools_css_cache', 'ctools_object_cache', 'logz', 'views_object_cache')
);

And I have a bash script file:

/usr/bin/drush sql-dump --root="/home/username/domains/sitename/www" --skip-tables-key="common" --gzip --result-file=/home/username/backup/$year/$month/dbname_$date_now_time.sql

But when I execute it the backup file still have data in cache tables.
What am I doing wrong?

And second question is - If I put this into crontab do I need to put configuration file somewhere else?

I use Drush version 8.

Dump all tables except the cache table and tables starting with cache_.

drush sql-dump --skip-tables-list=cache,cache_* > dumpfile.sql

Database structure only. No data at all.

drush sql-dump --extra=--no-data > dumpfile.sql

Data only. No cache data and no cache structure.

drush sql-dump --skip-tables-list=cache,cache_* --data-only > dumpfile.sql

No cache data but dump in their structures.

drush sql-dump --structure-tables-list=cache,cache_* > dumpfile.sql

sql-dump documentation


Trigger ajax action by url or link I currently have a page which has a block with taxonomy terms displayed.  Each link has been made to work with ajax to display information below if clicked, generated in a module callback.

What I am trying to acheive is also have this work if linked to.  So for example my page URL is currently http://localhost/events/building01
If someone was to visit http://localhost/events/building01/printer then the information for printer would be displayed under the taxonomy term as it would if someone had clicked on the term.

My ajax links are currently setup like:

function building_block_menu()
{
  $items['events/%/%/ajax'] = array(
  'title' => 'ajax call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_ajax_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  $items['events/%/%/nojs'] = array(
  'title' => 'nojs call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_nojs_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  return $items;
}
function _event_ajax_callback($building, $type)
{
  $markup = $building . ' - ' . $type;
  $ajax_commands = array();
  $ajax_commands[] = ajax_command_html('#ajax-target', $markup);
  ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}
function _event_nojs_callback()
{
  return "no js to be built";
}

And called from links built like:

$output .= l($term->name, 'events/$building/'.$term->tid.'/nojs', array(
            'attributes' => array('id' => 'building-term-'.$term->tid, 'class' => 'use-ajax')
            ));

The easiest option would be to add an ID to each link like link_printer and then use jQuery to parse the url, get the last fragment, and click any links that match.

var splitURL = window.location.href.split('/');
var link_id = '#link_' + splitURL[splitURL.length - 1];
if ($(link_id).length > 0) document.querySelector(link_id).click();


How do I change the top picture for blueprint theme? I just need to change the top image of the website to another image. The website is using Drupal 6 and the Blueprint theme. I am able to get to the theme building page, is that the right place to start?

First of all: You shuldn't use Drupal 6 anymore as it has reached EOL (https://www.drupal.org/drupal-6-eol).

The regular way to replace the page logo is through the admin interface. You should have an logo file field on your theme settings page.

Another way is to check out the logo path with with firebug (or F12 for the regular browser console) and replace it directly with your ftp client.

Edit: If "Top Image" means something else then the logo, you can also use the second method, but make sure the determined image is not processed through imagecache, otherwise it will be overridden after the next cache clear.


How to add field content as class in Twig? I want to add the content of a field (i.e. "workshop") as a class in field-html.twig

i tried

{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    'icon-' ~ item.content,
  ]
%}

but it only shows "icon-" as a class.

item.content works only in the items loop, but don't try to put rendered output in a class name. Use the field value instead, which you can get through the field object #items stored in a field template inside of the variable element:

{{ element['#items'].value }}

or from a different field of the parent entity:

{{ element['#object'].field_example.value }}

Depending on the field type replace .value with a different property, for example for a reference field to get the target id or the label of the target with .target_id or .entity.label.

When you have found the field value build your class name:

{%
  set classes = [
    ...
    'icon-' ~ element['#items'].value|clean_class,
  ]
%}


Single sign on between different Drupal versions Is it possible to have this module working with different Drupal versions?
We have some big projects in Drupal 6 and we want to start with a migration plan. Without being able to migrate parts of our sites, the task is much more complex than being able to do small migrations and tests.

I have seen there is the Bakery Single Sign-On System, but I don't know if it can be used when the subdomains use different Drupal versions.

UPDATE: bakery works like a charm for that. You can install it on different Drupal version sites, different fillet on same domain and, of course, different sub domains.

With the drupal-6 site override hook_login_validate() and write your own authentication mechanism. Simpler than it sounds, as any function that returns TRUE or FALSE based on success will work. It could directly access the database or connect via a JSON web service to the drupal-7 server. I described how to implement authentication via JSON on stackoverflow.

function mymodule_login_validate($form, &$form_state) {
   $username = $form_state['values']['name'];

   // do if condition to see if your authentication is required.
   // e.g. you might want to keep the drupal administration users.
   if (_mymodule_use_webservice_login($username)) {
     // We are logging in using service.
     if (_mymodule_validate_password($username, $form_state['values']['pass']) {
       user_external_login_register($username, 'mymodule');
       user_authenticate_finalize($form_state['values'];
    } // else drop through to the end and return nothing - Drupal will handle the rejection for us
   }
} else {
    // Username is not an member number, so use standard Drupal authentication function
    user_login_authenticate_validate($form, &$form_state);
}

_mymodule_validate_password() is where the authentication occurs and the only other function you need to implement. See the stackoverflow site for calling a JSON web service. Try to use SSL as passing passwords over SSL is not great, although your main site may not be SSL anyway.

Implementing the web service is a function return TRUE or FALSE - drupal_json_output. You need to set up a menu, with a function callback. The function callback would call user_authenticate().

You could also try one of the SSO modules. http://groups.drupal.org/node/182004. It is usually good policy to not implement your own security code so that the code gets tried as much as possible.


Text format dropdown has dissapeared from edit article form There is something strange it happened at a certain time. I no longer can set the text format from article (node) edit because the Text format input has dissapeared.

I can configure them from Configuration page but no longer can choose them from edit mode.

I have all permissions over them set up ok.

Please if you have any suggestions help me up.

Strangely, this combo dissapeared from admin/structure/types/manage/CONTENT_TYPE/fields/body as well

I tried to alter the content type filter using a module but no luck:

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

 $form['body']['und']['0']['#format'] = "full_html";

}

I have experienced this issue when a rich-text editor is enabled. In my experience, the input format box reappears when the rich-text editor is disabled.


Should dependent libraries list all dependencies? If I have a library called foo and it depends on jquery I will list is a dependency.
But what if I have libraries bar and baz that depend on foo and also jquery. Do I only add foo as a dependency or should I also add jquery as well? What is the concensus on this?

In general, a library (or any entity/resource in programming that depends on other entities/resources) should only include dependencies for things that it actually uses.

Given your example, bar and baz should depend on jQuery if they use jQuery functions directly. If, however, they only use functions that are provided by foo (which, in turn, uses jQuery), then bar and baz should not depend on jQuery.

Here's another way to look at it: in the future, if foo no longer needs jQuery, and you remove jQuery as a dependency from foo, do bar and baz break as a result? If they break, then they should have had a direct dependency on jQuery. If they don't break (because all of the jQuery dependency is encapsulated in foo), then they don't need a dependency.


Where is the target ISBN in feeds module? I'm using an ISBN module that create a simple textfield with "ISBN" as a type (this module makes validation of the books ISBN when inserted on the textfield when creating a book) It's a pretty cool module.

But now i want to populate my database with books from a CSV file, so in the header i've : "title, author,..,ISBN" i import this CSV file using feeds module, everything is imported except the ISBN. Even when i want to create a mapping for ISBN, i can't find field_data_field_isbn in the targets list. I know that the ISBN module makes validation (or not) for isbns only if you "write it" manually using the textfield. But is there any way to get ISBN from CSV with feeds (it's not important if it's validated or not) ?

Thank you

The ISBN Field module doesn't support Feeds yet. Every module that provides a field should write their own mapper to support Feeds, as Feeds isn't able to dynamically know how to populate a field.

In the ISBN Field issue queue there is a patch available which might solve your problem: https://www.drupal.org/node/1930538


nodejs server set up UPDATE:

The node.js server is now running correctly at Openshift. The node.js server and the socket.io script can now be accessed publicly.

Running cron in Drupal, I see that it can also access the node.js server. However, my problem now is this, from the Chrome console:

  GET https://nodejstapchat-breathalert.rhcloud.com:8080/socket.io/?EIO=3&transport=polling&t=LM-NWXx net::ERR_CONNECTION_TIMED_OUT    socket.io.js:3511

I think it has to do with that redundant port in the url. Can anyone confirm?

ORIGINAL QUESTION:

Having problems while setting up the drupal nodejs module to use with Chatroom. This is working for me on localhost, so I suspect it has something to do with HTTPS.

The Drupal site is served only via HTTPS, and I just got the nodejs server, running on Modulus.io with HTTPS.

The drupal nodejs module (v7.x-1.13) and nodejs server (v1.0.9) are of compatible versions (based on the doc). Also confirmed the matching config on the Drupal site as well.

Checking the HTML source on one of the chat pages using nodejs, came across this:

<script src="https://tapcreativechat-64706.onmodulus.net:8088/socket.io/socket.io.js"></script>

But it appears it does not return the socket.io script (also tried port 8080).

Second related problem is the messages in Drupal dblog:

  Error reaching the Node.js server at "nodejs/health/check": [-110] Connection timed out.

I am out of ideas why Drupal can't connect to the nodejs server.

My Node.js server config file:

//Node.js server
settings = {
scheme: 'https',
port: process.env.PORT || 443,
host: 'localhost',
resource: '/socket.io',
serviceKey: 'key',
//Drupal site
backend: {
    port: 80,
    host: 'tapcreative.services',
    scheme: 'https',
    basePath: '/',
    messagePath: '/nodejs/message'
},
debug: true,
sslKeyPath: '_privatekey.key',
sslCertPath: 'tapcreative_services.crt',
sslCAPath: 'all_certs.crt',
baseAuthPath: '/nodejs/',
extensions: [],
clientsCanWriteToChannels: false,
clientsCanWriteToClients: false,
transports: ['websocket', 'polling'],
jsMinification: true,
jsEtag: true,
logLevel: 1
};

Advice is appreciated.

your first host: '', (line 4) is empty, should be host: 'tapcreative.services',

In addition, you're using the wrong port, port 80 is for HTTP. You need to use the HTTPS port, 443.

Change line 8 from port: 80, to port: 443,


Home Page rel="canonical" We created a home page as node/1850 which is specified in /admin/config/system/site-information.  When I look at the generated code, I see:

<link rel="canonical" href="/node/1850" />

This results in Google listing the url of the home page as https://dom.ain/node/1850 which is not what we want.

What is the best way to correct this?  I believe the following is correct.

<link rel="canonical" href="/" />

You can use metatag module to adjust metatags like these.

After installing you can visit the settings page /admin/config/search/metatag and there is a specific set of metatags to adjust for front page.  Edit those settings and adjust canonical but I believe by default it sets this to [site:url] which should be OK.

Alternatively or if you don't want to install a module just for this you can do it using hook_preprocess_html in your THEMENAME.theme

function THEMENAME_preprocess_html(&$variables) {
  //if not front page do nothing
  if(! \Drupal::service('path.matcher')->isFrontPage())
    return ;

  //unset if set
  foreach ($variables['page']['#attached']['html_head'] as $key => &$value) {
    if ($value[0]['#tag'] == 'link' && $value[0]['#attributes']['rel'] == 'canonical') {
      unset($variables['page']['#attached']['html_head'][$key]);
      break;
    }
  }

  //add canonical
  $canonical = [
    '#type' => 'html_tag',
    '#tag' => 'link',
    '#attributes' => [
      'rel' => 'canonical',
      'href' => '/',
    ],
  ];
  $variables['page']['#attached']['html_head'][] = [$canonical, 'canonical'];
}


Image Styles Broken? I have a new view that is coming up with a new issue, there is a "main image" for every entry, and for some reason after loading the page, almost all images break. But what's odd is that when you click on the Title Number or the Image (whichever you want to get to the content), the images in the format of "Original Image" loads almost automatically.

My link is below, let me know if it is something I am not doing right (and can't seem to see it at all)

http://cocemproject.org/pueblo/survey-register

Thanks!

-----------UPDATE---------------

If I stylize the main image as "Original Image", the image shows - but when it is stylized to my new Image Style "125x125" (which is 125px by 125px Scaled & Cropped), it breaks.

-----------UPDATE---------------

I tried a different Image Style that I know works elsewhere on the site, and it doesn't work here. Also, tried the format "Colorbox" just out of curiosity, and it makes the image field image disappear completely, not even a broken picture.

-----------UPDATE---------------

I also right-clicked the broken image and clicked "View Image", it leads me to http://cocemproject.org/pueblo/sites/default/files/styles/125x125/public/DSC_0131_1.jpg?itok=kGUeABuy but there is nothing there.

-----------UPDATE---------------

Now, I have gotten around to looking into my files and it appears that the Styles were never generated for these images.

-----------UPDATE---------------

Saw https://www.drupal.org/node/1109312#comment-10021707 and that clean URLs might be causing this, disabled the module, ran cron, cleared caches. Still no change.

-----------UPDATE---------------

Below are the folders with the permissions. I tried altering them and then flushing caches and running crons (just to hit everything).

-----------------UPDATE------------------------

Turns out that these photos are too large for this site, and Drupal's just giving up on applying the styles to them. What's odd is that this site is technically a complete copy of an old one, just better planned out to incorporate recent changes on the old version. However, I used the exact same styles with the exact same pictures and had no problems. I'm still on the same server, just a different folder. What might be causing this?

This should be a folder permission issue. What you need to do is check the image style folder (sites/all/default/files/styles) if it is writable. You can use ls command to check the directory permission. To change the permission you either need chmod or chown commands to make the folders writable by Drupal.

Once the permission are correct you may need to flush the cache for images. If you have Drush you can do that by running drush image-flush STYLE_NAME or by clearing them all by running drush image-flush all.


Problem with Profile2 and NodeAccess We use Profile2 and Node Access but the profiles of users can't be show by everyone (access denied)  since we have installed Node Access. The problem is the same with Content Access.
Do you know how we can see profile of users and use Node Access or Content Access ( we want to limit access on pages of our intranet's ?
Thank you.

Thank you for your help. Finally we use a taxomony and Taxomony Access Control and we don't have the problem !
We create a vocabulary : Intranet with two words Private and Public. And we use Taxomony Access Control


Can I check a file's properties before saving it with system_retrieve_file? My understanding of system_retrieve_file is that it saves the file temporarily first. Is it possible to check this file and if it passes, then save it?

I've only used this function like below.

$image = 'http://.jpg';
$file = system_retrieve_file($image, 'public://images/', TRUE, $replace = FILE_EXISTS_REPLACE);

Thanks

It depends on what the file "properties" you're wanting to check here.

The file contents? Sure. You can invoke $result = drupal_http_request($url);(7) or \Drupal::httpClient()->get($url)->getBody();(8) ahead of time to inspect the HTTP contents before calling system_retrieve_file().

The file entity properties (or the temporary file created before moving to $destination)? No (without replicating/modifying some core functionality). There are no open hooks to that before system_retrieve_file() commits to saving that data to filesystem/DB.


Commerce Hook Function To Checkout Button I am a Drupal Commerce novice. I have a basic cart system working fine, but I now need to get into some custom code. I don't think I can use Rules because the code is a bit too complicated.

I have a Shopping Cart page with a Checkout button. I want to hook into that Checkout button.

I need to add a php function (which I already have) which will execute when that button is clicked but -before- the checkout page is rendered.

And I need this to do so without disabling the default actions that the Checkout button performs.

SO: How do I hook into this button without disabling the default behaviour?

Due to my noobness--I'd appreciate as complete an example as possible. I'm not lazy, just can't take for granted that I'll catch everything I need to if the answer is 'shorthand'.

TIA,

---JC

The checkout form is a form like any other, so you can just alter it (using hook_form_alter()) and add a submit handler:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_commerce_cart_form_default') {
    $form['#submit'][] = 'MYMODULE_some_function';
  }
}

function MYMODULE_some_function($form, &$form_state) {
  drupal_set_message('This was run after the cart form was submitted, before the checkout page was rendered.');
}

Addressing the comments...

As you have a custom shopping cart form, with a link instead of submit button, no extra processing will be done so you can just hook into the page build of the linked page (/checkout/%) and perform your operation there; it will have the same effect.

There are a couple of places you could do this (neither really 'better' than the other), hook_page_alter() and hook_init(). There are other places too (theme preprocess functions) but for processing logic something a bit earlier is probably more appropriate. Basic example (will probably need tweaking for your needs):

function MYMODULE_init() {
  if (arg(0) == 'checkout' && $some_other_pertinent_condition) {
    // Do some processing.
  }
}

As for learning Commerce - that's a tricky one. Commerce is heavily integrated with Drupal and uses a lot of its functions/hooks/integrations just like any other module would. So really you need to know Drupal's workflow, and then overlay Commerce's workflow on top of that. The best advise I can give is to grab a Drupal book (Pro Drupal Development is excellent), and after you're happy with the workflow there, hit the Drupal Commerce support pages and read, read, read.

Drupal has a notoriously steep learning curve, and there isn't really a shortcut to understanding how it works as a whole. You just have to get stuck in. But it's well worth it, Drupal's awesome.


No delete button for a content reference I have a custom block type in Drupal 8 where I reference an unlimited amount of content nodes. Now that I want to delete a reference, there’s no delete button available or label that mentions any kind of operation at all.

If you look at the "image reference field" there’s an operation to delete one image reference after another:

Where can I find this delete option for content references? Simply leaving the field blank and pressing save will raise a validation error.

To delete a value from your "Content Reference" field, simply leave the textfield of the desired row-to-delete blank (the multi-field widget for autocomplete fields doesn't have a delete button, it infers which rows should be maintained/deleted based on the presence of a value).

You've marked that field as required (notice the red asterisk at the top), so it must contain at least one value for the form to pass validation. If that's undesirable, just visit the manage fields page, edit the field, and remove the required constraint.


Get url path of node using entity query I'm trying to figure out how I can get the path of a node via entity query. So far I've managed to fetch the title of the node but I can seem to find a solution on how to get the node path/url. Here is a sample of my code

$facultyPostings = $query->get('node')
                           ->condition('status', 1, '=')
                           ->condition('type', 'careers')
                           ->condition('field_career_directory', 'Faculty Postings', '=')
                           ->sort('created')
                           ->execute();

foreach ($facultyPostings as $key => $faculty_postings_careers) {

     $careersNode = _nodeLoad($faculty_postings_careers);

    $variables['faculty_postings'][$key]['title'] = $careersNode->get('title')->value;
    $variables['faculty_postings'][$key]['path'] = $careersNode->get('path')->value;
}

It depends on what you want to generate. To get the \Drupal\Core\Url object for the node:

$node->toUrl();

To get a URL string:

$node->toUrl()->toString();

To get a \Drupal\Core\Link object:

$node->toLink();

To get an HTML string for the link:

$node->toLink()->toString();


Is it necessary to have a separate voting tag for each rating when using Fivestar? By design I will have a ratings page with many things to rate - 30 different Fivestar ratings altogether in the same content type.

Is it necessary to have a separate voting tag for each of these 30 ratings? Because I see there is a character limit on the field in Fivestar tags configuration and I can't input all my voting tags.

Yes, you need a separate voting tag for each ratings in the same content type, if you use the same for multiple fields, each field will recieve the same rating.

You can make a test, create two fields with the same tag, go to create one node and rate one field, refresh the page and you will see the same rate in the other field.


Logo is not displaying This is the code I used in Drupal 7.

            <a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">
                <img src="<?php print $logo ?>" alt="<?php print t('Home') ?>" />

This is the code I am using for Drupal 8.

    {{ logopath }}

If I upload the logo, it doesn't display. What should I do now?

This Link might be helpful :  http://www.lohmeyer.rocks/blog/2015/01/14/00187-print-your-themes-logo-path-drupal-8-twig.

I think you should define the logo path variable first into template.tpl in MyTheme_preprocess_page function.

One More thing you are trying to use {{logopath}} in 'span' tag and into 'src' its {{logo}}.


Enabling a block to inherit the settings of a sub theme Being relatively new to Drupal, I apologize in advance if what I'm saying is unclear, but I'd imagine that a fix should be simple enough:

Basically, I'd like to add a header block that functions identically to the other block regions on my Drupal site. At the moment, the text of that header is not responsive to window size, unlike the rest of the site. How can I inherit the default settings of my theme when creating a new block?

Thanks in advance, a solution to this would help me tremendously.

You can style a block however you like - since it is going in the header, it sounds like a css issue for the header region. I would start by comparing the css for the content and/or footer regions with that of the header.  If all else fails, you can theme individual blocks - here is some info.


Display textfield as clickable link I am trying to make textfields clickable so it would appear as link. What would be the best solution for this? I tried Link module, but it is not what I am looking for. This is how I got my textfield written:

$form['element4']['link4'] = array(
        '#type' => 'textfield',
        '#title' => t('link for 4th div'),
        '#description' => t('your link'),
    );

I need for it to stay textfield as user can input his value, but I want it to be displayed lets say in blue color and so that you could click on it. How could I do this in the most simple way?

What you need is the #ajax property of the Form API. Have a look at this page to find the answer to your question:

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


How to show multiple Series of line charts in Views with the Charts module? I need to create multiple line charts in the same chart.  I have a year column, a product column, and a consumer column.  I can plot product and year or consumer and year, but when I use all three columns I get a chart that puts both product and consumer data on the same line.

I am using the Charts module, with the Highcharts library as its charting engine and its views integration.

How can I get a product and consumer line to appear on the same graph?  I was hoping for the chart to look like Preview 6 here: https://www.drupal.org/node/2426177#preview6

Here is what my chart looks like.

Data:

Products:

Consumer:

Both:

The way to get this to work (to put those charts together), is to work with what's called  "parent charts" and "child charts", as explained within Steps to create charts using the views UI. More specifically what's detailed within the paragraph "Creating Multiple Series and Combo Charts in the UI". Here is a quote from it:

... you can combine multiple charts on top of each other. The "parent" chart provides the global information, such as the height, width, title, and other properties. Charts that are "children" provide only data and (optionally) a secondary axis. After you've assembled the first series of data in your chart according to the instructions in the Creating Charts using the Views UI section, add a new display to the same view of the type "Chart Add-on". The "Chart Add-on" type is added the same way you would add a new Page or Block display, from the "+ Add" menu at the top of the view configuration.
After this new display has been added, find the setting for "Combine with parent chart" and change this value to point at the parent chart you have already assembled. Then adjust the settings for the child chart to pull in different data (often by overriding the filter settings). Now you can go back to your parent display, and see that the results from the child chart have been merged into the results from the parent chart. You can even use this approach to combine different types of charts, such as a line chart over the top of a column chart. Note that not all chart types can be combined together and invalid combinations may cause your chart to throw errors.

Refer to "Combination chart without aggregation" for an online demo of such chart. Here is a quote from it:

The chart below (created using the "charts" module) shows a
combination chart about all nodes of content type "Article", which has
these fields with these "machine names" (+ values):

"field_optionlist" (with some select list values, such as the "year")
"field_free_format_text" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
"field_free_format_nr" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.

This online demo consists of a combination of 2 "Area charts". If you only change the "settings" for each of the 2 charts to "Line chart" (within "format" of each view), you'd get a similar set of combined charts but shown as line charts instead. Here is the view (in views export format) that created that chart (using "Line chart" as the format for both charts):
$view = new view();
$view->name = 'combination_chart_without_using_aggregation';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Combination chart without using aggregation';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Combination chart without aggregation';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'body';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'body' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'body' => '#2f7ed8',
  'field_free_format_text' => '#233a99',
);
/* Header: Global: Text area */
$handler->display->display_options['header']['area']['id'] = 'area';
$handler->display->display_options['header']['area']['table'] = 'views';
$handler->display->display_options['header']['area']['field'] = 'area';
$handler->display->display_options['header']['area']['content'] = 'The chart below (created using the "charts" module) shows a combination chart about all nodes of content type "Article", which has these fields with these "machine names" (+ values):

- "field_optionlist" (with some select list values, such as the "year")
- "field_free_format_text" (assumed to contain some numeric values), with Y-axis left, is used in the parent chart.
- "field_free_format_nr" (assumed to contain some numeric values), with Y-axis right, is used in the child chart.';
$handler->display->display_options['header']['area']['format'] = 'filtered_html';
/* Field: Content: Free Format Text */
$handler->display->display_options['fields']['field_free_format_text']['id'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['table'] = 'field_data_field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['field'] = 'field_free_format_text';
$handler->display->display_options['fields']['field_free_format_text']['label'] = 'Products';
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);
/* Filter criterion: Content: OptionList (field_optionlist) */
$handler->display->display_options['filters']['field_optionlist_value']['id'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['filters']['field_optionlist_value']['field'] = 'field_optionlist_value';
$handler->display->display_options['filters']['field_optionlist_value']['value'] = array(
  13 => '13',
  14 => '14',
  15 => '15',
);

/* Display: Chart */
$handler = $view->new_display('page', 'Chart', 'page');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['xaxis_title'] = 'Year';
$handler->display->display_options['style_options']['yaxis_title'] = 'Nr of Products';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_text' => 'field_free_format_text',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_free_format_text' => '#7b0d49',
  'field_optionlist' => '#8bbc21',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['path'] = 'combinatuion_chart_with_no_aggregation';

/* Display: Chart add-on */
$handler = $view->new_display('chart', 'Chart add-on', 'chart_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'chart_extension';
$handler->display->display_options['style_options']['type'] = 'line';
$handler->display->display_options['style_options']['label_field'] = 'field_optionlist';
$handler->display->display_options['style_options']['data_fields'] = array(
  'field_free_format_nr' => 'field_free_format_nr',
  'field_optionlist' => 0,
);
$handler->display->display_options['style_options']['field_colors'] = array(
  'field_optionlist' => '#2f7ed8',
  'field_free_format_nr' => '#006d1a',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: OptionList */
$handler->display->display_options['fields']['field_optionlist']['id'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['table'] = 'field_data_field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['field'] = 'field_optionlist';
$handler->display->display_options['fields']['field_optionlist']['label'] = 'Year';
/* Field: Content: Free Format Nr */
$handler->display->display_options['fields']['field_free_format_nr']['id'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['table'] = 'field_data_field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['field'] = 'field_free_format_nr';
$handler->display->display_options['fields']['field_free_format_nr']['label'] = 'Enduser Price';
$handler->display->display_options['fields']['field_free_format_nr']['settings'] = array(
  'thousand_separator' => '',
  'prefix_suffix' => 1,
);
$handler->display->display_options['parent_display'] = 'page';
$handler->display->display_options['inherit_yaxis'] = '0';


Migrate files into dynamic paths I have a constant defined in my migration definition like so:

  constants:
    destination: "private://working_papers/"

There are 30,000 files that will come in as part of the migration. I would like to create directory destinations on the fly, based on source field values or whatever I want.

So:

destination: constants/destination

Would become:

destination: constants/destination/@source_field_value/@source_field_value2

This would be to reduce the raw number of files appearing in a given directory. When I try the above, nothing happens, even though the migration succeeds. The files don't go anywhere.

How can I do this? For reference, here is the field in the process section of the definition:

  field_paper_working_paper:
    plugin: file_import
    source: doc_format_url
    destination: constants/destination
    uid: 1
    rename: TRUE

You can chain a concat process plugin to your destination property so that it contains the result of concatenated source & constant values:

field_paper_working_paper:
  plugin: file_import
  source: doc_format_url
  destination:
    plugin: concat
    source:
      - constants/destination
      - '/'
      - source_field_value
      - '/'
      - source_field_value
  uid: 1
  rename: TRUE


How to do an embedded select (with count()) with the Drupal 7 database api? Another day, another challenge with the Drupal 7 database API.  I'm trying to do something like this:

select n.nid,
     (select count(*) as count
          from {node_cnt} nc where nc.nid = n.nid) as node_count
from {node} n

That is, I want to get back a set of node id's and the number of times that each id appears in the table node_cnt.  I'm going to be laying in some other conditions and pager stuff, so I think I need to do this with db_select.  This should be simple, I suppose, but I just haven't figured out the right way to think about this stuff yet.  Any advice out there?  Thanks!

I don't think there's any existing method that will let you add a structured sub-query as an expression, so you're probably going to be left with something like this:

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

$sub_query = '(select count(*) as count from node_cnt nc where nc.nid = n.nid)';
$query->addExpression($sub_query, 'node_count');

// Build the rest of the query.


Get variables from checkboxes I'm creating my very first Drupal module (Drupal 7, btw) and I'm almost done with it. There is one last thing and that is that I need to get the values from multiple checkboxes.

My module list certain nodes and each of them gets a checkbox using a foreach $nid. All using the Form API.

Now, when the form is submitted, only one (1) value is returned - and as of now, not even the one that I check, but the last nodes ID.

Perhaps it is because each new value replaces the previous(?). Or something is wring with my code. Someone in the IRC channel told be that the forms checkbox returns an array of the values, but I'm trying to use foreach of that value, without any success.

What could be the problem?
Here is my code - shorted down.

function my_module_cmp($a, $b) {

  $a = (array) $a;

  $b = (array) $b;

  return strcmp($a['name'], $b['name']);

}

function my_module_form() {
$url = taxonomy_get_term_by_name(arg(1));
foreach($url as $term) {
    $tid = $term->tid;
}
$term = taxonomy_term_load($tid);
$name = taxonomy_term_title($term);
$terms = taxonomy_get_tree(3,0,1);
usort($terms, "my_module_cmp");
$counter = 0;
$result = taxonomy_select_nodes($tid);
foreach($result as $nid) {
    $form[$nid] = array (
        '#type' => 'fieldset'
    );
    // title
    $form[$nid]['title'] = array (
        '#markup' => '
' . $node->title . '
',
    );
    // checkbox
    $form[$nid]['company'] = array (
        '#type' => 'checkbox',
        '#title' => t('Check the nodes balbla'),
        '#title_display' => 'attribute',
        '#return_value' => $nid,
        '#default_value' => 0,
        '#prefix' => 'Skicka förfrågan till företaget >>',
        '#suffix' => '',
    );
$counter++;
}
return $form;
}

    function my_module_form_validate($form, &$form_state) {
// Validate that a company has been checked, at all
$valid_company = $form_state['values']['company'];
    if (!$valid_company) {
    form_set_error('company', 'Forgot to check something');
    }
}

function my_module_form_submit($form, &$form_state) {
$company = $form_state['values']['company'];
drupal_set_message('
'.print_r($form_state['values'], 1).'
'); // Check out the values

foreach ($company as $nid) {
    // Get the node from nid
    $node = node_load($nid);
    // Get the author of that node
    $user = user_load(array('uid' => $node->uid));
    drupal_set_message(t('DEBUG node:'.$nid.', user: '.$user->name.','.$user->mail.'')); // TEST

    // Check if the mail has been sent and show a message based on that
    if (drupal_mail('my_module', 'token', $user->mail, language_default(), $message, $from, TRUE)) {
        drupal_set_message(t('Offert been sent %name',array('%name' => $user->name)));
    }
    else {
        drupal_set_message(t('Error'));
    }
}
}

Your problem is that you have named the chechboxes the same thing which is why you only get one value.

You could replace ['company'] with [$nid] or use '#tree' => TRUE on the field set to make the values turn into a nested array.


Ubercart and Drupal 6 or 7? At present stage Drupal 7 looks very mature, BUT is see some modules are not yet moved to Drupal 7 or not production Ready. For now I had troubles finding UC_Product_Import and UC_AJAX_CART.
I was pretty confident that 7 was the right choice, but I am getting afraid I will need more modules that yet did not do the move to Drupal 7.
What do you think?

What's your reason for looking at Ubercart in D7? I would recommend taking a look at Drupal Commerce. It's not the perfect fit for everyone and is very developer orientated at the moment (this will get better eventually). It is where the future for e-commerce is for Drupal so I would defiantly take a look at it.

If DC isn't an option then it's just a matter of looking which modules you require have a stable release and which are close to a stable release.

Another thing to bear in mind when choosing between Drupal 6 and Drupal 7 is that Drupal 6 will have support (e.g. security releases) dropped for it eventually, so going with Drupal 7 may offer more longevity.


Override or extend function of a contributed module i need to modify the submit function of the module custom_search (8.x-1.0-beta3).

I need to set a Cookie every time the guest user search something, how can i override or extend the submit function?

It looks like not represent a hook. The function is: custom_search_search_page_submit located in the file custom_search.module and called by the custom_search_form_alter function that implements hook_form_alter()

/**
 * Search pages settings form callback.
 */
function custom_search_search_page_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $pageId = $form_state->getValue('id');
  // Save settings, and path as well so we can use it to retrieve the correct settings later.
  \Drupal::configFactory()->getEditable('custom_search.settings.results')->set($pageId . '.path', $form_state->getValue('path'))
    ->set($pageId . '.search', $form_state->getValue('custom_search_search'))
    ->set($pageId . '.advanced.visibility', $form_state->getValue('custom_search_advanced_search'))
    ->set($pageId . '.advanced.collapsible', $form_state->getValue('custom_search_collapsible'))
    ->set($pageId . '.advanced.collapsed', $form_state->getValue('custom_search_collapsed'))
    ->set($pageId . '.advanced.criteria', $form_state->getValue('custom_search_criteria'))
    ->set($pageId . '.advanced.types', $form_state->getValue('custom_search_types'))
    ->set($pageId . '.advanced.languages', $form_state->getValue('custom_search_languages'))
    ->set($pageId . '.info', $form_state->getValue('custom_search_info'))
    ->set($pageId . '.filter.position', $form_state->getValue('custom_search_filter_position'))
    ->set($pageId . '.filter.label', $form_state->getValue('custom_search_filter_label'))
    ->set($pageId . '.filter.any', $form_state->getValue('custom_search_filter_any'))
    ->save();
}

You don't need to override the submit function. Each module or theme can do exactly the same as the custom search module does. Use a form alter hook and add their own submit function to the form array. On submit they are each executed one after another.

mymodule.module

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_search_page_submit';
  }
}

function mymodule_search_page_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // set cookie
}


ckeditor loads all the page html while editing not only the body field I have strange issue with ckeditor that it loads all page source including (header, menu, body, footer ...) not the node body field itself.

the problem may have relation with default search module as it disappears when I re-index the site till the index built again.

I tried many links and that question but nothing works for me.

I tried jquery_update but didn't make any change BTW I see the body field content before the ckeditor loads after that the field content becomes all page source

CKEditor: 7.x-1.16, CKEditor Media: 7.x-1.x-dev, jQuery_update module loading jquery 1.8

I checked ajax requests and found that /ckeditor/xss returns the whole page content.

Please help me fix that issue

Answer:

The solution in my case was based on zhilevan answer solution 2

just added checking for the $view_mode like:

function my_module_node_view($node, $view_mode, $langcode){
 if ($node->type=="webform" && $view_mode != 'search_index'){
 //Do some stuff here
}

solved the issue without the need to disable the search module

Also solution 1 :Switch of "Plugin for inserting Drupal teaser and page breaks" didn't make sense and I think it have no impact here

I had this problem some month ago, one solution with disabling search module was good, but now i've needed search-box working, so i've made a research and found another thing.
In my case the problem was Plugin for inserting drupal teaser and page breaks. I've had this plugin switched off, but button "DrupalBreak" was added to Used button list.
solution 1:
Go to CKEditor profile settings page at '/admin/config/content/ckeditor/edit/[profile_name]'
Switch of "Plugin for inserting Drupal teaser and page breaks" in appearance settings.
Make sure, that "DrupalBreak" button is not in use.
solution 2:
The problem most likely lies within the search-module's cronjob to index the page. This cronjob kind of views the nodes it wants to index. If you use hook_node_view() anywhere in your modules and the cron-user gets an error or gets lead anywhere by a drupal_goto(), the behaviour you described is the result.
Solution: Disable the search-module if you don't need it. If you need it though, check the $view_mode in your hook_node_view()-implementations. If it says "search_index", no redirects should be made. (the easiest way is to just return $node if($view_mode == "search_index")


Resume State - Recruiter Distribution I have been using the recruiter distribution for a while and for some reason I remove the ability of the resume state.  I have analyze the problem and the issue is that every time someone register to the website their resume is automatic on visible state. And I need to make sure that the resume remain hidden until the user at least provide their contact information. This is a critical bug on the site because on the resume search show a lot incomplete users.

Anyone can help me to figure out how to enable the resume state functionality ? Or how to troubleshoot this problem. FYI... I updated the recruiter_features module and nothing happen.

I have post this issue on many places and I have not get any response.

https://www.drupal.org/node/2304539
https://www.drupal.org/node/2311329

Any help will be appreciated.

Views

Reinstating and uninstalling the module again fix this issue for me.


How to represent media as individual entities? I need some architectural advice please.

I'm building a Drupal 8 site for the first time and I need to represent audio and video media on the site.

There are probably fields I can use but I'm looking for a solution which will allow each video or audio to be represented as individual entities on the site so I can list one audio/video entity in multiple locations on the site.

Can anyone advice on how best I should implement my media requirements?

There is a module called Media entity. Some more details about it, from its project page:

Media entity provides a 'base' entity for media. This is a very basic entity which can reference to all kinds of media-objects (local files, YouTube videos, Tweets, Instagram photos, ...). Media entity provides a relation between Drupal and the media resource. You can reference to/use this entity within any other Drupal entity.
This module attempts to provide the base storage component for the Drupal 8 media ecosystem.

I think that it will do what you want.


synchronization on 2 ubercart instances Because of problems with multi-currency ubecart, I am thinking about creating 2 identical e-shops for 2 countries with different currencies. One important thing worries me - stock levels. Is there any way to synchronize stock levels data between multiple drupal/ubercart installations? Thank you very much.

Yes in the stock module is a function for set stock level and you also need a custom xml-rpc client/server functions for both instances.


Programmatically change select field options in contact form I'm currently rendering a contact form programmatically in a block plugin like so.

    $type = 'contact_message';
    $bundle = 'my_contact_form_name';
    $values = array();
    if (\Drupal::entityManager()->getDefinition($type)->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($type)->getKey('bundle');
        $values     = array($bundle_key => $bundle);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($type)
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($type, 'default')
        ->setEntity($entity);

    $my_rendered_form = \Drupal::formBuilder()->getForm($form);
        $content[] = [
            '#type'    => 'html_tag',
            '#tag'     => 'h1',
            '#value'   => 'My Form Title',
            'form'    => $my_rendered_form,
        ];

It grabs and renders the form just fine. But the form has a select field and I want to alter the options for it. This is because the options should be dynamically generated based off the values of certain nodes. I already have a field called 'my_select_field' but I'm not sure how to change the values from it. When using die(print_r($my_rendered_form['my_select_field'])); I receive a very large array and the my_select_field, and the test data I put in it appears in many locations in the array.
My ultimate goal would be to accomplish something like this

$form['my_select_field']['#options'] = [
    1 => 'My new option 1',
    2 => 'My new option 2',
    3 => 'My new option 3',
];

How would I alter the options in a select field in a programmatically rendered contact form?

UPDATE: I found '#options' in the array

        [#options] => Array
            (
                [test1] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 1
                    )

                [test2] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 2
                    )

                [test3] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 3
                    )

                [test4] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 4
                    )

            )

But the options are objects rather than strings I can edit. I should probably also mention that the select field I have is set to multiple checkboxes.

EDIT: I'm willing to use a form alter hook if that is necessary. But if that's the case the same question applies.

UPDATE 2:
I attempted altering the form using the hook form alter method like so

        $form['my_select_field']['widget']['#options'] = [
            1 => 'New option 1',
            2 => 'New option 2',
        ];

And the new options do appear, but now when I submit the form I receive the error

  The value you selected is not a valid choice.

This is probably not a good use case for the core version of contact form based on entity forms. You have not only to take care of the validation in the form api, but also on the entity level. If you want to do this, here is a tutorial: https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

In contrast Webform provides a very flexible handling of select options. You can edit the options separately from the form in predefined options lists and then you can modify the predefined options dynamically, see these examples:

/**
 * Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
 */

function mymodule_webform_options_test_alter(array &$options, array &$element) {
  $options += [
    'four' => t('Four'),
    'five' => t('Five'),
    'six' => t('Six'),
  ];
}

/**
 * Implements hook_webform_options_alter().
 */
function mymodule_webform_options_alter(array &$options, array &$element, $id) {
  if ($id == 'custom') {
    $options = [
      'one' => t('One'),
      'two' => t('Two'),
      'three' => t('Three'),
    ];
  }
}


new content type with fields for username and password I have a requirement for creating a new content type and creating a new user through that.

The content type have fields like 'name', 'address' etc. but the client wants to have username and password field in that, so that the user could be created along with it.

I am a bit lost with this, any suggestions please?

Under Configuration->People->Account settings->Manage fields in the menu (admin/config/people/accounts/fields) you can add fields to the User entity, such as name and address.

Fields added to the User entity has a settings whether they should be displayed on user registration form.


Why would some backup schedules work and others not? I have several backup schedules set up:

Every 15 minutes (keeping 12)
Every 8 hours (keeping 9)
Daily Backup (keeping 31)
Weekly Backup (keeping 52)
Yearly Backup (keeping 5)

The perplexing problem is that some of them seem to be working and some not, even though they're all using the default profile, and they're all enabled, and they're all being saved to the scheduled backups directory.

Here are the backups that are appearing:

sitename-2012-11-10T18-10-05 Sat, 11/10/2012 - 18:10 25 min  311.12 KB
sitename-2012-11-10T18-03-58 Sat, 11/10/2012 - 18:03 31 min  305.58 KB
sitename-2012-11-10T17-48-49 Sat, 11/10/2012 - 17:48 46 min  308.19 KB
sitename-2012-11-10T16-43-06 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T16-43-05 Sat, 11/10/2012 - 16:43 1 hour  303.99 KB
sitename-2012-11-10T15-43-02 Sat, 11/10/2012 - 15:43 2 hours 304.01 KB
sitename-2012-11-10T14-43-00 Sat, 11/10/2012 - 14:43 3 hours 303.99 KB
sitename-2012-11-10T13-38-00 Sat, 11/10/2012 - 13:38 4 hours 303.95 KB
sitename-2012-11-10T12-33-00 Sat, 11/10/2012 - 12:33 6 hours 303.95 KB
sitename-2012-11-10T11-28-01 Sat, 11/10/2012 - 11:28 7 hours 303.94 KB
sitename-2012-11-10T10-23-00 Sat, 11/10/2012 - 10:23 8 hours 303.95 KB
sitename-2012-11-10T09-18-02 Sat, 11/10/2012 - 09:18 9 hours 303.94 KB

The fact that there are 12 (which is the number mentioned in one of the schedules) makes me think that perhaps the Backup & Restore module has a major bug: perhaps it assumes you'll only have one or two schedules, and my 5 overwhelmed it.

Is there any other reason for the behavior you're seeing?

By creating different destinations for each schedule, the problem goes away.

Apparently Backup & Migrate simply assumes each schedule has a separate destination (although the UI gives no hint that this would be the case, and in fact gives reason to expect that there's no problem with sharing a destination).

For instance, one of my schedules is set to keep 12 copies.  Rather than keeping track of which backups belong to which schedule, it merely deletes all but the last 12 backups in the directory.

At any rate, isolating each backup allows everything to work as expected.


What is the correct way to pass values from PHP code to javascript in Drupal 8? I'm not talking about the library. That part is covered fairly extensive. What I want to do is generate the javascript based on PHP. But I can't, for example, do this:

$o = '<script> $data = [';
for ($i = 0 ; $i < 10; $i++) {
    $o .= $i.', ';
}
$o .= ']; </script>';

$form['mainText'] = array (
        '#type' => 'markup',
        '#markup' => $o,
    );

return $form;

How am I supposed to do this correctly?

And if you are wondering, the reason I am doing this is because I want to generate javascript that is to be used to plot points on a graph.

There are a number of ways you could do this. I will you tell you one.

Create a controller class that has a method that is responsible for printing an array of numbers. Hit that endpoint via a javascript get request and do something with the returned data.

So you would create a routing file:

your_module.routing.yml

your_module.create_numbers:
 path: '/your_module/{numbers}'
 defaults:
   _controller: '\your_module\Controller\YourCustomControllerClass::createNumberArray'
 requirements:
   _permission: 'access content'

YourCustomControllerClass.php

<?php

namespace 'your_module\Controller';

class YourCustomControllerClass extends ControllerBase {

 /**
 * Return a JSON response based on the number param
 * @param $number integer The number passed into the route.
 * @returns JsonResponse
 */
 public function createNumberArray($number) {
   $numbers = [];
   for ($i = 0 ; $i < $number; $i++) {
     $numbers[] = $i;
   }
   return new JsonResponse($numbers);
 }

}

Now you can hit your route from Javascript. The cool thing about this is that your route can create dynamic arrays. If you notice in the routing file the numbers is in {}. That means it is dynamic and is passed in as an argument to the createNumbersArray method. It can then use it to create an array of any length.

your_module_graph.js

var numbers = 10;

// Note numbers can be set to whatever you want.
var jqxhr = $.get( "/your_module/" + numbers, function(data) {
  // data will be a JSON object containing an array of numbers.
  var parsedJson = JSON.parse(data);
  // Now do what you want with parsedJson. Build your graphs etc.
});

I haven't tested that but have done similar things a lot lately and I'm quite confident that if not that exact code, the approach in general will suit your needs. As mentioned earlier there is no one way to do this but with Symfony now a core part of Drupal 8 it really is built for doing stuff like this. That is, taking HTTP requests and returning data.

Hope that helps.


How do you change the order of uploaded videos? How can we change this page so new content added goes to the top, not the bottom?

http://www.liveops.com/resources/videos

When it's added to this page, it goes to the top:
http://www.liveops.com/resources

The listed videos are created using a view. It looks like the view is called Resources (or something similiar). Edit that view, and there should be a tab called 'block', where you can edit the block view. In there, under 'sort', choose 'nid' and set it to sort descending.


Where should modal content be placed? I would like to create modals for special offers and promotions. I know how to open them either using drupal.dialog or OpenModalDialogCommand. This works fine.

But what is the best place to put the content for the modal? I started adding it in the JS with .appendTo('body'). This works, but the modal content is complex and contains a lot of elements. I would like to know wheter there is a better place to put this modal content?

There are couple of things you could consider before deciding on a particular approach.

Is this data static?

If yes, then you could store data in memory and retrieve as needed. Performance should no longer be an issue as our js libraries are being loaded on demand and I am sure there are many other ways to optimize your code to work for your particular need.

Is this dynamic data stored in db?

You could expose your data using the built in REST solution. Once you have your data exposed. You could just use jQuery REST api's to retrive your data.

Hope this helps.


Custom node color from role How to create custom node background color from role id
e.g. admin - red
manager -green
auth user - blue, automatically?

Find examples (template.php)

function themename_preprocess_node($variables) {
  $account = user_load($variables['user']->uid);
  //$account = user_load(array('uid' => $node->uid));
  $user_roles = $account->roles;
  if (in_array('administrator', $user_roles)) {
    $my_class = 'user-admin';
  }
  elseif (in_array('authenticated user', $user_roles)) {
    $my_class = 'user-author';
  }
  elseif (in_array('test user remove', $user_roles)) {
    $my_class = 'user-power-author';
  }
  elseif (in_array('VIP', $user_roles)) {
    $my_class = 'vip-author';
  }
  if (isset($my_class)) {
    $variables['attributes_array']['class'][] = $my_class;
  }
}

This doesn't work

UPDATE From the code you've added it looks like you want to add the class based on the node author. You can use much the same principle:

function MYTHEME_preprocess_node(&$vars) {
  $account = user_load($vars['node']->uid);

  foreach ($account->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

Each node will have the role-rolename classes added to it (see original answer below).

ORIGINAL ANSWER

Quick and easy way:

function MYTHEME_preprocess_html(&$vars) {
  global $user;

  // Loop over the user's roles and add a class to the body class array.
  foreach ($user->roles as $role) {
    $vars['classes_array'][] = 'role-' . strtolower(str_replace(' ', '-', $role));
  }
}

That adds classes like role-administrator and role-authenticated-user (and any other roles the user has) to the <body> tag. From there you should be able to target things easily with CSS (e.g. body.role-manager{background:red}).

Remember to clear Drupal's caches after you've added the preprocess function, or the changes won't get picked up.


Drupal.behaviors.customCKEditorConfig I am trying to use the Disallowed Content configuration from Ckeditor.
https://docs.ckeditor.com/ckeditor4/latest/guide/dev_disallowed_content.html
I am using Drupal 8.5.3 Lightning 8.x-3 and the built in Ckeditor v4.8

I have placed this js in my theme and the js is loading when I am in page edit mode.

(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
        config.disallowedContent= 'div span';
      }
    }
  }
})(jQuery, Drupal);

But this is not working. I have tried with the Allowed HTML tags enabled and disabled. I got this information from these sources. http://drucafe.blogspot.com/2016/02/adding-custom-styles-to-ckeditor-in.html
and https://tutel.me/c/drupal/questions/183036/allow+empty+tags and Drupal 8 CKeditor behaves LTR in an RTL site.

I have tried the filter 3 different ways

editor.filter.disallow( 'span div' );
config.disallowedContent( 'span div' );
config.disallowedContent= 'div span';

This is working.

use Drupal\editor\Entity\Editor;

function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['disallowedContent'] =
'h1 h2 h3';
  }
}

This supersedes any allowed tags in the drupal GUI. But you must enable Allowed HTML tags enabled for this to work. I took the idea from this.drupal-8-ckeditor-behaves-ltr


drupal cache_set / cache_get expiration I have a function:

function _dc_election_races_get_articles($search_term)
{
    $search_url = 'http://feeds.example.com/vote_up/search.php?search='.rawurlencode($search_term);

    if ($cached = cache_get($search_url, 'cache'))
    {
        $results = $cached->data;
    }
    else
    {
        $results = json_decode(file_get_contents($search_url));
        cache_set($search_url, $results, 'cache', 60*60*3); //3 hours
    }

    return $results;
}

I basically want the cache to expire after 3 hours and re-fetch the data from the url. The  documentation on drupal made it seem like that it might not be removed from cache after 3 hours. Will cron cleanup caches?

If you start chasing the code in cache_get you will eventually end up in DrupalDatabaseCache::getMultiple.  If you look at the code, you will see a call to DrupalDatabaseCache::garbageCollection at the top.  This will handle cache expiration before cron runs.

As part of system_cron you will see that cache_clear_all get called with NULL as the first parameter which

  $cid: If set, the cache ID to delete. Otherwise, all cache entries that can expire are deleted.

This cleans up the cache tables every time cron runs.

The Drupal 6 plumbing is different for pruning the cache (start reading cache_get, but the end result is essentially the same.

TL;DR, your cache TTL will always be honored when you get values, it's just the cache table cleanup that may not happen exactly when the TTL is up.


Show latest changes in node "View" tab while using Content Moderation I had been trying a lot to display latest revision into view tab irrespective of its state, so if a node is in "Draft" state I still want it to be displayed under "View" Tab rather than "Latest version". I had tried using hook_ENTITY_TYPE_view, hook_ENTITY_TYPE_view_alter and even tried in template_preprocess_node hook but no luck. I was able to load latest revision but not able to set it using below code in preprocess,
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->getType() == 'news' && $variables['elements']['#view_mode'] = 'full') {
    $node = $variables['elements']['#node'];
    $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($node->id());
    $node = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
    $variables['elements']['#node']  = $node;
  }
}

Also tried with below code from a custom module,
function mymodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $node = Node::load($build['#node']->id());

  if ($entity->bundle() == 'article' && $view_mode = 'full') {
    $revision_ids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);
    $latest_rev_id  =  end($revision_ids);
    $node_new = node_revision_load($latest_rev_id);

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity->getEntityTypeId());
    $storage = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId());
    //$node = $storage->load($build['#node']->id());
    $build_new = $view_builder->view($node_new, $view_mode);
    //$output = render($build);

    $build['#node'] =  $build_new['#node'];
  }

}

Please if anyone can point me in a right direction it will be very helpful.
Thanks in advance.

Finally after spending huge amount of time on this, I am able to figure it out. Thanks to shawn-conn's answer here - Take over display of a content type node route
I have created a custom module and have added below files and code to achieve this,
First created mymodule.services.yml and added below code,
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Then created Routing folder under src.
Added file named RouteSubscriber.php with below code,
<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

Then added NodeRedirectController.php under src/Controller directory with below code,
<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Display latest revision content in view mode
    if ($node->bundle() === 'my_content_type' && $view_mode == 'full') {
      $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($node->id());
      $node_new = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
      return parent::view($node_new, $view_mode, $langcode);
    }
    // Otherwise, display as per Drupal's default behaviour
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

This might help someone.


Can i use route ID for Link template 'edit-form' for entity type? Can i use route ID for Link template 'edit-form' for entity type?

I'm following this tutorial

over there he use:

 *   links = {
 *     "edit-form" = "flower.edit",
 *     "delete-form" = "flower.delete"
 *   }

while flower.edit (i assume) is from below route.yml:

flower.edit:
  path: '/admin/structure/flowers/edit/{flower}'
  defaults:
    _entity_form: 'flower.edit'
    _title: 'Edit flower'
  requirements:
    _permission: 'administer site configuration'

but when i run, it throw me an error:

  Uncaught PHP Exception
  Drupal\Core\Entity\Exception\InvalidLinkTemplateException: "Link
  template 'edit-form' for entity type 'flower' must start with a
  leading slash, the current link template is
  'flower.edit'" at
  \core\lib\Drupal\Core\Entity\EntityTypeManager.php
  line 97

I know i can just use: /admin/structure/flowers/edit/{flower} to solve my problem.

but the question is: is it actually possible to use route (instead of path) in entity links config?

The tutorial is from 2014. Since then the link templates have changed from route to path. See change record:

Previous link template format

   links = {
     "canonical" = "entity.node.canonical",
     "edit-form" = "entity.node.edit_form",
     "delete-form" = "entity.node.delete_form",
   }

New link template format

After the change, the path is used.

   links = {
     "canonical" = "/node/{node}",
     "edit-form" = "/node/{node}/edit",
     "delete-form" = "/node/{node}/delete",
   }


3-rd decimal digit has disappeared in the output I created a field, attached it to the entity: coefficient_to_second_side. Type in the  database is decimal(10,3). Then I added a value: 1.001. When I select this field manually from the database, the value is correct. In the edit form it is correct:

But when I output the field on the entity page:

field_attach_prepare_view('event', array($entity->id => $entity), 'full');
entity_prepare_view('event', array($entity->id => $entity));
$entity->content += field_attach_view('event', $entity, 'full');

I get this:

Coefficient to second side:
1.00

The third digit has disappeared. How to fix?

If you type of "Coefficient" is float, you can change scale in display options for your Content Type. (admin/structure/types/YOUR_CT/manage/display). By default it's 2.


Drupal menu management seems lacking compared to WordPress: Am I missing anything? I'm trying to understand how to best add content links to menus. As far as I can tell, there are two limited ways:

In the content edit screen, click the "Provide a menu link" checkbox. Shortcoming: This will only add links to the main menu- you can't target other menus from the content edit interface?
In the menu edit screens, you can add links. Shortcoming:  You have to spell out the paths. Seems like it would be a lot easier if there was a content finder on this screen so that you could easily select the content, a la WordPress and every other CMS.

I'm coming from WordPress, which has a basic but robust menu management system. Is Drupal just lagging in this regard? Are there better ways of handling menu links?

On node edit page, upon checking "Provide a menu link" populates a select box with menus and theirs items which are associated with this content type. To include other menus you need to edit your content type.
You are right in this regard but there can be some module.


How to get view mode of a node? So my question is how I can get programmatically in preprocess node hook, the display mode of a node, for example, to check if view mode is a teaser or full?

The view mode is in the vars:

function MYMODULE_preprocess_node(&$vars) {
    $view_mode = $vars['view_mode'];
}

See template_preprocess_node() or node.html.twig for more info.


Overriding theme_links__main_menu() I have the following call in page.tpl.php.

 theme('links__main_menu',array(...));

How can I override the theme function that is being called from that code?

In a theme, you just declare the mytheme_links__main_menu() function in the template.php file. (Replace mytheme with the actual name of the theme.)

In a module, you declare the mymodule_links__main_menu() function, and implement hook_theme() to define the theme function. (Replace mymodule with the actual name of the module.)

The argument passed to the function are the same passed to theme_links().

$variables: An associative array containing:

links: An associative array of links to be themed. The key for each link is used as its CSS class. Each link should be itself an array, with the following elements:

title: The link text.
href: The link URL. If omitted, the 'title' is shown as a plain text item in the links list.
html: (optional) Whether or not 'title' is HTML. If set, the title will not be passed through check_plain().
attributes: (optional) Attributes for the anchor, or for the  tag used in its place if no 'href' is supplied. If element 'class' is included, it must be an array of one or more class names.

If the 'href' element is supplied, the entire link array is passed to l() as its $options parameter.

attributes: A keyed array of attributes for the UL containing the list of links.
heading: (optional) A heading to precede the links. May be an associative array or a string. If it's an array, it can have the following elements:

text: The heading text.
level: The heading level (e.g. 'h2', 'h3').
class: (optional) An array of the CSS classes for the heading.


About the "read more" link There are some related questions but they  are not very new, and  I'm not sure if I get it right. My question seems quite elementary.

Am I wrong in assuming the following basic fact? In the standard default installation of Drupal 7, all articles show a "read more" link, even if there is actually no more text to show. And there is no simple way of changing that stupid behaviour.

Please, tell me that I'm wrong.

No, and yes - sort of, in order.

The teaser system assumes that there will always be more to read so if you choose to show the teaser, by default it will always have a 'read more' link.

You can, however turn off the link entirely quite easily.  Copy node.tpl.php from your main theme into your custom theme directory and comment out this part:

<?php print render($content['links']); ?>

If you only want to show a read-more link when there is more to read, you almost certainly need to build a custom module for that.  There's lots of good documentation on how to do that, but we can probably help with the specifics here once you have a framework going if that's what you decide to do.

Note that if you only want to change the behaviour for a particular content type, put some logic around the line instead of commenting it out, like this:

<?php if ($node->type != 'article'): ?>
  <?php print render($content['links']); ?>
<?php endif; ?>


Can I map to Body Summary in Feeds Importer? I'm setting up a Feeds Importer to pull in content form a previous CMS. To keep things manageable I'm setting up MySQL exports saved to CSV files per Content Type. In a content type of News we're using the Body for full content display and the Body Teaser for the views listing.

In the source CSV file I have two separate columns: one for Body Content and another destined for Body Summary.

But in the Mapping for Node Processor Feed Importer, I don't have an option to place the teaser column in Body Summary.

Follow up:

I did the dummy field option. Once I had that, three lines of SQL saved the day.

UPDATE field_data_body f, field_data_field_news_teaser_summary_holdin ff
SET f.`body_summary` = ff.`field_news_teaser_summary_holdin_value`
WHERE  ff.`entity_id`= f.`entity_id` AND f.`revision_id`= ff.`revision_id`

Couple of ways of doing this using a dummy field. Create a dummy text field on the content type you are importing to. Then you could:

a. Use rules to move the dummy field into the body summary.

or

b. (preferred) Use the feeds presave hook in your own module to set the summary AND set the dummy field blank.

/**
 * Invoked before a feed item is saved.
 *
 * @param $source
 *  FeedsSource object that describes the source that is being imported.
 * @param $entity
 *   The entity object.
 * @param $item
 *   The parser result for this entity.
 */
function [YOUR_MODULE_NAME]_feeds_presave(FeedsSource $source, $entity, $item) {
  if ($entity->feeds_item->entity_type == 'node' && isset($entity->field_temp_summary['und'][0]['value'])) {
    $entity->body['und'][0]['summary'] = $entity->field_temp_summary['und'][0]['value'];
    unset($entity->field_temp_summary);
  }
}


How to add Google adsense Adlinks at the middle of the post Hello I need to put adsense adlinks at the middle of the content or between paragraphs but I am not getting any modules to do that.Currently i use Content Injector to display image ads at top and bottom of the post.

2 Methods:

Create two body fields, display adsense between the output of the two.
Output the block for the adsense code (I assume it is in a block) via PHP in your body.

<?php
$block = module_invoke('block', 'block_view', 26);
print render($block);
?>


How to show fivestar votes in views as number instead of percentage? I have a view which show a content with a Fivestar field (votes).
The problem is that the field is shown as the percentage of votes, not like the stars, or the number (in fact I need to show the number instead of percentage).

I mean, my Fivestar field has 10 stars. Well then if, for example, a node has 7 stars, rather than see the 7 stars or the number of stars (7) is shown the percentage, 70.

What I have to do to show the number (in my example "7")?

I found a solution for my question: Hide your vote field in views ("Exclude from display"); then, add a Global field, the "global math expression", and in this field add a replacement token of your exclude field, in my case [value]. Finally add the mathematical expression to divide by 10 the number: [value]/10.
Apply and save the view.


Catch the English name of a translated taxonomy term (token) I'm building up a multilingual website (Drupal 7) with Locale and Content translation modules enabled for nodes. The node category is managed thru a content_area field (taxonomy term thru Entity Reference module), which is translated with Entity Translation and Title modules in order to have a translated path in URL (using Pathauto module). Everything goes as expected, the content_area is translated in URL, in the breadcrumb and in the tags area.

As each node manages more images, shared among languages, we've built a file folders structure which comply with paths (not equal but similar) in order to keep a clean images structure, using File (Field) Paths module.
Problems arise: if the content_area field (taxonomy term) is untranslated (i.e. English), we have only one folder for images of all languages (as expected), but if we translate the content_area field we get a translated folder keeping images, as we do not want.

When setting up File (Field) Paths for images field in File path, we expected to find a token related to the untranslated/translated [node:field_content_area:name], with no luck. Even [node:source:field_content_area] cannot work and do not work, as we cannot know if the editor building up the node content will begin ('source') from English or from another language.

I hope I have been clear, it is my first post.
Thanks in advance

Decipher's blog suggested the answer: I initially created a custom module to define a custom token to use in FileField Paths, and then I installed Custom Tokens module, and created same token as before.

Both methods worked, and at the end I'll use second method (installing Custom Tokens module, without my custom module), as it will be easier to create other tokens when needed.

Method 1:

/**
 * Implements hook_token_info().
 * gw_content_area_en is the token used as [node:gw_content_area_en]
 */
function MODULENAME_token_info() {

    $info['tokens']['node']['gw_content_area_en'] = array(
      'name' => t('Gw Content Area EN'),
      'description' => t('English version of field_gw_content_area'),
    );

    // Return associative array of tokens & token types
    return $info;

}

/**
 * Implements hook_tokens().
 */
function MODULENAME_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  // Check if token type is node
  if($type == 'node'){
    foreach ($tokens as $name => $original) {
      switch ($name) {
        // Check token is gw_content_area_en
        case 'gw_content_area_en':
          $tid = $data['node']->field_gw_content_area[LANGUAGE_NONE][0]['target_id'];
          $term = taxonomy_term_load($tid);
          $replacements[$original] = $term->name_original;
          break;
      }
    }
  }
  return $replacements;
}

Method 2:

Install Custom Tokens module;
Create a new token with following settings:

Token name: Gw Content Area EN
Token description: English version of field_gw_content_area
Token type: Nodes
Content:

$tid = $data['node']->field_gw_content_area[LANGUAGE_NONE][0]['target_id'];

$term = taxonomy_term_load($tid);

return $term->name_original;

New custom token used to set FileField Path.

Note: i18n_taxonomy module disabled.


modal window "loading" not loading in SCALD I'm working on a site using SCALD – and for some reason the modal media upload window does not work anymore. It's stuck with the status "loading…" but not going anywhere.

I first had it running like a charm – then I 'just' wanted to add multi-language support to the website adding i18n… Then when I checked again on SCALD this is all I get:

Firebug console is showing the following two messages:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help xhr.spec.whatwg.org ...A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertB…" (jquery.js?v=1.4.4 line 139)

and

uncaught exception: The editor instance "edit-body-und-0-value" is already attached to the provided element.

Firebug network: "POST ajax 200 OK"

So for what I can see from other modules ajax is up and running. Checking on other forum questions here on drupal-stackexange concerning modal window problems didn't help yet – so I just hope somebody has some pointers that would direct me in some direction… ThankYou!

–EDIT-
manual upload (atom/add/image) works and also using the SCALD library incl. drag'n'drop works fine. Just opening the modal dialogue either through "add" or "edit" form the SCALD sidebar does not load.

PS: not using the jQuery update module

Fixed it: the problem was that after going through the SCALD installation process the CKEditor was activated and the plugins declared in two locations:

under WYSIWYG Profiles
under CKEditor Profiles

This also corresponds with the error message I had in FF console:

uncaught exception: The editor instance "edit-body-und-0-value" is already attached to the provided element.

I simply deleted the WYSIWYG Profile and the problem was gone – modal window loading as it should. The detailled documentation of the process finding the error can be found over here: https://www.drupal.org/node/2454845#comment-9749453


Why does loadMultiple load 1000 nodes 9.2 times faster than loading each node one by one? I have always known that loading multiple nodes at the same time is faster than loading them one by one.

What I wasn't aware of, is the huge performance difference between the two ways of loading nodes.

I made an example to see the difference. Here's my result:

Load 1000 nodes one by one:

$start_time = microtime(TRUE);
foreach (range(1, 1000) as $nid) {
  $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
  if ($node) {
    print_r($node->id());
  }
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);

Execution time: 10.7266 seconds.

Load 1000 nodes at the same time:

$start_time = microtime(TRUE);
$nids = [];
foreach (range(1, 1000) as $nid) {
  $nids[] = $nid;
}

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

foreach ($nodes as $node) {
  if ($node) {
    print_r($node->id());
  }
}
$end_time = microtime(TRUE);
print_r($end_time - $start_time);

Execution time: 1.1664 second.

How can loadMultiple be 9.2 times faster than loading the nodes one by one?

Is it the connection between Drupal and the database? What other factors are slowing down the process when loading the nodes one by one?

I have cleared the cache after every request to avoid the loaded nodes being cached.

I used the microtime function to calculate the exact execution times.

It's likely that when you are loading individual nodes, you are loading the entity type manager, then for each node retrieve the storage, do a query to get the node data, and build the node. With the multiple process, some of the DB queries are likely combined, and the processing will be in a batch rather than having to run through the code multiple times.


How to add a tpl file to a block from a custom module I have a custom module that build a block. I'm trying to add a tpl file, but I don't get nothing.
This is my code:

<?php
/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function tados2_block_info() {
  $blocks = array();

  $blocks['block_with_tpl'] = array(
    // info: The name of the block.
    'info' => t('Tados2 example: block with tpl'),
    'status' => TRUE,
  );

  return $blocks;
}
/**
 * Implements hook_block_view().
 *
 * This hook generates the contents of the blocks themselves.
 */
function tados2_block_view($delta = '') {
  switch ($delta) {
    case'block_with_tpl':
      // The subject is displayed at the top of the block. Note that it
      // should be passed through t() for translation. The title configured
      // for the block using Drupal UI supercedes this one.
      $block['subject'] = t('Tados2 block with tpl');
      // The content of the block is typically generated by calling a custom
      // function.
      $block['content'] = t('Hola mundo');//_tados2_block_with_tpl_contents();
    break;
  }
  return $block;
}
?>

I'm trying to move the content to a tpl.php file.

This what I'm trying:

<?php
/**
 *
 * Implementen hook_theme
 *
 */
function tados2_theme(){
  return array(
    'tados2_block' => array(
      //'render element' => 'elements',
      'template' => 'tados2_block',
      'variables' => array('title' => NULL, 'content' => NULL),
    ),
  );
}
/**
 * preprocess function
 *
 */
function template_preprocess_tados2_block(&$variables) {
  dpm($variables);
}
?>

You have to call your theming function:

$block['content'] = theme('tados2_block', array('title' => 'foo', 'content' => 'bar'));


Local tasks not correctly limited to base_route I want to create a customized media library for my editors, with a tab navigation similar to the tabs on core's admin/content view. It basically works, but I also want to add a tab leading to a specific "media" taxonomy vocabulary used by my media entities. As soon as I add the taxonomy tab to my YML file, the base_route filter no longer works.

Screenshot with correct behaviour on view pages:

Screenshot with unwanted tabs on taxonomy page:

This is my custom modules' links.task.yml.

# a common view page for all media types
wt_media.media_list:
  route_name: view.medialibrary.medialibrary
  base_route: view.medialibrary
  title: 'All media types'
# a view page only for images
wt_media.image_list:
  route_name: view.medialibrary.imagelibrary
  base_route: view.medialibrary
  title: Images
# a view page only for videos
wt_media.video_list:
  route_name: view.medialibrary.videolibrary
  base_route: view.medialibrary
  title: Videos
# a view page only for documents/files
wt_media.file_list:
  route_name: view.medialibrary.filelibrary
  base_route: view.medialibrary
  title: Documents
# as soon as I activate the following entry, all the tabs are shown
# on every taxonomy overview page, this is not wanted
wt_media.manage_taxonomy:
  route_name: entity.taxonomy_vocabulary.overview_form
  route_parameters:
    taxonomy_vocabulary: media
  base_route: view.medialibrary
  title: Manage Categories

How can I prevent my custom tabs from appearing on the taxonomy overview pages?

You can use hook_menu_local_tasks_alter() to see what all elements are added and can remove elements based on any conditions you like.


How to display only one block in custom page using tpl? How to show only block and hide all other menus,blocks etc.,
This is my code

function example_menu() {
  $items['appointcal'] = array(
    'page callback' => 'example_show',
    'access callback' => TRUE,
     'type' => MENU_CALLBACK,
   );
     return $items;
}

function example_show() {
  return theme('example_cal');
}

function example_theme() {
  return array(
    'example_cal' => array(
      'render element' => 'elements',
      'template' => 'templates/examplecal'
    )
  );
}

My examplecal.tpl.php is

<div>
  <?php
    $block = module_invoke('views', 'block_view', 'example-block');
    print render($block['content']);
  ?>
</div>

There is need to show only region that is in red color and hide all other regions.

You can use Context module for this purpose. It provides the same functionality as you require.

Note:  If you don't want to use any extra module, then it can also be done simply through block configuration setting. There are three options to control the block visibility.


Why source is empty object for hook_feeds_after_parse in dpm()? Working on a module that modifies some CSV files before it's processed
by feeds_import. I use the hook_feeds_after_parse($source, $result).
The processing and $result is ok.

But the object $source of type FeedSource is empty!
So how can we know which source is being handled?

Why is it empty?

if $source == x: // do that.

is not possible.

Any solution?

Ooops ok,
dpm($source) does not show protected class properties if you don't specify which protected variable you want to display.
You have to point the property you want to display.

After some research in FeedsConfigurable.inc and DB
dpm($source->id) is the unique id (string!) I search for.

/n


How do I add role permissions to custom module I have a custom module in Drupal 8 and I have created a role called editor.
How do use .permissions.yml in my module to get it to display on the editor's role?

Create a file my_module.permissions.yml and add

my permission:
  title: 'This is my custom permission'
  description: 'A custom permission for your.'

Then use your permission in your my_module.routing.yml:

example.name:
  path: '/example/{name}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'my permission'

Now you can configure your custom permission on admin/people/permissions