how can I have a body with more than 64 Kb of data in it? I've noticed that when I create a node with too much data in the body field subsequent edits will not save. Or rather, the save goes ahead and I am taken back to viewing the node, but the content hasn't changed.

After extensive trial and error I was able to determine that any save which had a body length of less than 64 Kb saved fine but anything more than that would not save.

What is the cause of this and is there any way to get around it?

The reason of the problem is a regular expression that causes PCRE to reach the limit set for pcre.backtrack_limit or pcre.recursion_limit.
There was an issue report on drupal.org about truncated body content; the length of the text that is possible to enter before it gets truncated depends from the characters used (English text can be longer than a text containing all Unicode characters), and from the values set for pcre.backtrack_limit and pcre.recursion_limit.
The issue report I am speaking of is Document possible preg memory issues. Gerhard Killesreiter's comment is the following one:

This issue [the body content being truncated] is due to the limits of the perl regular expressions that we use to validate that you posted valid UTF8.
If you increase the limits in your settings.php file you will see the text.

ini_set('pcre.backtrack_limit', 200000);
ini_set('pcre.recursion_limit', 200000);

You will need to experiment which values work for you.

node_schema() defines the body field of the node_revisions table as "big text". This means that with MySQL the maximum length of a node body is 4 GB, and with PostgreSQL there isn't (theoretically) any limit; in both the cases, the limit is not the 64KB you are observing.
The default.settings.php file contains the following comment:
/**
 * If you encounter a situation where users post a large amount of text, and
 * the result is stripped out upon viewing but can still be edited, Drupal's
 * output filter may not have sufficient memory to process it.  If you
 * experience this issue, you may wish to uncomment the following two lines
 * and increase the limits of these variables.  For more information, see
 * http://php.net/manual/en/pcre.configuration.php.
 */
# ini_set('pcre.backtrack_limit', 200000);
# ini_set('pcre.recursion_limit', 200000);


Using hook_form_alter to hide a field in a view exposed filter I am using hook_form_alter to hide a field in a view exposed filter.

function cars_form_alter(&$form, &$form_state, $form_id) {
if($form_id == "views_exposed_form"){
    $form['field_price__1']['#type'] = 'hidden';
  }
}

My questions are :

It only works if use $form_id == "views_exposed_form". But I don't want for all views only for my specific one which has form_id=views_exposed_form_car-results_panel_pane_3 ,but it doesn't work if I use the specific form id
Using the above snippet,I can hide the field but not its Label.How can I hide also the label?

One possible way to alter the exposed filter for specific view is the following:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
        // Check if the form contains exposed filter form element.
    if ($form_id == 'views_exposed_form') {
        // Here you can define the check for specific view so that it doesnt apply to all views.
        $view = $form_state['view'];
        // If you have multiple display in view than you can add a check for specific display
        // as '$view->current_display == 'DISPLAY_NAME' in the below if condition with '&&'.
        if ($view->name === 'MY_VIEW_MACHINE_NAME') {
            // Add your code for specific form.
        }
    }
}

And for hiding the label of particular element, check #title_display: Indicates how the label should be rendered. The label includes the #title and the required marker, if #required. If the #title is empty but the field is #required, the label will contain only the required marker.

  '#title_display' => 'invisible'

UPDATE:

Also you may try using hook_form_views_exposed_form_alter as below:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  // To check the form id of your view.
  print_r($form_id);
}


Library dependancies not loading The dependency core/jquery.ui is not loading into the theme. jQuery is loaded as it is included by default but jquery.ui refuses to load.

#theme.libraries.yml
popup:
  version: 1.x
  js:
    js/popup.js: {}
  dependancies:
    - core/jquery
    - core/jquery.ui

#theme.info.yml

libraries:
  - theme/popup

I have also tried attaching the library using the code below, but still no luck.

// theme.theme
function theme_page_attachments_alter(&$page) {
  $route = \Drupal::routeMatch()->getRouteObject();
  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);
  if(!$is_admin) {
    $page['#attached']['library'][] = 'theme/popup';
  }
}

I have seen multiple references to core/jquery.ui throughout drupals files. So am a little confused.

I feel like i must be missing something obvious.

jQuery UI will load in fine if you are logged in, but again i believe this is included by default for admin users.

For those that are trying to use the built in jquery ui you must include -core/drupal.dialog as a dependency in your theme.libraries.yml for it to work


How to make the "Height" of Views Slideshow Fully responsive? I'm working on a slideshow on Drupal 7 with Views Slideshow. The only issue I have right now is to make the Frame "Height"(not the image) responsive when resizing the browser. I found many articles, questions and answers about how to make Views Slideshow responsive, but none of them work properly. I believe the "Frame" is causing this.

These articles I found does not really fix the height of Views Slideshow. Maybe I missing something.
- Make views slideshow responsive - remove inline styles
- Can't remove the height/width of the slide container

----- updated for @Patrick Ryan

I got some error from google chrome web browser after adding these js

----- updated on Aug. 20, 2014 @ 9:46am
I found the following script also fix the height. Its from drupal.org issue views Slideshow for Responsive design on #26

$(window).resize(function(){
  $('.views_slideshow_cycle_main').each(function(){
    var cycleMain = $(this);
    var img_width = 0,
        img_height = 0;
    var clearCSS = {width: "auto", height: "auto"};
    var cycle = cycleMain.children('.views-slideshow-cycle-main-frame');
    cycleElements = cycle.data("cycle.opts");
    cycle.css(clearCSS);
    cycleMain.find('.views-slideshow-cycle-main-frame-row').each(function(i){
      $(this).css(clearCSS);
      var tmp_img_width = $(this).width();
      var tmp_img_height = $(this).height();
      if(tmp_img_width > img_width)
        img_width = tmp_img_width;
      if(tmp_img_height > img_height)
        img_height = tmp_img_height;
      cycleElements.elements[i].cycleW = tmp_img_width;
      cycleElements.elements[i].cycleH = tmp_img_height;
      $(this).css({width: tmp_img_width, height: tmp_img_height});
    });
    cycleMain.height(img_height);
    cycle.css({width: img_width, height: img_height});
    cycle.data("cycle.opts.elements", cycleElements);
  });
});

I normally take care of the height with javascript.  First I make sure that I am handling the width properly with CSS:

.views-slideshow-cycle-main-frame,
.views-slideshow-cycle-main-frame-row,
.views-slideshow-cycle-main-frame-row img {
  width: 100% !important;
}

Then I create a function that sets the height.  This will take whatever container your slideshow is in as a parameter and find the slideshow within it.

/* Slideshow resize function */
Drupal.theme.prototype.slideshowResizer = function (target){
  var slideheight = 0;
  $(target + ' .views-slideshow-cycle-main-frame-row').each(function(){
    slideheight = $(this).find('.views-slideshow-cycle-main-frame-row-item').innerHeight();
    if(slideheight != 0){
      $(target + ' .views-slideshow-cycle-main-frame').css('height',slideheight+'px');
      $(target + ' .views-slideshow-cycle-main-frame-row').css('height',slideheight+'px');
      return false;
    }
  });
};

And finally I call the function on the window resize event:

Drupal.behaviors.slideshowResize = {
  attach: function (context, settings) {
    $('.your-slideshow-container', context).once('processed', function () {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });

    $(window).resize( function() {
      Drupal.theme('slideshowResizer', '.your-slideshow-container');
    });
  }
};

Also, make sure your base img tag has height: auto;


How many times is a view used Recently i'been assigned to a drupal project already in development. I need to change a view but the site is quite complex. Is there a way to know how many times is a view being used?

Thank you all

Views Usage Audit

From project page:

  This module can help you refactor a Drupal codebase by locating redundant views and displays or simply improving your understanding of what views are used where.
  It achieves this by logging where views get executed. You can then run reports from drush or through the UI


Grant/refuse access permission on the fly Is there some kind of hook or callback that will allow me to do some fancy checks before granting or refusing permission?

I have an Application content type which references another content type that contains a list of users that are allowed to view it. I need to load up the list of users and check to see if the current user is in the list.

Yes. Look into this topic: Node access rights.

That's what you should do if you want the permissions to be respected in all contexts, including DB queries (except your own if you don't use db_rewrite_sql).

Another potential solution, assuming that you can get your existing setup to work with it, is Content Access. It can do per-user access control. The way I would do this is implementing hook_nodeapi's update operation and then programmatically configuring Content Access to match the list of users. Basically, the list of users would become a simplified admin interface in this approach. You would of course have to look at how Content Access manages this specifically (I know it uses the ACL module).

This approach should have all the benefits of the previous one, i.e. low-level security.

The poor man's way to do this would be to use hook_menu_alter and change access callback/access arguments to your own, where you'd load the nodes and do your fancy checks. This would only help on viewing, though, not on data retrieval. But it is probably easier than the other two ways if you don't need a perfect solution.


Allow to change site logo without giving too many privileges I want to allow a certain role to change the site logo, but I don't want to give the 'administer site configuration' permission to that role.

At first I was hiding some form elements from the theme settings forms using hook_form_alter() and $element['#access'] = FALSE, leaving only the options related to uploading a new site logo; after that I noticed the user would need the 'administer site configuration' permission to access that form.

Do you have any idea?

You could implement hook_menu_alter() to change the permission associated with that page, and use other permissions to decide which form fields should be visible to the currently logged in user. In this case, instead of using $element['#access'] = FALSE, you should use $element['#access'] = user_access('your custom module permission').
In the case you are only interested to allow some users to change the site logo, then you can use your custom permission for the page containing that settings form, and then use the "administer site configuration" permission for the form fields only the site administrators should see ($element['#access'] = user_access('administer site configuration')).

function mymodule_menu_alter(&$items) {
  if (isset($items[$menu_path]) {
    // Use the following line if the access callback already used is not user_access().
    $items[$menu_path]['access callback'] = 'user_access';
    $items[$menu_path]['access arguments'] = array('your custom module permission');
  }
}

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == $form_to_alter) {
    $form[$element_id]['#access'] = user_access('administer site configuration');
  }
}


Panels layout with sidebar next to 3 pane grid I'm using Panels 3.2 on a fresh install of Drupal 7. I want to create a custom layout that I can use and manage via Panels, and the flexible editor is great, but not quite sufficient for the layout I want (as far as I can tell).

Currently I have a simple 3-column layout, but what I want to achieve is this:

I did take a look at Panels Extra Layouts, but I'm not sure if that would cater for this.

EDIT: to clarify, I don't have a problem creating a layout like this with straight up HTML and CSS. I'm just looking for a way of introducing another region above the first two columns of a 3 column layout - something which the flexible layout editor doesn't seem to allow. Sorry for any confusion.

Just take a peek at the current layouts you have, and you can probably figure out how to add new regions, it's fairly straightforward.

There's also a tutorial here: http://drupal.org/node/495654


Calculate percentage based on two fields, one of which is an embedded view I am trying to calculate a percentage based on two fields in my table. I am using views and I have a table which has 2 fields, one field is an aggregation of of all records and the other is an embedded view which has another number - I used the Views Field View module for embedding the field.

How can i get a percentage between these 2 fields. The Math Expression field is not supported in drupal 8 and I have also tried the views_simple_math_field and it didn't help me at all. Please help!

i tried in output code:

<?php
echo count($row->field_a) + count($row->field_a) ;
?>

and the result is:

I modified the view, and used aggregation.

I modified the field a:

I modified the field b:

I modified the field php:

And the code:

And result:


View scanning wrong template file I've inherited a Drupal 7 site that's having an issue. The field "date" appears on the test site, but not on prod, and the field "title" is linked on test, but not prod. On both sites, the "date" field shows up in views "preview."

Update: I've figured out as much as the view is scanning the wrong template file. There is a file with an identical name learning/views-view-fields--block.tpl that is being used in the view instead of news/views-view-field--block.

How does this happen and how can it be fixed (I'm new to Drupal view templates, so I apologize if there's a simple solution).

I fixed this by going into structure->views->the-specific-view-causing-the-issue(News)->advanced->theme information, and found a more specific name for "Row style output," in this case views-view-fields--news--block.tpl.php.


How to hook payment created on commerce 2 I use commerce to create a bakery. Unfortunately, there is no module to pay by check or cash. So I use the payment example "manual".
I need to debit the user account when a payment is entered (a "balance" field has been created on the user account).
Is there a hook when a payment is created so that I can do this operation on the user entity?

One option would be to use hook_entity_create() but I would rather react on Order transition event, such as commerce_order.place.post_transition which is triggered when Order reaches Completed state.


Views Infinite Scroll doesn't hide pager I need infinite scrolling for a View.  I installed Views Infinite Scroll, and it will work if I set jQuery Update to version 1.8, but when it loads the next page, it leaves the pager in plain site.  I don't want the pager to display, and I can't figure out how to disable it.  Also, when it's loading the next page of content, it displays that ugly progress GIF.  Is there a way to hide that as well, and just get a nice scroll functionality, like on Twitter?

I don't know if this is causing an issue, but my View results are nodes, using Display Suite view mode.  In these nodes, I have another View that displays product pricing and other fields, using Commerce Add To Cart Extras.  Would this other View (in each node) conflict with the Views Infinite Scroll module for my main View?

If I have to do this through code, what is the best route?  Should I use the Views Ajax API somehow, or is there another JS or jQuery library that I can integrate with Views?

I tried to use the Views Load More with Wayports, but I couldn't get that to work either.  The best I got was the View to just display the "Load More" link, which I don't want.

To hide the pager, I just set the display: none in the CSS.


downgrade drupal 7 to drupal 6 I need to downgrade Drupal 7 installation to Drupal 6, how should I handle it? I have pretty much blank Drupal 7 install (w/ bunch of users, which I really don't want to loose), but the module that I need only works on Drupal 6.

* UPDATE *

following is a module that I'd like to use w/ Drupal: Clickbank IPN | drupal.org and as you see developer(s) don't have anything other then d6 release.

Is there a way to export users from D7 and import then to D6?

You wont be able to find any easy solution to downgrade from 7 to 6. The best option is to either find an alternative to the module that is not available for D7 or check the issue queue of that module you might find the dev release of the module. OR If only users are important to you then just export the users from D7 and import them on D6.


Twig: "for" does not display variable content without first displaying all variable content I have found a very strange behavior.

My variable related_nodes contains a list of nodes. How it is displayed by Kint:

related_nodes array(10)
'#sorted' => boolTRUE
'#pre_render' => array(1)
'8' => array(5)
'10' => array(5)
'11' => array(5)
'12' => array(5)
'13' => array(5)
'14' => array(5)
'15' => array(5)
'16' => array(5)

If I first display the content the variable {{ related_nodes }}, it displays this all related nodes and then them one by one in Divs (with loop index before):

{{ related_nodes }}
            {% for rel_node in related_nodes[2:] %}

{{ loop.index }} - {{ rel_node }}

            {% endfor %}

But when I remove the first display of the variable: {{ related_nodes }}, it does not display related nodes one by one in Divs (it displays only the loop indexes):

        `{% for rel_node in related_nodes[2:] %}

{{ loop.index }} - {{ rel_node }}

        {% endfor %} `

I also have 8 errors like this:
"   Notice: Undefined index: title in template_preprocess_node() (line 616 of C:\Users\Oksana\Documents\sites\drupal2\core\modules\node\node.module)" when the {{ related_nodes }} is removed.

When I removed the slice [2:], it did not help.

Is there any need to pre-load a varible before I can iterate in it with the twig 'for'? Or what can be a reason for such behavior?

I need to remove this {{ related_nodes }} because it displays all vertically without formating in columns.

Drupal version: 8.5.3.

In Twig you could re-use the pre render callback for each single node, see Cycle comments on field--comment.html.twig, but since you are responsible for the content of the twig variable you can do this when preparing the variable by replacing viewMultiple() with multiple view():

foreach ($related_nodes as $node) {
  $variables['related_nodes'][] = \Drupal::entityTypeManager()
    ->getViewBuilder('node')
    ->view($node, $view_mode, $current_node->language()->getId());
}

Then in Twig you can use a normal loop:

        {% for rel_node in related_nodes %}

{{ loop.index }} - {{ rel_node }}

        {% endfor %}


How to use the Rules module to publish all nodes authored by a user when the user's role changes? I'm using the SMSFramework module for my user validation, I have a rule which changes user role to "Confirmed" when the user approves his cellphone number.

That means then, every node that the user have must become Published. I have no idea how to implement this with just using rules!

Since my event is: After updating an exisiting account it means I have no access to the users's nodes! that I can get some actions fired on them!

I'd really appreciate your help.

Yes this can be done with the Rules module. Here is a summary of what you'll need to get it to work:

Keep track of all node IDs of a user that still need to be published later on (after the user approves the cellphone number). For this add an entity reference to the user's profile (multiple values allowed). And each time such unpublished node get's saved you need to add the reference to that node as an extra value in this entity reference field (= Rule 1). So basically this is the "queue" of nodes for a user that need "post processing" after the user approves the cellphone number. It is will serve as your entry point starting from the user's id to "access (find) the exact node ids again later on".
Create a rules component (= Rule 2, though of type "component") with parameter just a "node id". All this Rules component has to do, is to "publish" the node indicated in the parameter. But you can add any Rules "Conditions" also if you'd need any (already now or later on if requirements change). E.g: check that the node is not published yet, only for specific content types or user roles, etc.
Create a rule (= Rule 3) containing a Loop that should be triggered after the user approves the cellphone number. The goal of this rule is to loop over each of the nodes in the reference field from Step 1, and in each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 2 (and which uses the node id as a parameter). By using a Rules Component, you'll be able to add any "Conditions" you might need inside the "Loop".

Video tutorials

If you're not familiar (enough/yet) with using Loops in rules, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 2 and step 3, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

You are creating an entity reference to nodes also, but from a user (not a node).
You only need the first parameter (= Node to link to) in your Rules component (you don't need the 2nd parameter).


Which method has better performance I want to update some term id on some node (let suppose 1000 node),My changes is convert all news node with category(term_id) = 3040 to category(term_id)=5).

I know I can do it with several methods( use views bulk operation, write batch running etc, .... ) but my question is about performance of below approaches

Approach based on old method ( node_save)

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'news')
        ->propertyCondition('status', 1)
        ->fieldCondition('field_category', 'tid', array('3040'));
$result = $query->execute();
$nids= array_keys($result['node']);
//ym($nids);

$nodes= node_load_multiple($nids);
foreach ($nodes as $node){
    foreach($node->field_category['und'] as $i=>$item){
       if($item['tid']==3040){
            $node->field_category['und'][$i]['tid']=5;
            node_save($node);
        }
    }

}

Approach based on entity wrapper method

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
            ->entityCondition('bundle', 'news')
            ->propertyCondition('status', 1)
            ->fieldCondition('field_category', 'tid', array('3040'));
    $result = $query->execute();
foreach($result['node'] as $nid => $stub_node) {
  // Load the full node and wrap it with entity_metadata_wrapper().
  $node = node_load($nid);
  $wrapped_node = entity_metadata_wrapper("node", $node);
  if ($wrapped_node->field_category->value()->tid == 3040) {
    $wrapped_node->field_category->tid->set(5);
    $wrapped_node->save();
  }

in first approach we have one node_load and one node_save but in second approach we have one node_load one creating entity metawrapper creation and one entity wrapper save.
I want to know which method has better performance?
let suppose we have the same situation for both 2 method, I just want somebody tell me ( take a benchmark on one node and  in bulk ( multi node) mode and tell me the performance of both that which one of this method is faster in the same situation.
please provide your answer with facts or benchmark testing result

This is essentially impossible to answer.  You have one part of your question, wrong

Your first method uses a single node_load_multiple() with multiple node_save
Your second answer uses multiple node_load() with multiple Entity API calls

My gut tells me the first will be quicker, as a single node_load_multiple() is typically more performant than multiple node_load() calls, given the same set of nodes.  You also aren't creating the the metadata wrapper objects.

However, you need to do the benchmarking on your system.  There may be a difference, but it may be small enough to not make a real imapact.  Some things that make cross-system benchmarks unreliable

entitycache can have a tremendous impact on a system, especially if you use a non-SQL backend for it
the number of fields on your node can effect how long the wrapper creation process takes, and also how long the node_save() takes
APC and/or OpCache usage and configuration
PHP version
MySQL configuration (or whatever database backend you are using), including some of the Drupal-specific tricks that can improve performance
The number of hook_node_update() instances that fire for each save


Custom block assigned to new region invalid I had created a new region to my theme "buynow" and my theme.info contains the following line

regions[buynow] = Buynow

In my custom module i had created a custom block in which i assigned the block to the region buynow

function buynow_block_info() {
  $blocks = array();
  $blocks['buynow'] = array(
    'info' => t('Shoretel Buynow'),
    'status' => 1,
    'region' => 'buynow',
  );
  return $blocks;
}

When i try to enable the module, Iam getting The block was assigned to the invalid region and the block was disabled

How can i set my block to the new region.

You can use this code:

function formalter_block_info() {

 $blocks = array();

 $blocks['buynow'] = array(

 'info' => t('Shoretel Buynow'),

 'status' => 1, // This will enable your block by default, and set it to region given in 'region' option

 'region' => 'buynow', // put <machine-name of your region> in place of footer
 'visibility' => BLOCK_VISIBILITY_NOTLISTED,

 'weight' => 2,

 );
return $blocks;
}


How to show an image in an image style I'm creating a custom twig for my node 1, as node--1.twig.html.

In this I'm showing the image uploaded in the node as

<div class="diversity-image">
    {{ set image = content.field_main_image|merge({'#style_name': 'header_image'}) }}
    {{ image }}
</div>

But it is not giving me the image of that image style, header_image.

How do I do that in twig?

In twig you can only merge the top level of an array. So you need two steps, first get the image from the content array and then overwrite #image_style.

node.html.twig

{% set image = content.field_image.0 %}
{% set image = image|merge({'#image_style': 'thumbnail'}) %}

You can now display the image a second time in the changed image style:

{{ image }}


Alter contextual links I'm trying to alter custom blocks contextual menu.
In particular I need to remove "Configure block" and "Delete".
Is there any way to achieve this?

The correct way to alter contextual links is to use hook_contextual_links_alter.

In your case, it should look something like:

function my_module_contextual_links_alter(array &$links, $group, array $route_parameters) {
  if ($group === 'block') {
    // Hide Configure Block option.
    unset($links['entity.block.edit_form']);
  }
}

The contextual links are heavily cached in the browser, therefore you need to make sure that the browser session cache is cleared - window.sessionStorage.clear(); - source.


I have muliple webforms in my site, but want to disable all webforms after user makes a submission I'm stuck. I have a site that has many users. Each user is allowed to log in and has access to a certain number of webforms (depending on their role status). Each webform contains a product that they receive for yearly award. They can pick from any of the products/forms that their user role allows.

The problem lies when they submit the form/product that they would like, the other forms are still active, which would allow them to submit another form etc etc.

I need to deactivate ALL webforms for that user when they submit their form/product choice so they cannot submit multiple products from the same user.

Please help.

B

make a user role user has submitted survey. use hook_webform_submission_insert or hook_webform_submission_update (what you use depends on if you allow Drafts) -- and change whatever role they have by default in your site, to user has submitted survey. Dont allow this new role to access any forms.


Migrating data from Drupal 6 to 7 with a twist I am working on an update of a site from Drupal 6 to 7. The site will have a complete redesign and - since the structure is somewhat chaotic - I don't want to migrate the complete data.

On the current site, articles are stored in 6 different content types which are different only by name, but have the same fields. I want to migrate them to the standard "article" type and only add a tag which will indicate which section they belong.

On the current site, images were uploaded to the server and then just linked from the teaser. I want them stored in an image field on the new site, and I need to modify the teaser too before inserting to the new site.

Can I do this on database level with a php script or should I do this in Drupal? In that case - how do I communicate between the old and the new version?

Or is there a module for this? What I need is:

Move all articles (6 content types) to new site (about 500 articles), all in the article content type and set a tag based on the original 6 content types
Catch images in teasers, make them drupal managed files and attach them to the correspondig node
Delete the image tags from the teasers (they will be displayed from the image field)
Retain paths and tags for the nodes as we have a lot of indexed pages

Is this possible or shuld I choose another path?

EDIT: Ok, I can insert nodes in the new system by code and add taxonomy terms as required, but I still trying to figure out how to add images and the way of communication between the two systems.

EDIT Thanks everyone for the ideas. I solved the problem by writing a custom module that communicated with the D6 install and pulled the nodes I needed.

In my experience the Migrate Module works really well for this.

In your migration you could use Preparerow() method to modify the fields you want to change before the import.

You can find more documentation on it here:
Advanced Field Mapping
Drupal Migration Documentation

Hope it helps :)


Is it possible to add template suggestions for image styles? I am experimenting with durpal 8 theme hook suggestions. I tried to customize the the theme suggestions based on the style name. I want the ability to add a twig template for each style if I wanted so I tried this:

function themename_theme_suggestions_image_style_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

and

function themename_theme_suggestions_image_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

I was expecting to see this as a theme hook suggestion in the html comments printed by in the page source after enabling twig debuging.

Using xdebug the hook is triggered but I don't find it in the suggestions list in the html after enabling   twig.config.debug to true.

am I missing anything?

hook_theme_suggestions_HOOK_alter doesn't use a third argument.
You are supposed to add the suggestions as string.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_style_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}


How to render the content in which the user is mentioned in? I render the Views page on the user profile page to show the content this user created.
Now the scenario changed and I have to render the content in which this user has been mentioned using Entity Reference fields. For just one field there is no problem, since I did it using Contextual Filter ... but when I'm trying to do so using multiple different fields (for different content types), then I do not get any results.

Is it possible to achieve this using UI or is it possible to put a custom query somewhere to get results and benefit from the Views fields?

Thank you all in advance!

If you think about writing this as a pure SQL query, what you are trying to do is have multiple WHERE conditions that are separated by OR operators.

Using OR operators with Conextual Filters is not possible out-of-the-box with Views. All Contextual Filters are added as AND filters.

There appears to be a module that adds this option, although I have not tested it. It doesn't have an official release, but appears to be in use by over 2000 sites, so might be worth a try: https://www.drupal.org/project/views_contextual_filters_or

Ultimately, however, this could be solved with a different data architecture. Is there a reason you have multiple different fields for referencing the user? Could these fields be combined into one base field, with instances on various content types? If so, then you can do it with a single Contextual Filter.


Hide row in view if any field is empty I have a Drupal 7 view that uses fields as display type.

There are three fields, and I don't want to show the row if any one field is empty.

Currently, I am adding a filter for each of the three fields to achieve this. meaning if I have 20 fields, I would have to go for 20 filters.

Is there an easier way of doing this?

P.S. I can do this by overriding the row style output template file, and then add some custom php code. But I want to know is there an easier way using the views administration interface.

You can add filter criteria corresponding to the field on which you want to hide the row .
Suppose you want to hide the row if content: body is empty then you can add filter criteria as Content:Body not equal to  "" (where value field should be left empty).
This will automatically hide the row if the specific field is empty
.


Pros and Cons of Combining CSS/JS files or loading contextually? I am building an application in Drupal 7.
There is one common CSS file A.css with 1000 lines of code. There are other 5 CSS files(B.css,C.css .... F.css) with 100 lines each. I want to load the other 5 files contextually(only on the pages they are needed).

Regarding pagespeed, what are the pros and cons of combining all those CSS files into one or loading them separately(contextually) ?

AFAIK, If I load them contextually, then the weight of those 5 files will be avoided in the pages they are not required. But I am not sure how Drupal's aggregation works. There are two possibilities I can think of.

When B.css is loaded contextually, the aggregated file will contain A.css + B.css into one file. Lets call it X.css. By this logic, when C.css is loaded, the aggregated file will contain A.css + C.css. Let's call it Y.css.  But since X.css and Y.css are two different files, this will not utilize browser's caching and will make http requests each time.
When B.css is loaded contextually, A.css and B.css will load separately. And similarly C.css will be loaded separately when needed. By this logic, A.css will be cached. Also B.css and C.css will be cached after being loaded once.

Which way it works(1 or 2)? How do I control it ?

As Drupal documentation says here: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme,

Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load every assets on every page, because it slows down front-end performance.

You don't need to worry about loading libraries (CSS/JS) contextually. Drupal can load individual libraries for a certain block, or when a certain node type is being displayed. That's the purpose of the [theme-name].libraries.yml file, you can mention the specific blocks and page in there and tell it load the required library for that part.

You can attach the library to all pages, to specific Twig templates, or to a render element in a preprocess function.

For instance for a maintenance page:

maintenance-page:
 js:
  js/mobile.install.js: {}
 css:
  theme:
   css/maintenance-page.css: {}
 dependencies:
  - system/maintenance
  - thunder_admin/global-styling

Or for certain blocks or part of your page:

vertical-tabs:
 css:
  component:
   css/components/vertical-tabs.css: {}
dropzonejs.widget:
 css:
  component:
   css/components/dropzonejs.widget.css: {}

You can also use hooks like THEME_preprocess_HOOK() function in the .theme file. For instance, if you want to attach JavaScript to the maintenance page, the "HOOK" part is "maintenance_page", and your function would look like this:

function fluffiness_preprocess_maintenance_page(&$variables) {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}


Configuration form confirmation I have a configuration form which extends ConfigFormBase.

How can I add a confirmation popup/page to give a message to the user that some field has certain value and do you wish to continue form submission?

I know there also is the ConfirmFormBase class but I don't have a clue how to implement this in my configuration form.

I'm not sure you could easily implement ConfirmFormBase with the config form. It might be easier to turn your form into a multistep form and have step 2 with a simple submit button/message for confirmation rather than trying to implement ConfirmFormBase

That should achieve essentially the same thing


What is the picture field in the node object? print_r($node) outputs:

stdClass Object
(
    [nid] => 4
    [type] => grouptype
    [language] => fa
    [uid] => 1
    ....
    [title] => sample group
    ....
    [name] => roshd
    [picture] =>
    ....
)

What is picture and how can I upload a picture into this field?

This is the profile picture of the author of that node. You can upload that in your edit profile form and you can display it using theme('user_picture', $node);.

If you want to be able to attach images to nodes, have a look at CCK and ImageField..


The purpose of $page in node.tpl.php and when does it become FALSE? I noticed that there is a variable $page in node.tpl.php and it is usually TRUE.
The node title is not displayed while it is TRUE, but in page.tpl.php, the node title has been displayed as a page title. The below is the code snippet from node.tpl.php of Bartik theme.

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

  <?php endif; ?>

When the variable is FALSE, the node title in node.tpl.php will be displayed and it seems like duplicate title being displayed. I tried this:

function bartik_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $variables['classes_array'][] = 'node-full';
  }
  dpm($variables);
  $variables['page'] = FALSE;
}

What is the purpose of this variable and when does it become FALSE?.

That variable becomes false in:

template_preprocess_node

with

$variables['page'] = $variables['view_mode'] == 'full' && node_is_page($node);

See also:

node_view

For the view_mode parameter used there.

The output of the node $title is controlled by page.tpl.php for the full page node view.


what happen if i have the same route as path alias? What if I have the following route in a custom module and a path alias that is equal to the route path?

mymodule.contact:
path: /contact
defaults:
    _controller: Drupal\mymodule\Controller\MyController::contact
requirements:
    _permission: 'access content'


Composer cannot find drupal/commerce in a specific module I'm attempting to update the dependencies of a specific module in my site. I've downloaded the module with git and navigated inside. If I run composer validate it says ./composer.json is valid.
However if I run composer update or composer require drupal/commerce:2.16 I get the error :

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

  Problem 1
    - The requested package drupal/commerce could not be found in any version, there may be a typo in the package name.
  Problem 2
    - The requested package drupal/search_api could not be found in any version, there may be a typo in the package name.

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

I cannot figure out what is the legit issue here.
This is the current require of my composer.json

  "require": {
    "drupal/commerce": "~2.8",
    "drupal/search_api": "~1.9",
    "picqer/php-barcode-generator": "^0.2.2",
    "cboden/ratchet": "^0.4.1"
  }

You need to add the Drupal repository to composer.json in your project.

"repositories": [
  {
    "type": "composer",
    "url": "https://packages.drupal.org/8"
  }
]

Note that after you do this and run composer require/update, it will create a vendor directory in your module folder. You'll want to delete this folder, as you only want your dependencies to be added when the module is added to your project, and your project's composer.json should install the dependencies in the correct directory.


Duplicate Results in View with OG Relationship I have a view that uses the OG Relationship "OG membership: Group Content (node) from OG membership", and this relationship is causing duplicates when a person has more than one group assigned to them.

If I use aggregation settings along with checking the distinct checkbox in the query settings, the duplicates disappear. (Oddly enough, I needed to use BOTH aggregation and "Distinct".)

However, I want the ALL Content Titles for the related Group (which is why I needed the relationship).

I even tried the Views Distinct module, but after fumbling around with it, it either shows one Content Title from the group or all Content Titles from all groups.

All of this behavior leads me to believe there's an issue with OG relationships because there's no way to aggregate the content titles that I can find.

Am I looking at a views hook to fix the issue?

Okay, so I believe I traced the issue to a problem with Entity Reference Relationships in Views, and posted a bug.

However, I was able to solve the duplicate issue AND get the results I wanted (all titles from related groups) by taking a different approach in the View.

Instead of hook_query_alter() or hook_views_pre_render(), I just wound up adding the field that reference the groups, setting the Formatter to "Label", and checking the "Link label to referenced entity." This produced a comma-separated list of groups linked to the group page (exactly what I wanted).


Transliteration of Danish characters I have a site running with these modules (among others):

Pathauto
Transliteration

My problem comes with danish characters. Normally they would be replaced like this:

Æ = Ae
æ = ae
Ø = Oe
ø = oe
Å = Aa
å = aa

However, the Transliteration module isn't working like I would expect; it replaces:

Æ = ae
æ = ae (correct)
Ø = o
ø = o
Å = a
å = a

So "ÆØÅ - æøå" becomes "aeoa-aeoa".

The "lower case issue" might be caused by the Pathauto module, and it is not neccesarily a problem with the transliteration. Still it's not correctly replaced.

This is a file from the Transliteration module that I think it does the replacement of Danish characters, but I can't figure out how to make it work correctly.

x00.php

<?php

$base = array(
  // Note: to save memory plain ASCII mappings have been left out.
  0x80 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  0x90 => '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
  0xA0 => ' ', '!', 'C/', 'PS', '$?', 'Y=', '|', 'SS', '"', '(c)', 'a', '<<', '!', '', '(r)', '-',
  0xB0 => 'deg', '+-', '2', '3', '\'', 'u', 'P', '*', ',', '1', 'o', '>>', '1/4', '1/2', '3/4', '?',
  0xC0 => 'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I',
  0xD0 => 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'x', 'O', 'U', 'U', 'U', 'U', 'U', 'Th', 'ss',
  0xE0 => 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i',
  0xF0 => 'd', 'n', 'o', 'o', 'o', 'o', 'o', '/', 'o', 'u', 'u', 'u', 'u', 'y', 'th', 'y',
);

// Overrides for Danish input.
$variant['da'] = array(
  0xC5 => 'Aa',
  0xD8 => 'Oe',
  0xE5 => 'aa',
  0xF8 => 'oe',
);

// Overrides for German input.
$variant['de'] = array(
  0xC4 => 'Ae',
  0xD6 => 'Oe',
  0xDC => 'Ue',
  0xE4 => 'ae',
  0xF6 => 'oe',
  0xFC => 'ue',
  0xDF => 'ss',
);

SOLUTION

When developing I had the language set to English; it needs to be set to Danish, in order to get this to work.


How to change a datatype for a field How do I change a data type for a field in a table?

To change the field name we can use db_change_field().

The same function can be used to change the type of the field.

Suppose you are the following field defined for the "foo" schema.

$schema['foo'] = array(
  'fields' => array(
    'bar' => array('type' => 'int', 'not null' => TRUE)
  ),
  'primary key' => array('bar')
);

You can change its type to "serial" using the following code:

db_drop_primary_key($ret, 'foo');
db_change_field($ret, 'foo', 'bar', 'bar',
  array('type' => 'serial', 'not null' => TRUE),
  array('primary key' => array('bar')));

The call to db_drop_primary_key() is necessary because the field is a primary key; for compatibility with any database engine, it is suggested to first remove the primary keys, the indexes, and the unique keys before to edit them.

If in the call to db_change_field(), the third and the fourth parameters contain the same value, then you are not changing the field name.

The documentation for the function contains the following text:

  Change a field definition.

  IMPORTANT NOTE: To maintain database portability, you have to explicitly recreate all indices and primary keys that are using the changed field.

To notice that the first line doesn't say "change a field name"; it says "change a field definition," and the field name is included in the field definition.


How to tell if a function is being called by javascript? I have a validation function that is being called either from another php function or a JavaScript call. I was wondering if there is a way to determine if the function is being called by JavaScript so that I can implement different functionality. I am using Drupal 7 for this but if you could post an answer for Drupal 6 too, I am sure that would help out other people as well.

JavaScript cannot directly call a PHP function. If you think that JS may be 'triggering' the call of that validation handler, then there must be an AJAX event going out to the backend, which then calls the validation handler. If that is the case, the request will go out to the system/ajax URI on your site (unless it has been intentionally changed to a different URI - you can double check this by viewing the 'Network' tab in Google Chrome's developer tools), which will then handle the request and dispatch it to the validation handler.

So...

You can check the $_GET['q'] value in your validation handler:

if ($_GET['q'] == 'system/ajax') {
    // AJAX request
}
else {
    // other request
}


Avoid PDOException while connecting to an external database I'm trying to connect to another database (not related to drupal) in drupal to show extra info. This database server could be down and is not a problem, if it's the case I don't want to show the info with no errors, maybe an info message that is now available at this moment.

I setted up the settings.php correctly with the database credentials, and when the database is up, everything is ok.

I use the next code

  db_set_active('external');
  $query = db_select('extra_info', 'i');
  ...

If the database is down, the db_select() fails and throws an PDOException. The problem is the website is down in that case, shows the error and so on. I tryed to sorround it in a try catch.

  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
  }

I don't know if there is a way to check if the database connection is ok first and then do the select or do nothing if is there is a problem and continue showing the website.
I tried the isActiveConnection() function, but I think is not what I need.

Thanks.

EDIT: The solution to my problem is to use db_set_active() back to default.

  try {
      db_set_active('external');
      $query = db_select('extra_info', 'i');
      ...
      db_set_active(); // This won't be executed!
  }
  catch (PDOException $e) {
      // Ok.. is not a problem
      db_set_active(); // Needed!
  }

issue is that db_set_active just sets active key in some array and doesn't do any connection. when you do db_select or any other query only then it connects.

your second code is good. also you could do something like this:

  db_set_active('external');
  try {
   //check connection
   db_select("select 1");
  }
  catch (PDOException $e) {
      //error. set default back
      db_set_active('default');
  }

as you know how to check if connection is there now you just need extra logic what todo when connection cannot be established


Views callback work only once with advanced form block this code work but the views is callback only once (reload only once), any idea to reload more than one time ?

see in detail on drupal.org

function modulename_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'form_id_of_your_afb_form':
            $form['#validate'] = array();
            $form['ajax-submit']['#ajax']['callback'] = 'modulename_create_callback';
    }
}
function modulename_create_callback($form, &$form_state) {
    // load view
    $view1 = views_embed_view('view_name','view_display_name',$view_arguments_as_required);

    // replace the afb form with a clean form
    $newform = afb_ajax_handler($form, $form_state);
    $commands = array(
      ajax_command_replace('#target_div_id_of_view_to_update .view',$view1),
      ajax_command_replace('#target_div_id_of_afb_form_to_replace',render($newform)),
    );
    $form['#type'] = 'ajax';
    $form['#commands'] = $commands;
    return $form;
}

you just need to put the number of tid directly here :

ajax_command_replace('#target_div_id_of_view_to_update .view','1'),


Drupal7 multistep module - how to skip validation on previous I created a multistep node form in Drupal7 using the multistep module (http://drupal.org/project/multistep)

I patched the module so it would work (previously Drupal complained about required fields that weren't on the current step). The module is working fine now, the only thing is that if I press the previous button, it still validates the current step. I want to skip this validation, so the current step is only validated if I press the next or done button.

I digged into the module code, but really cannot figure out what to search for.

Can anyone help me on this?

Edit: Here's my form_alter function for multistep:

function multistep_form_alter(&$form, &$form_state) {
if (isset($form['#multistep'])) {
  $excluded_children = _multistep_gather_excluded_fieldgroup_children($form, $form['#multistep']['current']);
  $current_children = _multistep_gather_current_children($form, $excluded_children);

  $prev_excluded_children = _multistep_gather_excluded_fieldgroup_children($form, $form['#multistep']['previous']);
  $prev_current_children = _multistep_gather_current_children($form, $prev_excluded_children);

  // Apply limit validations to all submit fields.
  foreach (element_children($form['actions']) as $key) {
    if ($key == 'previous') {
        if (isset($form['actions'][$key]['#type']) && $form['actions'][$key]['#type'] == 'submit') {
          $form['actions'][$key]['#limit_validation_errors'] = $prev_current_children;
        }
    }
    else {
      if (isset($form['actions'][$key]['#type']) && $form['actions'][$key]['#type'] == 'submit') {
          $form['actions'][$key]['#limit_validation_errors'] = $current_children;
      }
    }
  }
}

}

I'm not familiar with the multistep module, but in Drupal 7 this functionality can normally be accomplished by using #limit_validation_errors. It would probably be best to alter the form(s) that you need with hook_form_alter (or a variation of it) in a custom module. A basic untested example of what I described:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'THE_RELEVANT_FORM_ID') {
    $form['THE_PREVIOUS_BUTTON_KEY_NAME']['#limit_validation_errors'] = array();
  }
}


How to set an expiration date on an active rule so that it is disabled on a certain date? Anyone knows how to set an expiration date on a Drupal 7 Rule (using the Rules module) so that the rule is disabled on a certain date?

Example Use Case:

We've created a product (using Drupal Commerce) with a name that's just a long string of random upper and lowercase characters and numbers. We then created a rule with one condition and two actions so that when Drupal is initialized (the event) it recognizes a specific URL a user came to the site with (ie. sitename/?SKU=productnamewithlotsofcharacters)[using the text comparison condition and then the provide URL argument value action] and when that's the case it re-directs the user to a specific product form (page redirect action to a drupal commerce express checkout form).

We only want this promo to last until a certain date, but we will be using it again in the future (so we just want the rules disabled). When the user uses this link to get to our site and the promo is 'expired' it takes them to a page that says 'Promo Expired'.

It's not the most fool-proof method of doing things of course but it works well enough for our needs.

Programmatically disable a rule contains an example of how you can disable a rule programatically, as in this example:

/**
* Implements hook_update_N().
* Disables name_of_rule rule.
*/
function hook_update_N() {
  $rules_config = rules_config_load('name_of_rule');
  $rules_config->active = FALSE;
  $rules_config->save();
}

Tune this example to fit the machine name of your rule to be disabled, and then use that as the "PHP code " in a Rules Component (Action) which only performs an "Execute custom PHP code".

With that, the only challenge left to make this work, is to enhance your rule to be disabled, to conditionally trigger this (new) Rules Component "after the moment has arrived" for your rule to be disabled. For this you might want to add "Conditional Rules" (so that you can add a condition within the Rules Action of your rule to be disabled).


Is it better to hard code everything or use the ui? Is it better to hard code everything or to use the ui?  For example, is it better to field and entity with the UI or to add fields/instances programmatically?  Does it really matter?  What is the 'best practice'?

If you use code you can:

Version control the field settings.
Lock the field, so it can't be deleted or altered in the UI.

It's always a good idea to keep as much as possible in code, for when you need to roll out changes etc. This is why i prefer the above method, even though it is more time consuming during development. Depending on your use case, you may save a lot of time doing this however.


What is the difference between hook_menu(), hook_menu_alter(), and hook_menu_link_alter()? So, I am fairly new to Drupal (about 8 months in) and I am using Profile2 with 3 different profile types. Everything is working excellent, except for I wish I could wrap my head around how I can override the Profile2 view button when you click on, let's say Main Profile. So, if you are familiar with profile2, you know that it comes with a default profile as soon as it's activated, and when you click on it within the User Menu, you are presented with a screen with the local menu tabs called View, and Edit.

All I want to do is keep the View button, but change the path to either a panel page or an actual Views page.

I've explored hook_menu(), hook_menu_alter(), hook_menu_link_alter(), and to tell you the truth, I just don't get how those work. I believe hook_menu actually adds new "nodes" or paths to the system with their own page?

I think I have a lot to learn when it comes to these three functions (hook_menu(), hook_menu_alter(), and hook_menu_link_alter()) I just need a savior to explain these to me.

As a sub question, along with the View, and Edit button, how would I go about adding an extra local menu button to this row? Like upgrade my account, or view your bill?

Any light would be appreciated, and I do have the Devel module installed, as well as the theme developer tool. I tried making a custom module, and running a DPM on those functions above, but it's not even outputting anything.

hook_menu() -> Define menu items and page callbacks.

hook_menu_alter() -> Alter the data being saved to the {menu_router} table after hook_menu is invoked.

hook_menu_link_alter() -> Alter the data being saved to the {menu_links} table


Restrict Users from viewing frontpage When user enter http://localhost/node then the user will be able to view all the nodes created in the site till date. In the site there are some content type which are viewable to all users on site and some are restricted to created users and shared users.How to stop users from viewing those nodes which they have not created. It will also be OK for me if user enter http:///node then "Page Not Found" displayed.

Please let me know your views.

Drupal has only a very course access control structure for viewing content.  For the authenticated user role, you can set permission to 'view published content' (Drupal 7), but that's about it.   With that permission set the user will be able to view all the published nodes created in the site till date, without it, no content except own content will be visible.

Since the core's built-in support for node access control is rather course,  to control access to view a node, you must use some sort of node access control module.  There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module to control access.

One particular module, named Flexi access, allows you to create access control lists that explicitly contols the published nodes viewable by each logged in user.  This gives you fine grained node access control, but it may also be cumbersome to maintain such lists with a large number of users and nodes.

If you can live with a less fine grained resolution (role) there is the Content Access module.  While still only in beta for Drupal 7, I regard it as stable for role based node access control.  However do not use it for lower resolution (user based) access control, as this mode is not yet stable.

Finally, for more complex access control relationships, there is Organic Groups.  This is large. powerful and fairly complex project, but well suited for complex and entangled access control.

Disclosure: I am the maintainer of Flexi access.


Hide Breadcrumb on Taxonomy Term View Hello i asked this on stackoverflow and was refered to here. I hope you dont mind me copying and pasting it. thanks

Hello i don't really know where to ask this on drupal so i hope you all don't mind me asking it here on your fine site. Everything ive asked before has been resolved by your good selves so i thought i'd give you a try on this. Thanks.

I was hoping to just hide my breadcrumb when viewing the taxonomy term view created by Views. I do use Custom Breadcrumbs module but from what ive read that just edits the output and not the breadcrumb appearing or not. Here's an example of my view-
http://onlinebanter.com/general-chat

As you can see it's pushing the centre of my page down so as it isnt lined up with the sidebar. I dont really need it in these views. All help appreciate from your vast combined knowledgebase.

Thanks

Reg

This is easily done with a little bit of theming. Based on the page being displayed, you can unset the $breadcrumb template variable to suppress output of the breadcrumbs on that particular page.

Pop a function like this simple example into YOUR_MODULE's template.php:

function YOUR_MODULE_preprocess_page(&$vars) {
  if ($_GET['q'] == 'general-chat') {
    unset($vars['breadcrumb']);
  }
}


'The alias is already in use' when editing a node that had an alias generated programmatically I'm currently using an event subscriber to latch onto an event from a module that creates and/or updates nodes. I'm programmatically setting the url alias based on a user inputted field by doing the following

$path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

It works but when I open the node and attempt to edit it, I get the message

  The alias is already in use

When I try to save it. Is there something I'm missing? Does a field on the actual node have to be edited as well?

I'm also using pathauto if that has any effect.

UPDATE: I just noticed that whenever that aliased is saved it generates 4 entries in the URL alias list.

Turns out whenever you perform this

\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

It generates a new alias every time even if the path alias already exists. I was able to resolve the issue by performing checks to see if the path already exists like so:

if (!\Drupal::service('path.alias_storage')->pathHasMatchingAlias('/node/' . $node->id()) && !empty($node->id())) {
    $path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");
}


Where can I see screenshots of various themes? On Drupal.org, there are literally hundreds (perhaps thousands) of themes. As far as I can tell, the only way to actually see what a theme looks like is to install it. (Some of them have screenshots of the actual theme, but many just have what the creators apparently believe to be a cool logo, which really doesn't help much in determining what the theme itself looks like.) Is there a gallery somewhere that contains screenshots of all the themes?

Some can be browsed here http://themegarden.org/drupal6/


Running module unit tests from CLI: "Class '..' could not be found" I am trying to run module-provided PhpUnit tests from the CLI.

Following these instructions, so my core/phpunit.xml should be correct now.

Using this command:

cd core
../vendor/bin/phpunit modules/system/src/Tests/Installer/InstallerTranslationTest.php

I get this output:

Class 'modules/system/src/Tests/Installer/InstallerTranslationTest' could not be found in '/****/core/modules/system/src/Tests/Installer/InstallerTranslationTest.php'.

Module-provided tests in e.g. core/modules/system/tests/src/.., are found, and work correctly with the phpunit command. But tests in core/modules/system/src/Tests/.. do not seem to work, or be detected.

(I think I had this problem before, and someone told me what was missing. But I don't remember anything. Time to document this in this Q/A site.)

Ok, so the solution is

From Drupal root directory:

sudo -u www-data php core/scripts/run-tests.sh --url http://d8.localhost/ --class "Drupal\system\Tests\Installer\InstallerTranslationTest"

Assuming that your site is available under http://d8.localhost, and it is an installed site.

Maybe you want to use --verbose for more output.

Documentation on drupal.org: Running Tests Through command-line


How can I resolve these errors when updating the module? I want to update Drupal Commerce to 8.x-2.0-beta7 from a clean, Composer-based installation of 8.x-2.0-beta6, following the documentation on http://docs.drupalcommerce.org/v2/getting-started/update.html.

I noticed that composer update drupal/commerce --with-dependencies did not update drupal/core. This surprises me. Isn't drupal/core a dependency? Anyway, says it's white-listed so I then ran composer update drupal/core.

Now I am hitting a problem with updates.

  drupal update:debug

  Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore
      as DrupalConsoleCore because the name is already in use
      in/pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on
      line 11

  drupal update:execute

  Fatal error: Cannot use Drupal\Console\Core\Bootstrap\DrupalConsoleCore
      as DrupalConsoleCore because the name is already in use in
      /pathto/commerce8/vendor/drupal/console/src/Bootstrap/Drupal.php on
      line 11

I have since run update.php, but the Composer errors persist.

I am learning about Composer, and I don't know yet anything about Drupal Console.

What am I doing wrong?

It sounds like Drupal Console someone was installed improperly, based on the duplicate class name error.

Can you try removing the /pathto/commerce8/vendor directory. Then run composer install once more. That'll fixup all third party dependencies, hopefully resolve this.


How to get total of a field for all the nodes? I've payment content type. One of the fields of this content-type is Amount. In a view (page display: table format) I'm listing all the payment nodes (subjected to some filtering). In the same view I want to calculate the total amount amount of all these filtered nodes & display. How?

You should be able to use Views Calc or, if you need more flexibility, Views Aggregator Plus


How can I conditionally add a parameterized variable to my themes based on URL? I'd like to do something like the following:

If a user goes to node/15, my node.tpl.php file is used, as normal, to generate HTML.

If a user goes to node/15/animal/7, then my node.tpl.php is still used, as expected, but it has a variable in scope called $animal, set to the value that I would get from loading an animal.

So, the URL schema would look something like the following: node/%node/animal/%animal. I want this behavior so that if the user goes to node/15, that's fine, but if they attempt to go to node/15/animal/100 and animal 100 does not exist, the user gets a 404.

The problem I'm running into is that this requires functionality from several distinct areas of Drupal, and I don't know how to make them work together. Adding a custom URL schema would be done in hook_menu(), which requires a page callback. Using anything other than node_page_view would cause the node not to be rendered as normal. BUT, adding a variable to the template's scope would require implementing moduleName_preprocess_hook(), which I only want to conditionally fire when the user hits this specific URL schema.

I could of course manually check the contents of the requested URL myself, perhaps during moduleName_preprocess_hook, but this seems a little too low-level. Surely Drupal has some sort of way to accomodate what I'm trying to do?

You're on the right track: it'll be much more straightforward to stick this in a module where you have access to the menu system, and the most straightforward way to expose the data to the node template is through preprocess functions.

First, create an implementation of hook_menu():

function example_menu() {
  // Only two things specific to your case is page callback
  // and page arguments. Other options taken from node_menu(): customize as
  // you see fit.
  $items['node/%node/animal/%'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'example_animal_view',
    'page arguments' => array(1, 3), // Pass node object and animal ID
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
  );
  return $items;
}

Then create your callback, which will display the node as normal (including using the node template) if your animal check succeeds:

function example_animal_view($node, $animal) {
  if (animal_exists($animal)) { // Replace with your own check
    return node_page_view($node);
  }
  // Return a 404 if the check failed
  return MENU_NOT_FOUND;
}

Now, to expose the animal ID to node.tpl.php; you could either add it to the node object via the Field API, but in this case—since you're just using it for theming purposes—it's much easier to just add it to the template variables in a preprocess function:

function example_preprocess_node(&$variables) {
  if (arg(2) == 'animal') {
    $variables['animal'] = arg(3);
  }
}

You could do this last part in your theme, but I'd keep it in the custom module to encapsulate the functionality so it's available in every theme.

Finally, in node.tpl.php, just reference $animal.


How to print the products (fields) on a node using a custom display I am new to Drupal and I've been trying to create a site to function as a lending inventory. I have so far created a new content type with my fields (describing product details) which the user fills with data every time he adds content(adds a product). I want to be able to print the saved result of the add content page to a document but not in the display that it has as a row of the table view. To be more specific I would like to print every product and its details in a customized way so that the details are displayed in two columns and above them a text of lending agreement can be put.

I am sorry in advance for the complexity of the description
Does anyone have an idea?

Thank you

Hello @katerina and welcome to Drupal Answers.

You could use Display Suite and do the following:

Enable DS and DU UI modules
Create a new View mode for nodes, e.g. "Receipt"

For your content type, go to "Manage Display" > "Custom display settings" and activate the "Receipt" view mode for your content type

Now you should have, besides "Default" and "Teaser", the "Receipt" view mode available under "Manage Display" for your content type

Available directly under admin/structure/types/manage/PRODUCT_CONTENT_TYPE/display/receipt

You can now select the layout that suits you under "Layout for PRODUCT_CONTENT_TYPE in receipt", for example "Two column stacked"
You can use the available regions of that layout to lay the details out between the two columns
For the "Lending agreement" text, you would need to use a DS Code field, available under "Custom fields" > "Add a code field". You can enter your Lending agreement text in there, and then place that field in your header area.

That should be enough to cover the configuration of your custom display.

In order to get some URL access to that view, per product, you could use the View Mode Page module. Once you install it, you get a new configuration tab in your content type's "Manage Display" page, called "View mode pages".
There you can do the following:

Enter a URL patter under "URL pattern", e.g. 'node/%/receipt'

Save that configuration, clear all caches, and try to enter a URL for an available node, e.g. node/123/receipt
This should load that node using the view mode you configured above.

Hope this helps, good luck!


Calling a module function name in Ajax URL I am developing a custom payment gateway for Drupal Commerce. I am getting some problems calling a custom module function from an AJAX URL.

How do I call a module function from a custom AJAX request?

function custom_gateway_settings_form($settings) {
  $form = array();

  $form['code'] = array(
    '#type' => 'textfield',
    '#title' => t('Code'),
    '#maxlength' => 100,
    '#description' => t('Code.'),
    '#prefix' => '
',
    '#suffix' =>'
',
  );

  $form['btncode'] = array(
    '#type' => 'submit',
    '#id' => 'btncode',
    '#value' => 'Get the code',
  );
}

The JavaScript code is the following one.

   jQuery("#btncode").click(function() {
     jQuery.ajax({
       type: "POST",
       url: Drupal.settings.basePath + "/?p=ajaxGetCode",
       cache: false,
       beforeSend: function() {
         // jQuery('.loadrimage').show();
         // jQuery(".error").hide();
       },
       complete: function() {
         // jQuery('.loadrimage').hide();
       },
       success: function(htmlText) {
         alert(htmlText);
       }
   });

You have to create own endpoint and call post on it. For example create menu element using hook_menu:

$items['my-module-ajax-endpoint'] = array(
   'page callback' => 'my_module_ajax_callback',
   'delivery callback' => 'ajax_deliver',
   'access arguments' => array('access content'),
   'type' => MENU_CALLBACK,
);

And now post to it.


Set number of values for a field in an entityform type based on a fixed value I'm working with an entityform type that has a field with unlimited input values, so with the default button "Add another" I can add multple values for a field.

I'd like to fix this number of values, maybe with a get or post value, so I can preselect a specific number of values and then limit user to fill a specific number of fields.

Example:
first select how many items to order --> user selects 4 items --> user must fill 4 values of the same field and user can't add more or less then 4 items.

Do you think it's possible with drupal modules?

After hours of searches I found a solution: https://www.drupal.org/node/2868353


Add class to Menu Block UL unique to each Menu Block instance? I've seen lots of answers, but they only allow you to add classes to all Menu Blocks, or to specific Menus.

I have multiple menu blocks with the same menu behind them (1st level block, 2nd level block, etc.)

I need each menu block to have a unique class based upon the name of the Menu Block. Is this possible?

Unless your theme changes the usual behavior then each of your menu blocks will have its own unique ID so you can use CSS like this (note the ID/class I used here might not be the ones you have to use, they're just an example):

#block-menu-block-2 ul.menu

This way you don't have to worry about overriding the markup of the menu to add classes in.


More options for page--node--edit.html.twig for content type Using my Theme debug I'm getting the following themplate suggestions

page--node--blogpost.html.twig

page--node--edit.html.twig

When I tried to use different template to edit a blogpost template only like

page--node--edit--blogpost.html.twig

the template was ignored. How to add more template suggestion for Drupal?

What you are looking for is called theme suggestions you can implement your own or alter existing ones. In this case since the theme hook is provided by another module (core) you need to alter the provided suggestions and add your own.

Check this post with useful examples. Also core's always have excelent examples (Bartik theme example).

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}


Count total number votes a user has gained I am using rate module where users can plus or minus the articles created by an author. Now, in the profile page of the author, I want to display the total number of votes he/she has got from all his articles. Is there any way to do this without using db_query ?
Thank you.

I think it would be pretty expensive to do this without writing your own query, but here is one way you could do it:

Use EntityFieldQuery to build a list of nids created by the current author. Something like this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article');
  ->propertyCondition('uid', '1')
$nodes = $query->execute();

Then parse the nids returned into a seperate array and use that array as a criteria parameter in votingapi_select_votes(). Something like:

$votes = votingapi_select_votes('entity_id' => $nid_array);

I'm not 100% sure that votingapi_select_votes() accepts an array for the $criteria['entity_id'] param. You might need to loop through each nid if it doesn't.


Filter upon paste in CKEditor My stakeholders encountering a situation where they have to do finagling in the CKEditor window when they copy and paste from Google Docs, which they do often.

Ideally, what would happen is that inline styling information is stripped out from pasted tags, while preserving other styling information. For instance, here's the tag for some large-sized text, copied from Google Doc's resume template, and pasted in to CKEditor in Drupal 8.6.13:

Your Name

Is there a way to strip out the font-style and font-size attributes on page? I've googled for information on the Drupal side, and also on the CKEditor site, but I haven't found positive confirmation that this is possible.

I see that there are modules for CKEditor that provide a "Paste from Google Docs" button, but my team doesn't want another button they have to remember to use when they are pasting from Google Docs -- they want this to work with the default paste functionality. We will never be using the source font-size and font-family, because we have a style guide for our entire site which is standardized.

I am aware that typeface can be handled differently (e.g. styling  tags as bold instead of using font-weight:bold, etc), but we can deal with that. What I am looking for is how to get rid of the font family and font size.

As regarding custom text filters, I looked at this tutorial and downloaded and installed the sample celebrate custom text filter module. Upon testing, I confirmed that it only changed text when I saved the node, not when I pasted into the CKEditor textarea widget. So a custom text filter module does not do what I want.

I found the CKEditor custom config module. This allows one to specify arguments to ckeditor's config object. This module provides me as much configuration as CKEditor allows.

I am still testing if I can filter specific inline styles, but if I can't do that, then that's an inability of CKEditor, not Drupal's ability to interact with it.


New to Drupal 7 and I was wondering if this is possible to do? I am new to Drupal 7 (it's been years since I touched Drupal 6) and I have a question regarding a concept.

Is it possible to "port" an external web applications into Drupal so it appears to be part of the website, but the app itself actually lives on another server? The external web application will have no dependencies on Drupal other than it's served up via Drupal so it appears to be part of the site.

Example - I build a webform an it lives on Server A, can I server it up via Drupal and keep all of the apps functionality?

Is this possible?

Yes, it is possible. You can port an external web application, and can make it automatically compatible with your div specific properties. I suggest you to use jQuery to get external web application.

To add jquery in drupal 7, you need to install JS injector module. Enable the module and you can add jquery at admin -> config -> development -> js-injector. In the JS code section, the syntax is as follows:

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

   =====your jQuery code goes here ==========

}
};
})(jQuery);

For porting an external web application, let us assume you have a link/button in a specific div section and when you click on that link/button, I'm going to display that website in a target div section.

HTML should look like this:

    Click here to port an external website.

And the jquery to port web application:

$('#sourceDiv a').on('click',function(){
    var url = $(this).attr('href');
                                     //returns the targetDiv's height and width
    var height = $('#targetDiv').height();
    var width = $('#targetDiv').width();
                                    //replaces the div with porting the website.
    $('#targetDiv').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
    return false;
   });


should I use str_replace() or is there a better drupal way for that? Some background info:
I'm Building a D7 module that also sends out a message to users of the site.
I want the site maintainers to be able to define the message by using 'tokens' like this:

$string = "hello :username, there is a new node called :nodenodename_with_a_link on the :website"; // defined in the GUI

I could use str_replace to replace those 'tokens' like so:

$find = array(':username', ':nodenodename_with_a_link', ':website');
$replace = array($username, $node, $sitename); // generated form the db
$newstring = str_replace($find, $replace, $string);

But I'm wondering if this is also the correct way to go in Drupal (7)?

You can either create your own tokens in a custom module or use strtr (it's easier for multiple search and replace operations than str_replace).

To see how to create custom tokens and integrate with token module see token_example module in Examples.


i18n language switcher don't show on default lang I'm using Drupal 7 and Clean theme. And my site have 3 languages. Using i18n module for this features. Everything is working...

Language Switcher block is active, showing on 2 languages. But, when click my site default language, don't show this block.

How can i solve this?

There is an option under language switcher block configuration.You have to select all the language checkbox to display language switcher block in all languages.


Is it possible to programmatically add a path alias to a programmatically created node? I have created pre save hook in module which is populating my node by fetching information from various API's. However I can't get my mind around how to add node alias to newly created node. Is there any function or module or something (Drupal 7 had path_auto)? Or should I go with raw insert into url_alias? Might I shoot myself in the foot with such a drastic move?

To create the alias, I first check if the alias was set in the user interface, and if it is empty then I set it manually using the label().

use Drupal\Core\Entity\EntityInterface;

/**
 * hook_entity_insert
 */
function mymodule_entity_insert(EntityInterface $entity) {
    // Convert to lowercase, trim spaces, replace spaces with underscore and then truncate to 60 chars.
    $pathTitle = substr(str_replace(" ","_",trim(strtolower($entity->label()))),0,60);
    if ($entity->toArray()['path'][0]['alias'] == "") {
        $path = \Drupal::service('path.alias_storage')->save("/node/" . $entity->id(), "/mynewpath/" . $pathTitle, "en");
    }
}

https://www.drupal.org/node/1853148 for more information


Adding an 'Add more' button to a settings form in the backend For my module I need a settings form where administrators should be able to enter an arbitrary number of variables.

I have tried setting up an AJAX 'Add more' button, analogous to the example found in the AJAX example module. When I click the button, it doesnt add an extra field and I don't get any errors.

Can anyone help me out?

Example code, and my code: https://gist.github.com/Tagini/8282034

It turns out I had two problems:

I have jquery_update installed, which included a version too recent for the backend. I configured a previous version and I got a whole step further.
I did not have my $form and $form_state as input parameters in my main form function and as such the field count was not updated.


field renders with 2 spaces In a template I'd like to get an html tag from a field:

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

This should render  or  depending on the value of the field. But before the value it renders 2 spaces: <  h2>.

I have no idea where it comes from.

<?php print '<' . trim(render($content['field_headline_format'])) . '>'; ?>


Is there any way to disabling caching for a single field for anonymous users? I ran into an interesting, but probably a common, problem. With caching turned on, stock is not updated immediately for anonymous users (which makes sense as that's the point of caching). However this results in a little bit of a UXWTF. When a product is out of stock, users are still shown that '1' is still available. It's only when they try to add it to the cart, they are met with a notice

The maximum quantity of 'product name' that can be purchased is 0.

I would still like to keep cache pretty much for everything else, but is there a way to disable caching of the available stock count?

Just an idea - in this case a workaround might be to hook a function after an order has been placed and then clean the cache programmatically.

You can use the hook_commerce_checkout_complete() and there call the cache_clear_all() function.


Collapsing some fields in add content page I want to use the drupal Collapse style for some fields.For example: while writing a story in my drupal 7 site, on the content publishing form user will has an option like "I want to sell this story"
Now, if the user click on it then some filed's will show-up like [Story Price] [Story License] [Topic Summary], so that they can provide all those necessary information's to sell the story. Either, if the user don't want to sell the story, they need not face those fields instead of "I want to sell this story" link! Any idea? Thanks

You could try the Field group module. You can set field group settings "collapsed" and deselect "Mark group for required fields". It collapsed the field group by default.

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


Clear varnish cache for a specific node I am populating one of the node fields making third party api call. Since the data from api is supposed to change frequently mainly on node view. My question is, is it possible to clear caching for a specific node in varnish.

If you are using the Varnish HTTP Accelerator Integration module, you can use the varnish_expire_cache() function, that accepts specifics paths like nodes or could be for other paths too.


How to display drupal user page tabs on 3 different page We want to display a 3 tab  "Create new account(Lawyer Registration)" , "Log In" , "Forgot Password" link on 3 different pages. when we click on log in then they display all 3 tabs.

Actually we have 2 different type of registration process one for lawyer and another one is for normal user. when we click to login then they display above 3 tabs and this is confusing for user. so i want to hide this lawyer registration process form user page and call them to from different page.

So please help me how i can remove them from above tabs and call user/register page from different ways.

One quick solution to hide the tabs is to change the menu type form tabs to callback:

/**
 * Implements hook_menu_alter().
 */
function yourmodule_menu_alter(&$items) {
  $items['user/login']['type']    = MENU_CALLBACK;
  $items['user/register']['type'] = MENU_CALLBACK;
  $items['user/password']['type'] = MENU_CALLBACK;
}

You could render the user register form whatever you want with this:

$elements = drupal_get_form("user_register_form");
$form = drupal_render($elements);
echo $form;


Views: adding "new" image when published date < 1 month In a table view of nodes i want to add a tiny "New" image only when a node is published < 1 month ago.
Is there a way to achieve this without using PHP? If not, is there an easy way and what PHP should i insert?
I was hoping for a little module to get the job done, but haven't found anything.

Thanx,
Cas

If the list is always going to be in date order, then it can be done without PHP by using a View with an attachment. See this answer for an explanation of how to do that.

If the list is not sorted in date order, PHP may be the way to go. (Though I'd be delighted to be contradicted.) You'll need the Views PHP module installed.

Add the Content: Post date to your list of fields. If you don't want it displayed set the 'Exclude from display' check box. Displayed or not, it's needed.
Add a 'Global: PHP' field to your list of fields. In the Value code box, insert the following snippet:

$interval = time()-  $data->node_created;
$days = round($interval/(60*60*24));
return $days < 30 ? $days : 0;

This snippet grabs the value of the Post date field from the database query that the view has executed. It then works out the number of seconds difference between the post date and the current time. It converts the seconds into days. If the post is less than 30 days old it returns the number of days as a field value, otherwise it returns 0. (It could just return 0 or 1, but returning the value could be useful in some cases.)

In the No Results Behaviour section check the boxes for 'Count the number 0 as empty', 'Hide if empty' and 'Hide rewriting if empty'. This means when the PHP returns zero, nothing will be displayed.
In the Rewrite Results section, insert whatever output you want when the node is less than 30 days old. In the question you talk about an image, so maybe put in something such as .

Additional Notes

If you want to use different date fields etc. you can work out what to put in the PHP by switching on the display of the SQL query in preview. (See the Views settings tab from the main Views page.)

If you want a bit more control over your output, you can use the Output code box. For example the following code will put a red 'new!' label against new fields. When doing this you don't want to also have Rewrite Results set.

<?php if ($value) echo '
new!
' ?>

This code checks to see if the result of the earlier PHP code is TRUE (and not zero is TRUE). If it is is displays the red 'new!'


How do I use the Video module with Colorbox? I am using the Video module, and I want to show videos on Colorbox. I have also found a patch for that, but I don't understand something.

I am using the most recent versions.

Colorbox: 7.x-2.3
Video: 7.x-2.9

I dont know to use video module but can open a video in colorbox easily with  Video Embed Field. Just create a content type with field as Video Embed Field and in the manage display tab Select the format as 'Preview with Colorbox'.


How to modify the image output for just one content type using Responsive Images? There is a field_image (image) field on the basic content type. Using the Responsive Image, we enabled it on the Default view mode for the field_image field using a Responsive Image style.

The reason why we are setting the Image url as the data-src attribute is because we are using Lazysizes javascript library to lazyload the images. The Responsive Image module outputs using source srcset as separate tags from the img tag.

In my testing, I have found that although the browser fetches whatever size it needs to based on the Responsive Image style configuration, it does not change the image url.

How would we control the output of the image so that we can get the image to display similar to below?

Goal:

Lazy load images even while using Responsive Image Module
Output the image field so that the data-src is set, src is not set, and the "lazyload" class is added

Current situation:

<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">

</picture>

Desired Output:

<picture>
<source srcset="/image.jpg 1x" media="all and (min-width: 768px)" type="image/jpeg">
<source srcset="/image2.jpg 1x" media="all and (min-width: 320px)" type="image/jpeg">

</picture>

The responsive image module creates these with a twig template called:
responsive-image.html.twig.

You have two options to change the output.  You can either copy this template from it's location under core/modules/responsive_image/templates to your theme.

Or you can use the hook_preprocess_responsive_image() in a module or your my_theme.theme file.

Basically, you will need to change the values in the source_attributes object. E.g. grab the value of the src attributes, delete it, and add your srcset attribute with the value of the src attribute.


How to use tokens as watermark on images I need to create a watermark on images in my website. The watermark should contain a text which consists of the node ID and its author ID.

So for every image a unique watermark is created. How can I do that?

I tried the following modules so far but I am not sure if they can do what I need:

Imagecache Actions
ImageMagick
textimage
IMCE Watermark
Media watermark

I think Imagecache Actions can do what you want. Text Overlay watermarking comes default in this module. I haven't checked if it supports tokens but you'll notice it immediately if it does. Don't forget to enable the tokens module.


Why do I get these errors in my module? I am trying to use the Date module in a module I am writing, but I get the following errors:

  Warning: Missing argument 1 for myform_data_entry_form() in myform_data_entry_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).
  Warning: Missing argument 2 for myform_data_entry_form() in myform_data_entry_form() (line 28 of D:\wamp\www\drupal\sites\all\modules\myform\myform.module).

This is the code I am using in my module.

function myform_help($path, $arg) {
switch ($path) {
      case "admin/help#myform":
        return '<p>'.  t("Displays links to nodes created on this date") .'</p>';
        break;
    }
 }

function myform_menu() {
  $items['myform/data_entry_form'] = array(
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page callback' => 'myform_data_entry_form'
  );
  return $items;
}

function myform_permission(){
  return array(
    'access myform content' => array(
      'title' => t('Access content for the myform module')
    )
  );
}

function myform_data_entry_form($form,&$form_submit) {
  $form['curdate'] = array('#type' => 'date_popup', '#title' => 'Date', '#date_format' => 'd/m/Y');

  return $form;
}

Drupal forms should be called using the drupal_get_form() method, even from menu callbacks. Your menu item needs to look like this:

$items['myform/data_entry_form'] = array(
  'type' => MENU_CALLBACK,
  'access arguments' => array('access content'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('myform_data_entry_form')
);

return $items;

Make sure you clear Drupal's caches each time you make a change in hook_menu(), otherwise it won't get picked up.


How to get the NodeID from ItemID of connect Item from Field Collection I have a nodetype which is has a connected field collection (multiple values). In this case one of items of the collection is a date and I have got the ID of this one. So:

field_collection_item_load($did);

takes me just half the way home, since I still need some data of the node, hosting this collection, which in turn holds that item.

Illustration:

node // need that id
  + dates (Field Collection)
     + item (of item of the field collection)
       + ....
       + date // got this id
       + more fields
     + ...
     + more items

Any Ideas?

you may want to try hostEntity() method (link)

  Returns the host entity, which embeds this field collection item.

Then you'll be able to extract nid from the result returned by hostEntity().

but it is not clear what are you loading with field_collection_item_load($did);

is $did the id of the field_collection item - meaning the field collection and not the field in it? if so, than you can do something like this

$entity = entity_load_single('field_collection_item', $did);
$host_entity = $entity->hostEntity();
$nid = $host_entity->nid;  // returns node id of the node that hosts given field collection


Destroy Superfish plugin I have the Superfish module on my site that my main navigation uses. The site I am building is responsive so I'd like to destroy Superfish when the viewport is smaller than a specific size.

I see that superfish has a destroy method: example.superfish('destroy');

How can I use this method on my nav menu in Drupal? I'm assuming I need to do something like...

Drupal.behaviors.superfish {something here}

I have the same issue and I think this is not possible: The destroy() method was implemented in the Superfish jQuery plugin since version 1.7, but the Superfish module uses version 1.4.8 of Superfish jQuery plugin.


CKEditor with CKFinder - removing the 'Browse Server' button, but only for certain profiles I have a number of CKEditor profiles, some of which use CKFinder to upload images. However, for one profile I want to remove the option to browse the server within the CKFinder dialogue, whilst retaining it for another profile.

Is this possible?

There's a similar question answered here, but it only deals with removing the button globally (as far as I can see):

https://stackoverflow.com/questions/3610041/ckeditor-with-ckfinder-disable-filebrowser-keep-upload-functionality

In case anyone else end up on this link to look for a solution.
I am using wysiwyg, IMCE, IMCE wysiwyg api bridge, and ckeditor.

Configuration -> Media -> IMCE -> Role-profile assignments

select User-1 or any other profile according to your setting.


Making a colums total (SUM) with Views Popular Drupal 7 modules such as Views Calc and Views aggregate plus are not available for Drupal 8, so I'm struggling with achieving the following :

Making the sum of a column (of one integer field of list of child nodes) per parent node, without any custom code. No matter what I do with the "Use Aggregation" feature , I keep on getting a list of the values of entities meeting my criteria and not the sum.

Your current configuration is doing the SUM of all numbers in that field but per views row, so you'd see numbers added up within each node if you had a multivalue field.

To make it sum up across all results/nodes you need to remove the Sort criteria, that can throw aggregation off.

I don't think your second question is making sense, you want to make a reference to a value calculated within views?

Entityreference creates a list of entities, and the summed up value is not an entity, you can't reference it like that. You can create a Views block and show the summed up value on some content pages and wherever you need it. Is that what you're after?