Why print $block->content sometimes converts line break to  but sometimes does not? During debugging of a sliding animation, I found that print $block->content sometimes convert line breaks to
.

The following code in a block:

  1
  2
  3

is output in HTML as:

  1

  2

  3

Note: there are two
.

While the following code in a block (  surrounded by

):

1

2

3

is output in HTML as:

1

2

3

Note: there is no
.

How can I disable line break to
 conversion when printing block content?

This could be due to the input format you are using for the block's content region.

Assuming you are using the default input format (id 1), the filter option Line break converter is probably enabled. See admin page: /admin/settings/filters/1

You can uncheck this setting in the default input format or you can use a different input format by clicking on the Input format fieldset under the Block body content region.

If you do not have any other input formats, you can add a new one that does not use this Line break converter setting here: /admin/settings/filters/add

Note: Being able to configure or add any input format requires the administer filters permission from the filter module.


Is there a way to downsize images on upload to save server space? Ok, so I have a content type with an image field that gets cropped using the Image Widget Crop. My users will potentially be uploading images directly from their DSLR cameras which are anywhere from 8 to 12 MB each. I want to reduce them down to 1080px x 720px where they'll be around 300kb and drastically cut down on server space.

I've been using hook_ENTITY_TYPE_presave() to reduce the image size however I just discovered this is messing up my cropping. The Image Widget Crop is cropping the original full sized image but after the image size reduction in the presave hook the cropping is no longer valid.

So, is there a way I can hook into the image file as it's being uploaded to then reduce the image size before it hits the Image Widget Crop?

Alternatively, is there a way to convert the crop settings after the image size reduction?

I answered my own question and I feel a little silly. I realized resizing images programmatically is unnecessary. In the UI you can set maximum dimensions for an image that will be uploaded. I knew that but I'd never read the text underneath that mentions the image gets resized if it violates the limits. That's all I needed, no need to for me to do it in code.


How can I query by node title? In Drupal 7 I had this code to query node fields and its respective title:
$query = db_select('node', 'n');
$query->join('field_data_field_internal_institute_paper_i', 'iipi', 'n.nid = iipi.entity_id');
$query->fields('n', array('nid'));
// some other conditions
$query->fields('n', array('title')); // <- working fine for D7
$result = $query->execute()->fetchall();

which was working fine. I know imported to D9 and I need to rewrite this accordingly:
$db = \Drupal::database();
$query = $db->select('node', 'n');
$query->join('node_revision__field_internal_institute_paper_i', 'iipi', 'n.nid = iipi.entity_id');
$query->fields('n', array('nid'));
// some other conditions
$query->fields('n', array('title')); //<- not working for D9
$result = $query->execute()->fetchall();

for some reason array('title') isn't a field anymore as seen above. How can I get the title here?

This works fine in Drupal 9 for titles only from the node_field_data table:
$ drush php
Psy Shell v0.10.4 (PHP 7.4.13 — cli) by Justin Hileman
>>> $db = \Drupal::database();
=> Drupal\Core\Database\Driver\mysql\Connection {#767
     +"_serviceId": "database",
   }
>>> $query = $db->select('node_field_data', 'n');
=> Drupal\Core\Database\Query\Select {#4281}
>>> $query->fields('n', ['title']);
=> Drupal\Core\Database\Query\Select {#4281}
>>> $result = $query->execute()->fetchall();
=> [
     {#4254
       +"title": "Foo",
     },
     {#4257
       +"title": "Bar",
     },
   ]

Or for only an array of titles use fetchCol():
>>> $result = $query->execute()->fetchCol();
=> [
     "Foo",
     "Bar",
   ]

Node Field Data table:
mysql> describe node_field_data;
+-------------------------------+------------------+------+-----+---------+-------+
| Field                         | Type             | Null | Key | Default | Extra |
+-------------------------------+------------------+------+-----+---------+-------+
| nid                           | int(10) unsigned | NO   | PRI | NULL    |       |
| vid                           | int(10) unsigned | NO   | MUL | NULL    |       |
| type                          | varchar(32)      | NO   | MUL | NULL    |       |
| langcode                      | varchar(12)      | NO   | PRI | NULL    |       |
| status                        | tinyint(4)       | NO   | MUL | NULL    |       |
| uid                           | int(10) unsigned | NO   | MUL | NULL    |       |
| title                         | varchar(255)     | NO   | MUL | NULL    |       |
| created                       | int(11)          | NO   | MUL | NULL    |       |
| changed                       | int(11)          | NO   | MUL | NULL    |       |
| promote                       | tinyint(4)       | NO   | MUL | NULL    |       |
| sticky                        | tinyint(4)       | NO   |     | NULL    |       |
| default_langcode              | tinyint(4)       | NO   |     | NULL    |       |
| revision_translation_affected | tinyint(4)       | YES  |     | NULL    |       |
+-------------------------------+------------------+------+-----+---------+-------+
13 rows in set (0.00 sec)


Drupal Apache Solr How to process all the results and not only 10? I have a Drupal 7 website with apache solr search engine, and i want to access to all the results via my custom module before it is displayed, so i used this hook hook_apachesolr_process_results and as it says in it description

  This is invoked by apachesolr_search.module for the whole resultset returned in a search.

and that works good as long as your results are less then 10, but if your results are more then 10 results, then this hook will only process 10 by 10 (and 10 is the number of results that are returned in search page by default) so it only process the results that are currently displayed in the current page.

my question is there is a way to access all the results and not only the 10 results that are displayed in the current page?

Thanks in Advance

You can both preprocess, https://api.drupal.org/api/drupal/modules!search!search.pages.inc/function/template_preprocess_search_results/7 and https://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/template_preprocess_search_result/7, and theme search results (even with solr), with search-results.tpl.php and search-result.tpl.php


Views Exposed form in block : how to add a ajax results counter? I implemented a view as following :

a page display with an extensive exposed filters form (Better exposed filters), ajax enabled, let's call it the landing page
a clone of it, in a second page display with exactly the same fields, but few exposed filters instead (quick search form)
that clone has exactly the same path, Exposed form in block is set to yes

I display the clone created block (quick search form) on homepage : submitting its form redirects to landing page with correct results and the complete exposed filters. This is fine.

Question :

I need to display a results count next to the exposed form block, which refreshes each time you change a exposed filter value in the form.

The Global: Result summary in header or footer doesn't work because  footer and header aren't displayed together with the exposed block, they only come with the full view display.

How could solve that, either with UI or programmatically ? Below some ideas to begin, there might be a good and straight way :

force the results count header to be displayed next to exposed block ?
add a markup to the form with ajax results ?
create another block ?

EDIT

I tried several approaches based on Shreya answer below, but the blocking point is always the same, I need to execute the view to get result count, but as soon as I do, it returns an Allowed memory size exhausted.

in template.php :

function shoot_preprocess_views_exposed_form(&$vars){

  if($vars['form']['#id'] == 'views-exposed-form-customer-products-list-search-block') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->execute();
    $count = count( $view->result );
    $vars['count'] = $count;
  }
}

in views-exposed-form--MY_VIEW.tpl.php

print 'There are:'. $count. 'results';

And other tries with views_get_current_view() or views_get_view_result() in the tpl, also tried within form alter :

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-my-view-my-display') {
    $view = views_get_view('MY_VIEW');
    $view->set_display('MY_DISPLAY');
    $view->get_total_rows = true;
    $view->pre_execute();
    $view->preview('MY_DISPLAY');
    $view->execute();
    $content = $view->total_rows;
  }
  $form['submit']['#value'] = 'Voir les'. $content.' résultats';
}

Any clue to explain why I can't execute the view, or how to return count in that context ?

Create a folder structure as sites/all/themes/example_theme/templates/views

2.Create a file named views-exposed-form.vars where you use MYTHEME_preprocess_views_exposed_form. Code snippet below:

function example_theme_preprocess_views_exposed_form(&$vars){
  if($vars['form']['#id'] == 'views-exposed-form-exaample-page') {
    $views_rows = views_get_view_result('my_custom_view', 'page');
$count_rows = count($views_rows);
   $vars['count'] = $count_rows;
  }

}

Then you can override the exposed filter tpl. To override the
exposed form template for a particular view, you need to create a
template in the following name pattern,

views-exposed-form--view_name.tpl.php

and print the $count variable wherever you want to place the count.
Once you add the template clear the cache.


Add html to li for active-trail menu links Ive used the theme override below to add a span to the end of the li of my menu links. This is working but I need it so the span is only added to the active-train li.

function MYTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . ' Something ' . "
\n";
}

You can check if $element['#localized_options']['attributes']['class'] contain active-trail class and create your custom span based on this information.

function MYTHEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $span = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if (isset($element['#localized_options']['attributes']['class'])) {
    if (in_array('active-trail', $element['#localized_options']['attributes']['class'])) {
      $span = 'Something';
    }
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . $span . "
\n";
}


Show active taxonomy term as title of product category view Commerce kickstart comes with a view named Collection products that shows: a Collection of products (Product display).
In the relationship's tab of this view there are 2 relationships:
1. Product category field_product_category
2. Belongs to Collection field_collection.
The contextual filter is set to: Indexed Node: Product category (field_product_category) and the path to this page is product_category/%.
There is a menu block showing above this view that comes from the same view showing all the category terms as links.
When you click them, you see that the view shows correctly all the products referring to that term.
My problem is that the term that is active (e.g. url: category/beef) doesn't show as a title right above the view or in the block.
How can I achieve that?

Edit your Contextual filter and you'll see the option to override the title in the section for when the filter argument is present or a default is provided.

You can use tokens from the Replacement patterns section to construct the title text.

Your "menu" is likely also coming from the Contextual filter, set to the "Summary" option.

Another way is to add the title in the Views Header, you can see how it's implemented in the "Taxonomy term" Views.


Is it still possible to use a custom attribute for a form (e.g. $form['#foo'])? In the documentation for #value, the Drupal 7 documentation contains the following note:

  Note that as of Drupal 6, you can also simply store arbitrary variables in $form['#foo'] instead, as long as '#foo' does not conflict with any other internal property of the Form API.

Is that still possible, in Drupal 8?

I looked at the documentation for the Value class, but the note given for Drupal 7 is not present.

I know Drupal adds $form['#token'] to forms, but I take it is a special case Drupal handles in a particular way.

See FormCache::setCache(). The whole $form is put in the cache, anything that's in there is stored and fetched again.

That said, I would definitely advise against using it. The recommended and standard way to store something is $form_state->get()/set().

Also be aware that while this still works when the form is cached, Drupal 8 only caches form/form_state once an actual form submission happens. Usually that means only for ajax requests and in case of form validation errors (although I don't 100% know how it behaves then).

That means you can not put something in $form['#whatever'] or $form_state->set('whatever, ...) on the first form build and expect it to stay there.


Route that renders a node has title of route rather than node title I have a route that takes a wildcard $product and then loads a default node that is stored in config. This is working (i.e. the node is rendered on that path) but instead of the node title it is displaying the route title 'Default Product List'.

Any ideas?

Routing.yml

default_product_list.generate_default_product_list:
  path: '/destinations/{region}/{area}/{town}/{product}'
  defaults:
    _controller: '\Drupal\default_product_list\Controller\DefaultProductListController::generateDefaultProductList'
    _title: 'Default Product List'
  requirements:
    _permission: 'access content'
  method: [GET]

Controller

 /**
   * Generatedefaultproductlist.
   *
   */
  public function generateDefaultProductList($region, $area, $town, $product) {

    $vars = [
      $region,
      $area,
      $town,
      $product
    ];

    $config = $this->config('default_product_list.defaultproductlist');

    $data = $config->get();

    if ($product === 'accomodation') {
      if (isset($data['default_accomodation_product'])) {
        $node = $this->defaultProductListUtility->loadDefaultNode($data['default_accomodation_product']);
        if (isset($node)) {
          $view_builder = $this->entityTypeManager()->getViewBuilder('node');
          $build = $view_builder->view($node);
//          kint(array($build));
          return array($build);
        }
      }
    }

  }

As it is routing path, Drupal will always look for the title in routing.yml, if you want to set title for this you can do as follows,

$build['#attached']['html_head'][] = [
    [
      '#tag' => 'title',
      '#value' => "Node title"
    ],
    'title'
  ];

OR

$build['#title'] = 'Node Title';

Here you can replace "Node Title" with your dynamic node titles.


User logout on browser / tab close How to modify Drupal user's cookie so the cookie is not available anymore after a predefined time or when the user close his web browser or close all of the websites pages open in tabs ?

After some online searches i found that by setting the cookie lifetime to 0 should create temporary cookies that would be deleted once the browser is closed:

I first tried by modifing some ini_set() values in the settings.php :

ini_set('session.cookie_lifetime',  0);
ini_set('session.gc_maxlifetime',   0);

I created a php.ini file located at the drupal site root, containing:

session.cookie_lifetime = 0;

But it does not work on my test site. Any ideas?

You can change this setting directly in the settings.php. You've a line that looks like that :

ini_set('session.cookie_lifetime', 2000000);

Change 2000000 to 0 and you will get what you want.


scale image in Drupal I need to scale image in Drupal 7.
IF the width is greater than the height, THEN scale the image to 200px height.
IF the height is greater than the width, THEN scale the image to 200px width.
and if the width and height are the same, scale to 200x200.
Please help me out.

I believe this module will do the trick:

ImageCache Actions

  Effects provided

  ...

  Aspect Switcher - lets you perform different actions or use different    dimensions based on whether the image is 'landscape' or
  'portrait'


Does hook_node_access_records() and hook_node_grants() change permissions for existing nodes? When I install a new module containing hook_node_access_records() and hook_node_grants(), Does it change permissions for existing nodes? Or it affects only on new nodes?

If it doesn't change permissions for existing nodes, Is there a way to rebuild node_access table?

You can implement hook_enable() and call node_access_needs_rebuild(TRUE), see user_relationship_node_access_enable() for an example.

That doesn't actually do much on its own, but Drupal will then automatically print a message to administrators and inform them that the permissions need to be rebuild and also includes a link to the place where this can be done.


multidimensional tableselect Is it possible to create a multidimensional tableselect (table with checkboxes)?
Why? I would like to show a tableselect of all menu links to delete one or more but a nested tableselect.

So if they want to delete a link, all child-links will be selected to. I know i can just delete all children with a query, but for the user I want to visualise which part of the tree will be deleted.

Output ex.:
=> CB = checkbox

CB link1

CB  link 2
CB  link 3

CB  link 4

CB  link 5

CB link 6
CB link 7

CB  link 8

... and so on.

If you are looking to delete children as well with parent menu items seems like Delete menu options address this issue..

Project page says

  On the 'Delete menu item' confirmation page you can choose to delete
  child menu items and decide if the linking nodes should be deleted as
  well. When the checkbox 'Delete all children of this menu.' is
  checked, all child menu items of the parent menu item to delete, will
  be deleted as well. When the checkbox 'Delete nodes of the deleted
  menu items (only orphaned nodes).' is checked, the nodes to which the
  child menu items link will be deleted too. When other menu items link
  to same nodes or aliases as the nodes which were set out to be
  deleted, those nodes will not be deleted.


What is the correct way to programatically set node type options? I learned yesterday that the correct way to create a node type is by implementing hook_node_info inside a .module file. Before I had been programatically creating node types in a .install file via node_type_save, like this:

// Create node type
$type = array(
  'type' => 'fruits',
  'name' => st('Fruits'),
  'base' => 'node_content',
  'description' => 'Contains information about fruits.',
  'custom' => 1,
  'modified' => 1,
  'locked' => 0,
);
$type = node_type_set_defaults($type);
node_type_save($type);

I had also been setting the node type options in the .install file, like this:

// Set 'fruit' options.
variable_set('node_preview_fruit', 0);                     // Set 'Preview before submitting' to 'Disabled'.
variable_set('node_options_fruit', array('status'));       // Set 'Default options' to 'Published'.
variable_set('node_submitted_fruit', 0);                   // Unset 'Display author and date information'.
variable_set('comment_fruit', COMMENT_NODE_CLOSED);        // Set 'Default comment setting for new content' to 'Closed'.
variable_set('menu_options_fruit', array('navigation'));   // Set 'Available menus' to 'Navigation'.
variable_set('menu_parent_fruit', 'navigation:0');         // Set 'Default parent item' to '<Navigation>'.

Is this the correct way to programatically set node type options: like this, inside the .install file, even though the node type itself is created inside the .module file?

Looking at the code for node_type_form_submit you can see that the variables are set before the node_type_save() function is called. Thinking about it a bit, it doesn't really matter as the node type info is saved into a different table than variables. So as long as the variables are being set synchronously with the creation of the node type, it shouldn't matter. Even then, the worst case scenario would be you'll have some redundant variables in the variables table. Which is not a big issue.

So to answer the question, yes that's the proper way. However I'd do it in the same function call in the .install file, maybe implement it in hook_install or hook_enable depending on what you need.


{{ directory }} not available in parts of menu--main.html.twig Printing {{ directory }} at the start of the file works fine. But a bit further it's no longer availble:

{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
    **{{ directory }} {# THIS WORKS #}**
    {% import _self as menus %}
    {% if items %}
        {% if menu_level == 0 %}

        {% else %}

        {% endif %}
        {% for item in items %}

                **{{ directory }} {# THIS DOESN'T WORK #}**

                {{ item.title }}

        {% endfor %}

    {% endif %}
{% endmacro %}

Any idea why this happens and how to fix it?

The second occurrence of {{ directory }} is within a Twig macro. As the Twig documentation mentions, you cannot access the outer variables in a macro:

  But as with PHP functions, macros don't have access to the current template variables.

You can however pass _context through a macro parameter and access directory that way, or pass it explicitly.


Upload images in ckeditor for free After following instructions given here: https://drupal.org/project/ocupload#install-swfupload
I got an upload button. Further it is possible to upload images within the backend. After saving the page there are visible as well.

But if I call the page in frontend there's text only.

Is there a way to solve my problem for free?

ubuntu 12.04, drupal 7.28, ckeditor 4.4.1, firefox and chromium newest release

This problem is probably related to the text format used when the page containing the image is rendered.

If the text format used is "Filtered HTML", you should try to change the format for the node to "Full HTML".  If this change makes the missing images re-appear, the problem is the text format.

If only trusted users are allowed to insert images in nodes, you can fix the problem by changing the default text format from "Filtered HTML" to "Full HTML".  However, it is not recommended to allow untrusted users use this text format, as it allows XSS attacks.

For a secure configuration where untrusted users can insert images, you need to use a better filter module that the default "Filtered HTML".  You can do this by installing the WYSIWYG Filter module as is decribed here.


user relationships - add friend link in a content-profile node I have installed the User Relationships module, and I have questions about how it works.

When you install the module, a "relationships" link should be added in a user profile page (users/myname), but in my case it doesn't; I've modified user-profile.tpl.php, and cleared the cache, but still the link doesn't appear. What's wrong?

How can I add a link to "add/remove friend" on a content-profile node of user? And also how to output list of user's friends? I guess a view block would help me in this situation.

I followed the instructions that I found in the documentation of the module, and everything worked absolutely perfect. The steps for your reference were:

Enabled the modules: UR-API, UR-Mailer, UR-UI, UR-Views
Created a new relationship (e.g. friend)
In Permissions make sure that you have enabled the can have relationships permission in the user_relationships_api module (this is what I forgot the first time)

The rest of the permissions are pretty straight-forward. If you follow the instructions to the letter, you will get the link in the user profile page.

P.S: The guide in the above-mentioned link has a screenshot for the required permissions: make sure that your permissions match this screenshot's EXACTLY.

As for the block that you want to create:

Enable the UR-blocks module. It creates sample useful blocks (including a block for each relationship that you created). You can insert this block directly in the profile node using the corresponding tpl.php file and a code like the one that you can find in this article:

Drupal - How To Display Block In Node?


Are .module files still required? I noticed that, in the current page crumb module, there is no .module file.

Why is that no longer necessary? As a test I added a .module file, but it seems it is not being read.  Where can I find documentation about using or not using a .module file in Drupal 8?

.module files are not required if you are not adding any procedural code. If you need to use any hooks, like hook_theme or hook_form_alter, yes, you need to do that in the .module file, because it cannot be done anywhere else. A lot of modules that extend base classes or provide services don't have any need to also include a .module file unless they provide something via hook_help, for example.

Some developers provide empty .module files, like:

<?php

// empty

I simply omit them if they have no code.

  And as a test I added a .module file but it seems it is not being read.

You'd have to elaborate on this, because any module that is enabled that has a .module file is definitely read. You may have to clear cache to pick up on changes.


File upload functionality on node display page I want to provide an upload button on a node display page. By clicking a button, it should be possible to upload files. Here is what I'm thinking of:

For this I am changing the node.tpl file.

 <?php //code added
     if($node->title=='Course Materials'){?>
        <form action="" name="uploadform" >
            <input type="submit" value="upload" name="upload"/>
        </form>
    <?php  }
    if(isset($_REQUEST['upload'])){ ?>
    <form  method="post" action="" enctype="multipart/form-data">
        <input type="file" name="file"  />
        <input type="submit" name="submit"  />
    </form>
     <?php //end
     }?>

And to save the files:

  if(isset($_REQUEST['submit'])){
    if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){

   //$file = $_FILES['file']['tmp_name'];
   move_uploaded_file($_FILES["file"]["tmp_name"], "C:/xampp/htdocs/drupal6upload/sites/default/files/".$_FILES["file"]["name"]);
    $node = node_load($node->nid);

        // Build the file object
        $file_obj = new stdClass();
        $file_obj->filename = $_FILES['file']['name'];
        **$file_obj->filepath = "C:/xampp/htdocs/drupal6upload/sites/default/files/".$_FILES["file"]["name"];**
        $file_obj->filesize = $_FILES['file']['size'];
        $file_obj->uid = 1;
        $file_obj->status = FILE_STATUS_TEMPORARY;
        $file_obj->timestamp = time();
        $file_obj->list = 1;
        $file_obj->new = true;

        // Save file to files table
        drupal_write_record('files', $file_obj);

        // change file status to permanent
        file_set_status($file_obj,1);

        $node->field_test1[] = (array)$file_obj;
        node_save($node);

        drupal_goto('node/'.$node->nid);
    }
}

But I am facing some problem to set the filepath and file_copy instead of move_uploaded_file.

Any suggestions?

I am able to do it by creating custom module.

    function upload_course_form($form_id) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['course_materials'] = array(
            '#type' => 'file',
            '#title' => t('Course Materials:'),
            '#size' => 60,
            );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
        '#weight' => 10
    );
    return $form;
}

  function upload_course_form_validate($form, &$form_state){
  $field = 'course_materials';
  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array('file_validate_extensions' => array('pdf xls html doc txt docx'));
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}

function upload_course_form_submit(&$form, &$form_state){
print_r($form_state['storage']['file']); //see the upload file details
//and add the code to save the node.

}


What to do when there are defined constans in a module and you need to change it I have installed a module. In the module there are no configuration options. In the code of the .module, there is a cache time which is set to 20 minutes, in a constant. I need to refresh the data printed by the module with a cache of less than a minute (say seconds). The only solution I have found is to manually change the code and put a value define ('THIS_MODULE_CACHE_LENGTH', 0.1); //-- cache for 6 seconds. Is there another way of doing? Is it a bad designed module? (I do not mention the name if that is the reason). Please advice, because I am worried that with an upgrade to the module I will obviously loose the performance and will recover that excesive 20 minutes times (the module is for content which can upgrade very frenquently, so I do not understand the 20 minutes). Thanks!!

Is there another way of doing?

Depends where it's used. If the use is hardcoded into a function that doesn't offer any altering, then no, there's no other way other than a hack to change it.

Constants are constant, if they could be changed then they wouldn't be constant any more; if someone has used a constant they should have had a very good reason for doing so. So it's up to you to decide whether you trust the knowledge and design decision of the author. If you don't, don't use the module. Or change it to what you know is correct or reasonable.

At the very least, open an issue to ask the maintainer why they've hardcoded that value. There may have been a very good reason.


How Can I Prevent Webform Being Displayed in Front Page I've installed panopoly distribution and Webform module. I've also created a webform called contact form and added the contact form in a pane as a block. The problem is: The contact Form (webform) is being displaying in the front page as new content.

I've also tried various settings including:

Untick all options from publishing option (Administration » Structure » Content types » Webform)

to remove that but nothing works.

How can I remove webform from being displayed in the front page in Drupal 7?

The publishing options at Administration » Structure » Content types » Webform are defaults. Edit the particular webform node and uncheck "Promoted to front page".


Change the default value of the node reference via hook_alter_form field_userid is a user reference field with an autocomplete widget

i want to set the default value of this field, but the code below doesn't work

Does anyone can help me?

Thank you very much!

 function mymodule_form_node_form_alter(&$form, &$form_state, $form_id)
    {
        global $user;

        if($form['#node']->type=="article")
        {

            $form['#after_build'][]='mymodule_after_build';

        }
    }

    function mymodule_after_build($form, &$form_state)
    {
        global $user;

        $form['field_userid']['#default_value'][0]['uid']=$user->uid;

        return $form;
    }

I can't think of any reason why your code would need to be in an after_build function, you would usually put it straight into the form alter hook. At the moment you've got the array keys the wrong way round. Without being able to see the structure of your form it's difficult to say exactly where the correct element is, but one of these should work:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  global $user;

  // Try this one
  $form['field_userid'][LANGUAGE_NONE][0]['#default_value'] = $user->uid;

  // Or this one
  $form['field_userid'][LANGUAGE_NONE][0]['uid']['#default_value'] = $user->uid;
}


Block Plugin Derivatives Discovery I need some help with my code. I am creating blocks dynamically using the plugin derivatives. I store some form data in a database table, then I display it in each block separately, depending on it's derivative id. My issue is: while, I do obtain all the individual blocks on a full clear cache, in the "Place Block" section, it's not there when I submit the form, basically, I would like the form submit function to trigger the derivative creation and it's discovery. Any suggestions appreciated.

Here's my Plugin Derivative code:

<?php

namespace Drupal\simpleads\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class SimpleAdsBlock extends DeriverBase
{
    public function getDerivativeDefinitions($base_plugin_definition)
    {
        $query = \Drupal::database()
            ->select('simpleads_blocks', 'sb')
            ->fields('sb');
        $results = $query->execute()->fetchAll();

    foreach ($results as $result) {
        $this->derivatives[$result->bid] = $base_plugin_definition;
        $this->derivatives[$result->bid]['admin_label'] = $result->name;
    }

    return $this->derivatives;
    }
}

Copied from BlockContent::postSave():

// Invalidate the block cache to update custom block-based derivatives.
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();


unable to extract dumped files in .tar extention on my site I can't extract my backup dumped with .tar extention. so i can't work with features
can I download features in .zip ?

No. Tar is what's supported.

Downloading the files I generally feel is a pain though, I would encourage you to look at managing the features with Drush instead. It's often a lot faster as it mostly enables you to skip the whole download step.


How do I set up the Crumbs trail For Commerce Kickstart Checkout? Using Crumbs 7.x-1.10

During Checkout, the standard flow is 3 pages:

Cart ---> Shipping ---> Review

But at that last (3rd) step the Crumb trail shows

Home > Checkout > Checkout > Checkout

How do I set the Crumb trail to reflect the page H1s?

Is this done via the standard Setup page or 2. Does it require a plug-in? And if a plug-in can someone give me an example for this use case? Frankly, I'm having trouble understanding the nomenclature of both the std. Setup -and- the plug-ins of the docs.

You will have more luck with Crumbs 7.x-2.*.

See also

Use Crumbs 7.x-2.*, or tell people how to upgrade. (Kickstart queue)
Commerce Kickstart Checkout Use Case (Crumbs queue)


Theme settings to include different PHP files into template I'm trying to include a template section into another template under conditions based on the themes settings.

page.tpl.php

    <?php
    $theme_header_style = theme_get_setting('header_style');//the value is 1
    $header_path = "header_tpl_".$theme_header_style.".php";
    include_once $header_path;//includes header_tpl_1.php
    ?>

<?php print $site_name; ?>

header_tpl_1.php

this will show up

<?php print $site_name; ?>

this will show up on page.tpl.php as well

I'm pulling in header_style from my themes settings and for this example the value is 1. The file it will include is being added, as the html from the file is displaying but any php in the file is being ignored. anything on page.tpl.php is working as expected its only the php content on included files like header_tpl_1.php that is not working.

Update

Now that I know using a PHP include doesn't work I would like to know how I could include the contents of the header_tpl_1.php into the template prior to Drupal rendering the page, as this clearly would be the solution. The end objective is being able to load different PHP files into page.tpl.php based on a value set in the themes settings. The code in my header_tmp_1.php was removed from page.tpl.php as working code and put into header_tpl_1.php so I know there are no errors in it, as it works if it's added directly into page.tpl.php. The problem is including content into a template. I need the content to be included prior to Drupal rendering the variables.

Did you cleared cache ? I usually include header.inc, but I try your code and it worked on my site.


Clean URLs with multi-site only with suffixes / sub-folders In D7 Multisite, I'd like to use clean URLs. However, these sites share the same domain but have different folder names.

For example, the login pages would are currently

https://domain.ext/red/?q=user
https://domain.ext/pink/?q=user
https://domain.ext/green/?q=user
https://domain.ext/purple/?q=user

How might I set this up to allow clean urls and have login pages as such:

https://domain.ext/red/user
https://domain.ext/pink/user
https://domain.ext/green/user
https://domain.ext/purple/user

The .htaccess file is untouched. The apache config file /etc/httpd/conf.d/aliases.conf contains:

Alias /blue /var/www/html
Alias /pink /var/www/html

And inside of /var/www/html/sites/ I have folders

/var/www/html/sites/blue
/var/www/html/sites/pink

Can I accomplish this by editing the $baseurl in each settings.php file and adding a redirect per site in .htaccess?

think you will require a separate virtualhost entry for each of the sub-sites.  That should direct visitors to the correct location and negate any need for redirection.

At the moment you're using aliases to effectively send all traffic to the same place, I think using virtualhosts will separate the traffic a bit better and help you turn on clean URLs.

I'm going to assume your core Drupal files are at /var/www/html.

You definitely need to read the documentation in /var/www/html/sites/sites.php and set that up if you haven't already.
You do need to set the $basepath in each site's settings.php
In Apache it kind of depends what OS you're using but you basically want to turn on NameVirtualHost in Apache and then tell it where to send visitors:

Here's how to do it in Ubuntu
Here's how to do it in CentOS which probably also translates to RHEL/Fedora

Those links give the full setup, so you've probably already done the first few steps.  Keep going down the page to find the Virtual Host section.

Finally, clean URLs need to be enabled in each of your sites, one by one.


Adding a view to a panel Running Drupal 7, Views 3 and panels 3

Been searching for an answer for this for a few hours now and I can't seem to find one. I am creating a custom user profile page in panels. I created a view to display certain fields from profile2 if that user is of that role. When I test the view at the bottom of the views page by passing it an id it works fine. here are the settings:

Contextual filters:
Node:Nid

Relationships:
Content:Author
(author) User: Profile

Now in panels when I add this view I have the heading Content: Nid with a drop down list in the options. I select the information I want to display and save. Then when I go to the profile page, nothing shows up. I don't think it is passing the nodeid to the view, but I am not sure what I haven't done.

If you create the view as a content pane (panel pane), you are able to select options used in panels on how to receive the context params, (Like from a Panel context of type Node). When adding the content pane in Panels you also get to select which variables should be sent to the view. This is probably what you are missing.


Set amount of fields on an existing content type One of our website requirements is to have a content type that lets you decide on the total amount of form fields on the fly.

For example, if I specify a number 10, then it ought to generate the form fields consecutively; the text area and the checkbox form fields are created 10 times.

Essentially, to break it programmatically, it will create:

for(i = 0; i < 10; i++) {
  echo "<input type = 'textarea'></input>";
  echo "<select><option>1</option><option>2</option></select>";
}

This is pretty straightforward if I was dabbling with simple PHP files, but with Drupal 7's fields it is posing a bigger challenge than what it ought to be. I have tried exploring modules that let you create content types on the fly and considered creating a custom content type programmatically which seems like another challenge altogether.

I am curious if anybody has an alternative for this, and has dabbled with this challenge before.

If I understand you correctly, you're trying to change the cardinality of a field based on user input. You can do this by using field_update_field():

$field_name = 'field_bar';
$field = field_info_field($field_name);

$field['cardinality'] = 10;  // Change to number you want

// field_update_field() throws an exception on failure
try {
  field_update_field($field);
}
catch (Exception $e) {
  drupal_set_message(t('Could not update field.'), 'error');
}

As you can see, cardinality is actually a per-field setting: if you wanted to do this on a per-instance basis (so, separate cardinality for the field for each content type/bundle), you actually need to create an entirely new field for each bundle.

This would likely cause a number of issues, particularly if you wanted to do things like display the values in a view (each field would be handled separately, even though the only thing different is the name and the cardinality).

Instead, what I'd do is just set the cardinality of the field you want to be dynamic to "unlimited" (FIELD_CARDINALITY_UNLIMITED in code): out of the box you get a fancy widget that lets users add as many values as they'd like.


Module/Method to cleanup content of Drupal site? I have been assigned with the task of maintaining a specific Drupal site. The problem is that the person who created the website did not actually think it through. No input filters to be heard of, no restriction for images' placement, plain HTML everywhere.

I'm now on the spot, since I've promised to tidy up the website, and I've just realized how much work will it require. There are articles that are copy+pasted from wikipedia (the WYSIWYG editor kept all the formatting), random websites or (even worse) from MS Word.

I understand that I will have to do some manual editing and check the articles one by one, but I was wondering if there is some kind of a method that someone may have used in a similar situation. Perhaps a module that will cleanup the html of the various nodes?

Note: The website is built in Drupal 6, but if you have suggestions for Drupal 7, I guess that I could upgrade.

Normally, when I have encountered this, there is too much variety to do much automated cleanup.  You can do something like this, though

$sql = "
  SELECT n.nid
  FROM {node} n
";

$result = db_query($sql);

while ($row = db_fetch_object($result)) {
  $node = node_load($row->nid, NULL, TRUE); // bypass internal cache
  $node->body = _filter_htmlcorrector($node->body);
  node_save($node);
}

Either stick this in a custom menu entry or make a simple script for it.  Depending on how many nodes you have, you may need to use the Batch API.

_filter_htmlcorrector will fix bad HTML to an extent, and I have also used check_markup with luck, too.  For check_markup, you just need to figure out the numeric filter number to use.

Other than that, you really do need to play with the processing you do in the loop.  This will give yourself a head start, but you still need to edit each article and manually check/fix things.


Views two content type relations I have two content types.
1. Referrals: Name, other info type fields
2. Referral semesters: start date, end date

I want to list all referral semesters out while counting the number of referrals there were in between the referral semesters start and end time. Looking at the referral creation date.

I've started a view of semesters but see no where I can relate it to referrals in the relationship area.

example:
Spring 2016: 17
Summer 2016 : 22

I think the entity reference view may help you in this case.

Ref: http://codekarate.com/daily-dose-of-drupal/entity-reference-view-widget


"File not found error" when installing using composer I'm running Docker on Ubuntu 18 with a container for MariaDB, Nginx and php-fpm (7.3).
The PHP container has composer installed, and I used it to create a Drupal Commerce project. I can start the Drupal install process using a browser, but after I input the DB settings, the process fails and I get the following error.

  An AJAX HTTP error occurred.
  HTTP Result Code: 404
  Debugging information follows.
  Path: /core/install.php?profile=commerce_base&langcode=en&id=1&op=do_nojs&op=do
  StatusText: Not Found
  ResponseText: File not found.

Increasing the execution time, post time, memory limit, post and upload sizes in the php.ini file, as recommended by another user, didn't solve the problem.

Nginx error log contains the following message.

  [error] 6#6: *46 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream'.

The database has tables and data in it, so I know the database credentials are correct.

What am I doing wrong?

Yes, it turns out it was an Nginx configuration problem. In my docker-compose.yml file i have:

web:
  volumes:
    - '/server/path/to/html:/usr/share/nginx/html'

php:
  volumes:
    - '/server/path/to/html:/var/www/html'

In my site.conf file, i had:

fastcgi_param SCRIPT_FILENAME project/$fastcgi_script_name;

Not sure why this worked for the initial php files i tested but then failed during the installation. Changing this line to the full path as follows solved the problem for me:

fastcgi_param SCRIPT_FILENAME /var/www/html/project/$fastcgi_script_name;


How to customize the output of node content in Drupal 6? I am looking to customise the templated output of the $content variable in node.tpl.php Can you tell me how I could achieve this? Is is possible with another template file?

The reason for this is to achieve AJAX pagination thus I need an ID on node_body and also to pull out the paging nav from this same DIV.

Any help appreciated :)

These are the available them files where you can get $content

  node--[type|nodeid].tpl.php

  base template: node.tpl.php

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

  node--nodeid.tpl.php

  node--type.tpl.php

node.tpl.php

See node.tpl.php in the Drupal API documentation for more information.

Drupal 7 Template (Theme Hook) Suggestions


How can I send an email using the Rules module to a user specified via Entity Reference in a Content Type? This question is similar to others posed, but all the answers I can find appear to refer to Drupal 6, with CCK fields.

I am using Drupal 7 with the Rules module enabled.

I have created a custom Content Type and one of the fields is an Entity Reference, which allows a registered user to be selected as the Content Type is added. Essentially an administrator can associate a registered website user with the content item being added.

I need to email the referenced user when another field value within the Content Type is changed. I'm sure this is possible via the Rules module, but I cannot get the mail to send.

It must be a fairly common situation, emailing a referenced user when a field value is updated, but I have looked at the online notes for the Rules module and cannot find an example of this particular use case.

Has anybody managed to achieve the same outcome as I am seeking?

Thank you.

After some trial and error, I found how to reference the field.

Within the Conditions section of the rule, I needed to:

Add "entity has field"
Enter "node" within the Data Selector box
Select the entity reference field within the Value dropdown

I was then able to refer to the field required, with the mail parameter appended, directly from a standard Send Mail action (i.e. [node:MY-REFERENCED-FIELD:mail]).


Loading of assets via Libraries API I'm writing a new module which has a dependency on an external library. In Drupal 7 I would use hook_libraries_info giving the name of the library the required assets and Drupal would search the valid locations, libraries directories, to load these assets when required. Drupal 8 introduces *.libraries.yml and after reading https://www.drupal.org/node/1996238 it seems that module developers must now provide a path, relative or absolute, to the required assets.

In my case I will be expecting site builders to download the external library - where should libraries be located in Drupal 8?

hook_libraries_info is not in core, it is from a contrib module:

Libraries API

This module provides the external libraries. It will be ported to drupal 8 and can be used the same way as in drupal 7.

In drupal 8 the libraries, that are defined in *.libraries.yml are seperate and should not be confused with the external libraries, despite their identical name. They are mainly for js and css packages, that are specific to one module, but can also be used by other modules. They can be a replacement for the external libraries, but do not provide the full functionality.

In the long run composer will probably be the way module developers will go for downloading external libraries. But for now this is an ongoing discussion how this can be implemented.

Your reference to https://www.drupal.org/node/1996238 is a seperate issue about the replacement of hook_library_info() in drupal 8 core. This must not be confused with the external libraries defined in hook_libraries_info().


Views: How do you view the query? How do you view the query that a 'View' is using to gather data from the database?

Go to admin/structure/views/settings, check Show information and statistics about the view during live preview and then Show the SQL query checkbox that will appear below.


Cannot install bootstrap theme in drupal 8 via composer fresh install I set up d8 site with:

composer create-project drupal-composer/drupal-project:8.x-dev my_test_site --stability dev --no-interaction

Then installed the db and drupal with:
drush site-install

Fully working D8 (8.3.3) with no errors at all.

I go to curate the composer.json file with some themes and modules to play around with it to get familiar:

composer require drupal/bootstrap

When this command runs, it results in the following error:

  Could not find package drupal/bootstrap at any version for your
  minimum-stability (stable). Check the package spelling or your
  minimum-stability

Inside my composer.json (after install)

{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0+",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/console": "~1.0",
        "drupal/core": "~8.0",
        "drush/drush": "~8.0",
        "webflo/drupal-finder": "^0.3.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
        "behat/mink": "~1.7",
        "behat/mink-goutte-driver": "~1.2",
        "jcalderonzumba/gastonjs": "~1.0.2",
        "jcalderonzumba/mink-phantomjs-driver": "~0.3.1",
        "mikey179/vfsstream": "~1.2",
        "phpunit/phpunit": ">=4.8.28 <5",
        "symfony/css-selector": "~2.8"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
      "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        }
    }
}

I've followed the solutions on  Installing Bootstrap theme using Composer , but it seems all the answers are all defaults already in my installation unless i'm missing something?

I've tried several different combinations of versions available for the bootstrap theme and it's the same message every-time. I have also tried to change my overall projects stability with no luck.

I'm not too familiar with composer so I am assuming I am missing something small. Going through the documentation I am literally finding nothing to help solve this issue with composer. I have had no issues installing bootstrap before everything was on packages.drupal.org

Any ideas to why I cannot install bootstrap theme as a dependency or am I approaching this entirely wrong?

Sounds like you're in the <project_root>/web folder. You need to be in <project_root> when using the Drupal Project to manage modules.

Just cd .. and run composer require drupal/bootstrap again, it should be fine.


Converting a Views SQL query with INNER JOIN to an EntityQuery I'm trying to create a custom JSON:API resource that returns the entities that have been flagged by a user.  (The Flag module does not offer a way to get this out of the box.)
I used Views to build a query to show all terms flagged by the user:
SELECT taxonomy_term_field_data.tid AS tid, flagging_taxonomy_term_field_data.id AS flagging_taxonomy_term_field_data_id
FROM
{taxonomy_term_field_data} taxonomy_term_field_data
INNER JOIN {flagging} flagging_taxonomy_term_field_data ON taxonomy_term_field_data.tid = flagging_taxonomy_term_field_data.entity_id AND (flagging_taxonomy_term_field_data.flag_id = 'MY_FLAG' AND flagging_taxonomy_term_field_data.uid = 'MY_UID')

Then, I installed the JSON:API Resources module and configured a custom resource.
However, JSON:API uses EntityQuery, not regular SQL queries.
So based on my very limited knowledge of SQL, I wrote a basic query to get all the terms:
    $query = $this->getEntityQuery('taxonomy_term')
      ->condition($entity_type->getKey('bundle'), 'MY_VOCABULARY');

Now I want to restrict this to the terms that have been flagged by the user.  How do I implement the INNER JOIN in the Views query in EntityQuery?

You can try hook_query_TAG_alter
Sample code
$query = $this->getEntityQuery('taxonomy_term')
  ->condition($entity_type->getKey('bundle'), 'MY_VOCABULARY')->addTag('join_flaging');

/**
 * Implements hook_query_TAG_alter().
 */
function MYMODULE_query_join_flagging_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->addJoin("INNER","flagging","flg","taxonomy_term_field_data.tid = flg.entity_id AND (flg.flag_id='MY_FLAG' AND flg.uid='MY_UID')");
}


Checking what user a migration is running as I have a single migration out of a larger group, that needs to be run as the administrator or an entity reference fails to map the User entity properly.  I'd love ideas on what I might change so that I wouldn't have to be an administrator to entity reference users, but failing that:

How can I check what user the migration is currently running as?  Basically I want to be sure that drush has been invoked with --user=1 or throw an exception with a reminder that this migration needs to be run as administrator.

In the interest of trying to up the percentage of Drupal Questions that have an answer, I'll post the solution that I came to as a result of Clive's comment.

I added a preImport and postImport method to my migration class as follows:

  public function preImport() {
    parent::preImport();
    $GLOBALS['user']->previousid = $GLOBALS['user']->uid;
    $GLOBALS['user']->uid = 1;
    if ($GLOBALS['user']->uid != 1) {
      throw new MigrateException('Run Staff Contributor Migration as user 1.');
    }
  }

  public function postImport() {
    parent::postImport();
    $GLOBALS['user']->uid = $GLOBALS['user']->previousid;
  }

This ensures that this particular migration is run as user 1 and returns the user value back to whatever it had been at the end of the migration.  It also throws an exception if for some reason the user switch failed.


Views relationships with two views blocks I am trying to connect two different block views so as when you click the title of the first view block the second block will display the content of the url. Both views are of the same content type. How do i do this? or any usefull tutorials i can count on?

EDIT:
I have this company news page which is accessible from the main menu so that's why i wont to keep the same url. So i created a content type called company news and two views. The first view will display the date and the title of the company new and the second view block will display the content of the company new clicked. My first view is like a left-hand side bar with the 10 newly added. So if a user clicks for example at the second company new the second view block willk display the content of that new. I hope i made it more clear!

In this case I think you need one view who shows title, date and body.

So now you will have a full list of all the news and through jquery you can do something like this.

 $('.field-name-body').hide(); //it hides all the body fields.
 $('.views-row').click( function() { // The body is a children of the row.
$('.field-name-body').hide(); // it hides all the open body fields if there is one.
  $(this).children('.field-name-body').show();
});

Do you want something like this?
Fix the css with more specifications (view name, block name...)
With the css you can do the style you want.

If you want to have two different blocks you need to show in one view all the title fields and in the other view all the body fields.
You don't need contextual filter for the second view (a part from the company id). You will show all the body fields and then hide them.

Now you need to change the files views-view-unformatted.tpl copy it from views/theme, paste it into you template folder inside your theme and rename it with the name of the view.
To find the name of that view, you have to open your view, on the third column you click on theme and you will see the files and the suggested name to specify that view (views-view-unformatted-YOURVIEW-BLOCK_1.tpl or something like this). Do it for both views block, they have to be different, one could finish with block_1 and the other with block_2.
Clear the cache after you rename the files.
In the views you can add the node id and exclude it from display.

This is views-view-unformatted.tpl

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

AND YOU CAN MODIFY ADDING THE ID IN THIS WAY WITH $view->result[$id]->nid;

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>" id="<?php print $view->result[$id]->nid; ?>"> // in the body view use body-id
    <?php print $row; ?>

<?php endforeach; ?>

So, now again the js

$('.field-name-body').hide(); //it hides all the body fields.
$('.field-name-body:first').show(); // It will open the first news.
$('title:first').addClass('active');// add class active to the first title
$('.title').click( function() { // The body is a children of the row.
$('.title').removeClass('active'); // remove class active to all the title
    $('.field-name-body').hide(); // it hides all the open body fields if there is one.
    $(this).addClass('active'); //add class active to the clicked element
    var activeBody = $(this).attr('id'); //find the id of the clicked element
    $('#body-'+activeBody).show();
    });


How can I invalidate a cache on a specific View? I am facing a situation where I need to invalidate a specific View in order to initiate clearing the cache on that View.

views_invalidate_cache() clears ALL cached Views data, for every View on the site.

How can I trigger a cache invalidation for a specific View from inside my module code?

If you know the name of the view that you want to clear, then you can clear the caches specific to that view by calling a function like the following:

/**
 * Function to invalidate selected views caches to enable the action forms to work
 */
function mymodule_invalidate_views_cache($view_name) {
  cache_clear_all('ctools_export:views_view:' . $view_name, 'cache_views', TRUE);
  cache_clear_all($view_name, 'cache_views_data', TRUE);
}

I needed this to allow VBO actions with configuration forms to be able to work while views caching was enabled (I am using content caching).  I called this twice, once in the function mymodule_myaction_form() and again in the function mymodule_myaction_submit().


Alter existing form and add element with an ajax "add more" button I am altering the field settigns form, in order to add custom settings. I used the example module as a guide and added my code in the following manner:

/**
 * Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.
 */
function fd_image_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {

  // Gather the number of names in the form already.
  $num_names = $form_state->get('num_names');
  // We have to ensure that there is at least one name field.
  if ($num_names === NULL) {
    $name_field = $form_state->set('num_names', 1);
    $num_names = 1;
  }

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = [
    '#type' => 'fieldset',
    '#title' => t('People coming to picnic'),
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  for ($i = 0; $i < $num_names; $i++) {
    $form['names_fieldset']['name'][$i] = [
      '#type' => 'textfield',
      '#title' => t('Name'),
    ];
  }

  $form['names_fieldset']['actions'] = [
    '#type' => 'actions',
  ];
  $form['names_fieldset']['actions']['add_name'] = [
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => ['_fd_image_add_one'],
    '#ajax' => [
      'callback' => '_fd_image_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ],
  ];
  // If there is more than one name, add the remove button.
  if ($num_names >= 1) {
    $form['names_fieldset']['actions']['remove_name'] = [
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => ['_fd_image_remove_callback'],
      '#ajax' => [
        'callback' => '_fd_image_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ],
    ];

    $form_state->setCached(FALSE);
  }
}

I also added my ajax callbacks:

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function _fd_image_add_more_callback(array &$form, FormStateInterface $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function _fd_image_add_one(array &$form, FormStateInterface $form_state) {
  $name_field = $form_state->get('num_names');
  $add_button = $name_field + 1;
  $form_state->set('num_names', $add_button);
  // Since our buildForm() method relies on the value of 'num_names' to
  // generate 'name' form elements, we have to tell the form to rebuild. If we
  // don't do this, the form builder will not call buildForm().
  $form_state->setRebuild();
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function _fd_image_remove_callback(array &$form, FormStateInterface $form_state) {
  $name_field = $form_state->get('num_names');
  if ($name_field > 1) {
    $remove_button = $name_field - 1;
    $form_state->set('num_names', $remove_button);
  }
  // Since our buildForm() method relies on the value of 'num_names' to
  // generate 'name' form elements, we have to tell the form to rebuild. If we
  // don't do this, the form builder will not call buildForm().
  $form_state->setRebuild();
}

Now when I go to the field settings form, I see my form elements and I do see the add more button. I can click the add more button 1 time and it adds an extra element, but the problem is, I cannot add more than 2. Once the page have 2 elements subsequents clicks on "add more" result in an ajax callback that does nothing.

After debugging it looks like the $num_names is not being correctly stored and increased. I am assuming that is because the Examples module has it's own buildFrom method while in my case I am only altering. What is the correct way of adding an ajax element to an existing form?

Answering my own question after resolving the issue.
Removing $form_state->setCached(FALSE); fixed the issue.

However, I am not sure why it did or whether this have negative consequences. Hope this helps others.


How do I remove a module JavaScript file through a theme? I need to remove a JavaScript file added from a module through a theme. How can I achieve this?

Implement hook_library_info_alter:

mytheme.theme:

/**
 * Implements hook_library_info_alter().
 */
function mytheme_library_info_alter(&$libraries, $extension) {
  if ($extension === 'some_module') {
    unset($libraries['some_module.library']['js']['js/foo.js']);
  }
}


How to change order of custom module theme output? I need to add some top links and sub top links . I altered hook_theme function and created two templates for these
code is like this-

function acts_theme() {
    return array(
            'acts_top_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-topmenu',
            ),
            'acts_submenu_links' => array(
                    'variables' => array(
                            'links' => NULL,
                            'activelink' => NULL,
                        ),
                    'template' => 'acts-submenu',
            ),
    );
}
function template_preprocess_acts_top_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['toplinks']=$toplinks;
    $variables['activelink']=$activelink;

}
function template_preprocess_acts_submenu_links(&$variables){
    $toplinks=$variables['links'];
    $activelink=$variables['activelink'];
    $variables['sublinks']=$toplinks;
    $variables['activelink']=$activelink;
}

Now I am using these theme output as-

function acts_display(){
    $build['acts_toplinks'] = array(
            '#theme' => 'acts_top_links',
            '#links' => $toplinks,
            '#activelink'=>'Company Law',
    );
    $build['acts_sublinks'] = array(
            '#theme' => 'acts_submenu_links',
            '#links' => $submenulinks,
            '#activelink'=>'/companylaw/acts',
    );

    $build['acts_table_rows'] = array(
            '#theme' => 'table',
            '#rows' => $rows,
            '#empty' => t('Currently there are no active content'),
    );
return $build;
}

I expect output as -
first to show- top links, then sub menu links and then table but output exactly reverse-
first I get table,then sub menu links and then top links
How can I achieve this?

If you add the #weight property to the arrays in $build() then that will allow you to order them e.g.:

$build['acts_table_rows'] = array(
        '#theme' => 'table',
        '#rows' => $rows,
        '#empty' => t('Currently there are no active content'),
        '#weight' => 99,
);


How to determine if loading a form or submitting a form in hook_form_alter? I am trying to put a simple message at the top of a node edit form when a user is creating a new node.
I added a \Drupal::messenger()->addMessage() inside a my form_alter hook but this prints when I open the edit form (good!) but also on the view of the node after the node is saved (bad!).

Looking in debugger I can see that the hook is run twice (load and submit); but I don't see any way of determining which version is being run.

The only thing apparent to me is that $form_state->requestMethod is different in both cases; but this is a protected property; so no access to it.

code shouldn't be required for this question, but:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  \Drupal::messenger()->addMessage(t('some msg'), 'warning');
  return;
}

When there is no user input the form is loading for the first time and it is not submitting.

Additionally you can check the entity whether it is new, if you don't want this condition to be true when the form is loading for an existing node:

if (!$form_state->getUserInput() && $form_state->getFormObject()->getEntity()->isNew()) {
  // first load of the form
}


Add class to {{ link }} twig attribute I'm trying to apply a button class to the {{ link }} attribute in code below.

<a class="usa-button"{{ link }}

It displays correctly however the markup is not correct. I see an extra <a="" tag.

<a class="usa-button" Image styles for grid view_3.docx

Any ideas on how to apply class cleanly?

I think your easiest approach would be to modify the field template and add a wrapping span with classes you need.

field--field-name.html.twig:

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

or replace span and content with to add class directly to  tag:

{{ item.content['#title'] }}


File name transliteration I need to clean up file names on upload. Both for image fields, other file fields and IMCE file manager. The transliteration module is not yet ported to Drupal 8 and the community does not seem to agree on how to implement the core transliteration in Drupal 8.

Do I have to make a custom module for this, or is there a simpler way?

Right now, Drupal 8 seems to allow both spaces and special characters in filenames. I know about the module File (Field) Paths, but it will have to be set up for every file field on every content type. I don't think it will work with IMCE.

I applied a Drupal 8 core patch from this page. It seems to work fine. It adds a new option to /admin/config/media/file-system:

This option enables transliteration for all future uploads to all file fields. It also works for inline images when Enable image uploads is enabled (for the text-format). I don't know if the patch affects IMCE, since IMCE was not installed on my test installation.


How to make Drupal 7 render taxonomy tags as RSS categories? In Drupal 7, taxonomy tags do not show up in the RSS feed. How do I make them visible in the feed, so that RSS reader users can filter out stories based on these tags?

(I found it difficult to find an answer to this, so posting my findings in the hope this helps others)

This used to be the default behaviour in D6, but was accidentally removed from D7 after some refactoring. The latest versions of D7 contain a patch that allowed a third-party module to show RSS categories.

Step 1: download and install the RSS field formatters module.

Step 2: navigate to /admin/structure/types

Step 3: click "manage display" next to the desired content type

Step 4: expand "custom display settings" and make sure "RSS" is checked:

Step 5: select the "RSS" tab (after hitting Save if you had to enable the RSS checkbox). This one is a bit hard to notice:

Step 6: add the Tags to the fields list if not already there. Set the format to "RSS category":

Now save and enjoy your taxonomy tags in your RSS feed!


does node_save wait until end of php session to create db record? Is it possible/expected that node_save() does not create a new record until the current php session is complete?

In other words, if i have a set of nodes to create and i need to check something that is based on the entire list of nodes prior to creating each one; the ones i am creating in my script will not yet be included in the full list?

Is it possible/expected that node_save() does not create a new record until the current php session is complete?

I'm not sure 'session' is the right word there, I'm assuming you mean 'current request' (queuing actions to be run when the session has expired would be an odd thing, and not something PHP/Drupal would do without you telling it to).

Either way, before node_save() completes it commits the database transaction and flushes relevant caches. So no, it doesn't wait for the current request to complete.

So to address

  the ones i am creating in my script will not yet be included in the full list?

No, once you've saved the node, and assuming it completed without error, it will be in the database and available immediately via node_load().

Of course you don't actually need to load it, as your $node object will be in an identical state to the loaded node when node_save() has completed anyway.

Ignoring all that, if you actually mean "does running node_save() automatically update an array of nodes I've previously loaded into a variable earlier in the script", then also no. That would be magic :)


Access user profile data I have a field on a user profile called field_certified_tap. When this is equal to 1 or true on user update/create, I want to send an email.

Currently, I do not see this field in the Condition->Entity Has Value->[data select].

I am using the 3x-dev version of Rules and the 1x version of token.

What am I doing wrong? Is there currently a way to accomplish this with Rules UI or should I make my own Rule or implement in the user save hook?

Thanks!

In your image, you are configuring the "Entity" parameter of the "Entity has field" condition. That parameter should be set to just "user" in the data selector - it would be wrong to specify a field here since it is calling for the entity that you want to check.

The SECOND parameter should be "Field", and it is there that you would want to enter "field_certified_tap" using direct input (not data selector).

Note that the "Entity has field" condition cannot be used to check the value of the field - that has to be done in a separate "Data comparison" condition.

But you are right that even when you properly configure the "Entity has field" condition, your custom field does not show up in the data selector for subsequent actions. I'm not sure why, but there's an open bug report for that in the Rules issue queue:  "Entity has field" doesn't actually give access to the field

Instead, use the "Entity is of bundle" condition to get access to the field. Here's an example using a boolean field called "field_certified_tap" which I added to the user entity. If you import this Rule and examine it in your UI you will see that after adding the "Entity is of bundle" condition to the rule, the data selector in the "Data comparison" condition and the "Show a system message" action DOES now give you an option of "user.field_certified_tap". You can then add a "Data comparison" condition to show the message only when field_certified_tap is true.

I'm using "Show a system message" here because it's much easier to use for debugging than "Send mail". You should use this action to test the tokens you plan to use for your email, then when you are sure you have the values you need you can add a "Send mail" action.

langcode: en
status: true
dependencies: {  }
id: access_certified_tap_field
label: 'Access user certified tap field'
events:
  -
    event_name: 'rules_entity_update:user'
description: ''
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: 137a6a57-2d1a-467d-80e6-68091de5eb11
  conditions:
    id: rules_and
    uuid: 098bb2b1-3e95-4efa-9328-07b651591e63
    conditions:
      -
        id: rules_condition
        uuid: 3b23a038-ac0c-4461-b14b-6db518c3261a
        context_values:
          type: user
          bundle: user
        context_mapping:
          entity: user
        context_processors:
          type:
            rules_tokens: {  }
          bundle:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_entity_is_of_bundle
        negate: false
      -
        id: rules_condition
        uuid: fbcdef7b-9681-47a2-bcac-94d49c86d7fa
        context_values:
          data: '{{ user.field_certified_tap }}'
          operation: '=='
          value: '1'
        context_mapping: {  }
        context_processors:
          data:
            rules_tokens: {  }
          operation:
            rules_tokens: {  }
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        condition_id: rules_data_comparison
        negate: false
  actions:
    id: rules_action_set
    uuid: d6d904a0-007a-4f7f-97be-ac7c1f64edd2
    actions:
      -
        id: rules_action
        uuid: c5d31406-7355-4d91-b623-2c55dc3d57cb
        context_values:
          message: 'User is certifiable!'
          type: warning
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message


Language switcher does not have current page query parameters I have a custom block that shows a schedule. It also show arrows to allow the user to see next or previous days. For this I simply add ?date=DATE to the arrow link. Once landed on one of those pages that have a GET query parameter it is impossible to switch language without loosing your current date selection.

I searched and found many similar issues but all for Drupal 7.

Switching language loses the line item URL parameter

Language switcher (locale_block) doesn't keep query parameters

Since this part of Drupal have been completely rewritten, I need a solution for Drupal 8.

IMO I think it should be a bug in Drupal 8 core. I think the language switcher should know there is existing GET query parameter that need to be passed along the language links. I don't see any reason you wouldn't want to keep the GET params.

anyone has a solution to this problem?

It seems that when I upgrade from 8.1.x (8.1.10) to 8.2.x (8.2.6) it fixes the problem. So it was a core bug.


Serve aggregate CSS/JS files from S3 instead of local storage I have enabled aggregate CSS/JS from the backend. It stores the aggregated files in the local system. How do I make them accessible through the S3 bucket? I have already installed the S3fs module.

The point is when my server is down it automatically creates another instance. And that newly created instance does not have the previous aggregated CSS/JS files. Therefore, it breaks my website.

It's all explained in the module's README.txt

  This will configure your site to store new uploaded files in S3.
  Files
  which your site creates automatically (such as aggregated CSS) will still
  be stored in the server's local filesystem, because Drupal is hard-coded
  to use the public:// filesystem for such files.
  However, s3fs can be configured to handle these files as well. In
  settings.php you can enable the s3fs.use_s3_for_public and
  s3fs.use_s3_for_private settings to make s3fs take over the job of the
  public and/or private file systems. This will cause your site to store
  newly uploaded/generated files from the public/private file system in S3
  instead of the local file system. However, it will make any existing files
  in those file systems become invisible to Drupal.
  To remedy this, you'll need to copy those files into your S3 bucket.

  Example:
  $settings['s3fs.use_s3_for_public'] = TRUE;
  If you use s3fs for public, you should change your php twig
  storage folder
  to a local directory, php twig files in S3 produce latency and security
  issues (these files would be public). Please change the php_storage settings in your setting.php and choose a directory, out of docroot
  recommended.

  Example:
  $settings['php_storage']['twig']['directory'] = '../storage/php';

  If you have a multiple backends you may use a NAS to store it or other
  shared storage system with your others backends.

Related Question: Serve compressed JS and CSS with S3 as filesystem


Distributing nodes across drupal sites I'm investigating how to create a scalable drupal system where nodes can be shared across different sites. In order to support future growth, it is likely we will need to "plug in" more servers/sites into the network.

I was thinking that this would be best achieved with a central site for storing the master records, users, and permissions, and then the slave sites would hold copies of these where relevant. Not all sites will need all the nodes, only those that are linked.

Alternatively, the central site could store which site has the master record. That might make it easier to grow. Thinking of node id's, the end solution needs to cater for the fact that these numbers could easily hit the millions.

It may be a crazy idea and maybe Drupal is not the right platform for this too.

Any ideas?

UPDATE: The concept is similar to that of sharding and map reduce (my basic understanding that it), yet my biggest concern are the node id's. If the system hits the number of users/groups/nodes we are looking at, we could hit the nid int limit and experience performance issues well before that point too. So a distributed model seems to be the best direction.

Normally with drupal you would not have several databases each with their own fragment of the database, and combined you have a whole site.

With drupal 7, drupal now supports database masters and slaves from within the application. What this means now is say you need 3 database servers to support your sites non-functional requirements (availability, performance etc), you can now add:

<?php
$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb1',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver1',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb2',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver2',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb3',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'dbserver3',
);
?>

This definition provides a single "default" server and two "slave" servers. Note that the "slave" key is an array. If any target is defined as an array of connection information, one of the defined servers will be selected at random for that target for each page request. That is, on one page request all slave queries will be sent to dbserver2 while on the next they may all be sent to dbserver3.

The above is straight from the docs ;)

I would recommend the above approach as this is a supported configuration, if you decide to create your own custom drupal schema or load splitting algorithm - you now have to support it.

With drupal 6 - you are pretty much forced to use pressflow. Pressflow is a performance based fork from the drupal code base that tries to keep 100% API compatibility with drupal. Lullabot wrote an awesome article on database replication with pressflow 6.

It turns out lullabot released their views 3 slave query module on github as well, fork away!


Initialize form object properties based on url params? I did see some form classes which set form object properties in the buildForm() method.

However, these property values are no longer available in submitForm().

Simplified/incomplete example:

class MyForm {

  private $arg0;

  public function buildForm($form, $form_state, $nid) {
    $this->nid = $nid;
  }

  public function submitForm($form, $form_state) {
    $nid = $this->nid;  // $nid will be NULL.
  }
}

Actually there are some callbacks where these property values are available. E.g. if you register a #process => [[$this, 'process']] callback.

But it is not really surprising that the values are gone in some callbacks. ::buildForm() is not a constructor.

In some other form classes, they use $form_state->set($key, $value) to make data available to submitForm(). This works, but it somehow seems ugly.

Another way would be to store these values in the $form array as '#type' => 'value', or as #_my_data' => .... Again, I find this ugly.

Is there a more reliable way to initialize object properties on the form object based on url parameters? E.g. to have these parameters sent to the constructor?

Also, depending how I do this, do I need to worry that the data will be serialized?

(To me this seems like a flaw in the form API. But maybe I am missing something. I might open an issue on drupal.org, if the answer does not change my mind.)

Yes, you can use form_state storage.

Object properties should work fine as well as long as you do not use private, use protected. private conflicts with the DependencySerializationTrait.

And yes, everything you store like that is serialized (unless it is a service, then that trait will remove and restore it) because that's the only way to transport this data across different requests.


.htaccess error on local site in docksal I've built a Drupal 8.6.4 website within Acquia Dev Desktop, but moved it into a local Docker/Docksal setup to continue working (haven't used it before) - on a mac, if it matters. Everything seems fine, but for two issues. The first is a bunch of Security warnings in the logs about htaccess, saying to add an htaccess containing some specific code to the "/var/www/config/default" directory, but I don't have this file directory. It's a Docksal set-up: just ~/projects/projectname/docroot set-up on my computer.

The second issue, which I suspect may be related, is that I can't Drush archive-backup --destination=x/x/x.. It always tells me the file permission prevents it, Even if I give full read/write permission on the folder. But I can do it without the --destination added. It just puts it in a temp folder.

Here's the Error I see - it generates most any time I load an admin page.

    Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your /var/www/config/default directory which contains the following lines:
    # Deny all requests from Apache 2.4+.
    <IfModule mod_authz_core.c>
      Require all denied
    </IfModule>

    # Deny all requests from Apache 2.0-2.2.
    <IfModule !mod_authz_core.c>
      Deny from all
    </IfModule>

    # Turn off all options we don't need.
    Options -Indexes -ExecCGI -Includes -MultiViews

    # Set the catch-all handler to prevent scripts from being executed.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files *>
      # Override the handler again if we're run later in the evaluation list.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    # If we know how to do it safely, disable the PHP engine entirely.
    <IfModule mod_php5.c>
      php_flag engine off
    </IfModule>

There is a directory in the root of the Acquia project, config/default.So, all you need it's make it writable.

or you can  change $config_directories['vcs'] and $config_directories['sync'] in your settings.php to somewhere which will be writable .


Show views only on one specific node I think my question is very simple, but I was searching for long time for a good solution.

How do you integrate in Drupal 7 one views (e.g. page or block) inside or after one single node (e.g. node/10). What is the best solution?

Until now I used the drupal block system to attach one views-block after a single node. But I read, is not a good solution.

Thanks

That's the best use case for the Viewfield module. It works providing a custom field, so you can "attach" a view to nodes.

You can provide a default view if you want to display the same view on many nodes.

Or you can provide a custom argument to pass to the view.


What are possible alternatives for Admin:Hover, which suffers a major security issue? As mentioned on its project page, module Admin:hover adds administrative links to nodes and blocks for users with proper permissions to easily edit content.

But it suffers a major security issue, as detailed in SA-CONTRIB-2012-006.

Does anyone know of any alternatives?

There are several other modules that do this (quotes are from the project pages of these modules, where available):

Contextual Links (Backport of contextual.module in Drupal 7):

Hover over nodes, blocks, and views blocks to expose styled edit/configure/delete tabs.

Admin links

Block edit

... provides inline (on mouseover) editing capability for any block or node.

Administer Tooltip

... adds little icons to all entities (node, block, view, user) which are visible on mouseover ...


Testing for taxonomy On my website, I have used the Taxonomy to created different sections. Each section has its own "contact us" page. I want to create a variable that will create a path to the relevant contact page. That way I can print the variable in taxonomy-term.tpl.php, node.tpl.php and page.tpl.php files to print the path dynamically.

How can I test for the taxonomy, and then change the value of the variable accordingly?

I've looked around for an answer and the closest I could find was How to move custom code into template.php. However, it requires a taxonomy reference field to present to perform the test and so wont work on the main taxonomy index pages (which cannot have taxonomy field references).

EDIT: Please note: The contact us page is just a normal node with telephone numbers on it. It is not the Drupal contact us form.

There is a Drupal Dojo video that answers this exact question. It is done in Drupal 6 but might give you some clues how to accomplish this in Drupal 7.

(edit: Response to comment) Although it might add complexity to developing your website, you can use the Context module to trigger block visibility based on certain criteria such as a View being viewed or a taxonomy term page being viewed. Keep in mind that if the Context module is used with all blocks disabled in the block UI it gives a performance boost to the website.


HTML output of whole page I am trying to generate html output of whole page and then pass it to response array.I am doing something like this:

  $page = array(
  '#theme' => 'html',
  '#page_object' => new HtmlPage(render($content)),
   );

$content is a render array and new HtmlPage creates a HtmlPage object from an existing page. I am passing render($page) to the response object, but I am getting error this error:

  LogicException: A stray drupal_render() invocation with $is_root_call = TRUE is causing bubbling of attached assets to break. in Drupal\Core\Render\Renderer->doRender() (line 377 of core\lib\Drupal\Core\Render\Renderer.php).

What should I do to make this correct? Thanks

Try using renderer service instead as rendeer and drupal_render() is deprecated, e.g.

\Drupal::service('renderer')->renderRoot($content);

  Renders final HTML given a structured array tree.


Error when printing URI in drupal Views I tried to print the Image field URI and the image field in the views-field.tpl and i got this error.
Notice: Undefined index: field_photo in include() (line 6 of timeline.tpl.php).
Notice: Trying to get property of non-object in include() (line 6 of timeline.tpl.php).

Here is my code

    <div class="timeline-badge <?php print $fields['field_event']->content ?>" data-toggle="tooltip" data-placement="top" title="<?php print $fields['field_event']->content ?>"><?php print $fields['field_icon']->content ?>

<?php print $fields['field_minute']->content ?>

<?php print $fields['field_comment']->content ?>

        <?php if($fields['field_photo']->content){  ?>

        <a id="tml-photo" href="<?php  print $fields['uri']->content; ?>" title="<?php print $fields['field_comment']->content ?>">
        <?php print $fields['field_photo']->content ?>

        <?php } ?>

If you just want to check if it has a value, you can add a check if it exists, so on row 6:

<?php if (isset($fields['fields_photo']->content) && $fields['fields_photo']->content) { ?>

Otherwise do a <?php dpm($fields); ?> to see what is actually available to use for your theme.

It couldn't be that you have set it to "Exclude from display"?


Backup and Migrate gives me a tar ball I have a local site and a development site. I want to replace my development site with my local site. I used the Backup and Migrate module to backup the development site into a .gz file. All good. But when I did the same again with the local environment, it came back as a .tar file, no matter which compression option I chose.

When I tried to restore onto the development site using the local site's tarball, it specified it needs a .gz or .zip file. So I ran:

  tar -cvzf 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar.gz
  127.0.1.1-2015-01-12T17-23-50.sitearchive.tar

This time, it came back with this error:

  Unable to restore from file
  /tmp/backup_migrate_vbDBRs.0.1.1-2015-01-12t17-23-50.sitearchive.tar
  because a tar file can't be restored to this database.

How can I correctly restore a backup from my local site onto the development site. Or is this method completely wrong and I should be doing something else, like creating a new site from scratch and restoring that?

This is not an issue with the module.

The most likely cause of the problem is that your local system is missing gzip, so the backup and migrate module is unable to turn the tar-file into a gzipped tar file.

The command to do that is not tar -cvzf (which you've tried), but gzip. I.e.:

gzip 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar

This should produce a valid 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar.gz, but if you try this on the local system, it will probably fail telling you that it can't locate gzip.

The best fix would be to install gzip on the local system.

Alternatively, you may export the file to some system that has gzip, and do the gizipping there.


Do I have to validate() user entity saved programmatically? I have a custom module saving user accounts from a customer API.

For this I use the \Drupal\user\Entity\User::create method, and I initialise the user account with the code above:

  /**
   * Save a Drupal user using `mail`.
   *
   * @param array $data
   *   The User data to save.
   *
   * @return bool|int
   *   Result: SAVED_NEW or FALSE.
   */
  public static function saveUser(array $data) {
    // Only if user exists on API
    if (empty($data['mail'])) {
      return FALSE;
    }
    // Create the user
    $email = $data['mail'];
    $user = \Drupal\user\Entity\User::create();
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();

    // The Basics
    $user->setEmail($email);
    $user->setUsername($email);
    $user->set("init", $email);
    $user->set("langcode", $lang);
    $user->set("preferred_langcode", $lang);
    $user->set("preferred_admin_langcode", $lang);
    $user->enforceIsNew();
    $user->setPassword(user_password());
    $user->activate();

    // Save user.
    return $user->save();
  }

I like to look for a good way of doing things and to read about getting D9 ready for my modules. When it is necessary, I also inspect the core code to see the available methods and how core modules are made to inspire me.

I found this interesting topic about Entity Validation API, where it speaks about using validation on entities. I also found that user object has methods to know if a validation is necessary and to validate, and the preSave method will throw an exception if the validation is necessary and not done.

All the examples and code snippet I found on internet about creating a user programmatically never use any kind of validation, and I wonder if this is something new or if it is just not really necessary for my case.

As I said, I save data from a remote API, and I do not manage the quality of the email address I use as email and username. I also do not verify if those values already exist.

Should I add something like this ?

// Entity validation
if ($user->isValidationRequired()) {
  $violations = $user->validate();
  if (count($violations)) {
    \Drupal::messenger()->addError($violations[0]->getMessage());
    return FALSE;
  }
}

If you want to first verify the user you programmatically created passes validation, which means (for example) that its username and emails are unique, you can check if there are validation violations. You don't need to fist call isValidationRequired() as that method returns the value set with setValidationRequired(), which is called only from ContentEntityForm::buildEntity() and ContentEntityForm::validateForm(). (In other words, if the entity isn't created via its entity form, isValidationRequired() will return FALSE.)

$violations = $user->validate();
if (count($violations)) {
  // The user account didn't pass the validation.
}

Note also that you can pass to User::create() an array containing the values to assign to the user fields, instead of calling each setter as your code does.

You could also create the user account with \Drupal::entityTypeManager()->getStorage('user')->create($values), where $values is the same array accepted by User::create().