Override taxonomy term display page with panel page I am having a menu built using taxonomy terms which links to a URL pattern like shop/[Term name] this is a dropdown menu.
I have created a panel page which takes an argument in the URL i.e (shop/!argument).
In the panel I have added a contextual filtered(has Taxonomy term) view and checked "send arguments" option in settings.
so obviously the taxonomy term display page is where I land when clicking the links.
I don't want to use the taxonomy term panel or the views page for taxonomy which comes with drupal core itself.
I want my panel page to override the taxonomy term display page
this is only for two types of vocabulary terms, any ideas how?

Have you tried this tutorial? http://drupaleasy.com/blogs/ultimike/2010/10/taxonomy-term-pages-steroids-using-panels-views


What is the best way to put comments section to user profile I need add ability to add comment for user profile. What i am thinking is, create a content type with empty body and leave just comments, and afterwards insert that node to user_profile.
But i don't know how to append comments to user profile tpl file. How to do this, or maybe other suggestions?

  After some research i decided to make my own module to add comments on
  user profile, i will make a block and insert this block to only user
  page user/*, and will track user id to show proper comments.

If you use Profile2, this creates profiles as node type entities so you can turn comments on as each profile will have settings similar to that when you create content types.


How does CSS and JS aggregration work in Drupal? When Drupal is set to optimize JS and CSS, it creates the 'js' and 'css' folders in your public file system root. Aggregated JS and CSS get stored in these directories. I've tried to figure out how Drupal keeps track of these files, and how Drupal matches consequent page request against applicable aggregated files in these directories. Is the filename a hash based on, say, the request URL?

Right now, I'm working on a site which has 4 web servers. All web servers have the same storage mounted as their public and private file systems. When one server generates CSS and JS files for a page, how does any of the other servers utilise these generated files for an indentical request?

CSS/JS files get added to Drupal various ways; 5 out of the 7 ways allows for the file to be aggregated. Once they have been added to the page, drupal renders the html markup for them and creates/uses the markup inside of template_process_html().

Functions to look for how an aggregate is built is drupal_build_js_cache() & drupal_build_css_cache(). Inside of these function it gets a list of filenames and then creates a hash of them. This is a lookup, to see if the file has already been created.

  $map = variable_get('drupal_js_cache_files', array());
  // Create a new array so that only the file names are used to create the hash.
  // This prevents new aggregates from being created unnecessarily.
  $js_data = array();
  foreach ($files as $file) {
    $js_data[] = $file['data'];
  }
  $key = hash('sha256', serialize($js_data));
  if (isset($map[$key])) {
    $uri = $map[$key];
  }

If it has not been created before, because of the order and/or contents of the $file['data'] info then it will create a new aggregate based off of all the files contents strung together.

  if (empty($uri) || !file_exists($uri)) {
    // Build aggregate JS file.
    foreach ($files as $path => $info) {
      if ($info['preprocess']) {
        // Append a ';' and a newline after each JS file.
        $contents .= file_get_contents($path) . ";\n";
      }
    }
    // Prefix filename to prevent blocking by firewalls which reject files
    // starting with "ad*".
    $filename = 'js_' . drupal_hash_base64($contents) . '.js';
    // Create the js/ within the files folder.
    $jspath = 'public://js';
    $uri = $jspath . '/' . $filename;
    ...
    $map[$key] = $uri;
    variable_set('drupal_js_cache_files', $map);
  }
  return $uri;

The files are kept track inside of 2 variables drupal_js_cache_files and drupal_css_cache_files; Drupal will also check to make sure the file exists before it is used. The aggregates have nothing to do with the URL. Your 4 webheads will utilize these aggregates due to the variables being stored within the database.

Note: AdvAgg is sorta similar to this but it uses a couple database tables instead of 2 variables; AdvAgg does this for a couple of reasons mainly to fix issues with concurrent variable_set's and allowing for advanced grouping logic.


How do you reorder an entity reference revisions field during hook_node_presave? I am trying to reorder some paragraphs based on a text field within them on node save so the author does not need to maintain the alphabetical order manually, but when I save the node all values are lost. I tried matching the array from $node->get('field_paragraphs')->getValue(), but that does not seem to work.

function mymodule_node_presave(NodeInterface $node) {
  if ($node->bundle() == 'page' && $node>get('field_paragraphs')->count() > 1) {
    $values = $node->get('field_paragraphs')->getValue();
    $entities = $node->get('field_paragraphs')->referencedEntities();
    uasort($entities, function ($a, $b) {
      return Unicode::strcasecmp($a->get('field_text')->value, $b->get('field_text')->value);
    });

    $new_values = [];
    foreach ($entities as &$entity) {
    $id = $entity->id();
    $new_value = [
      'target_id' => $id,
      'target_revison_id' => $entity->getRevisionId(),
    ];
    $index = array_search($id, array_column($values, 'target_id'));
    if (FALSE !== $index && isset($values[$index]['subform'])) {
      $new_value['subform'] = $values[$index]['subform'];
    }
    $new_values[] = $new_value;
  }

  $node->set('field_paragraphs', $new_values);
}

You don’t need to re-create the array of target IDs by creating all that $new_values stuff.

Just set the entities like this:

$node->set('field_paragraphs', $entities);


How to embed two views into a block I have two views that are block displays.  I'm trying to embed these views in a block.  When I include the block nothing is displayed.  If i add "test" to $block['content'] it displays test in the block body.

Here is my code ($gid is an organic group id as an argument to the block):

  case 5: // Create Mugshot block
    $viewName = 'display_most_wanted';
    $display_id1 = 'block_1';
    $args = array($gid);
    $wanted = views_embed_view($viewName, $display_id1, $args);

    $display_id2 = 'block_2';
    $convicted = views_embed_view($viewName, $display_id2, $args);

    $block['subject'] = 'CWPA OG Mugshots';
    $block['content'] = $wanted . $convicted;
    break;

  default:
    // Throw an error
    break;
}

return $block;

It seems like instead of rendering the views programmatically you could also leverage the Views "Attachment" display .  The allows you to attach a view to another display, in other words render one view after another.  The "block_1" display of the view you posted above would be the main view displayed as a block, and then you would change the "block_2" display to an attachment and configure the settings similar to the image below.

This would eliminate the need to create custom code to display both views in a block.


Migration from one domain to other domain I have build a D8 website on domain www.example.com/abc and now wants to copy this site to www.example.com/xyz

Hosting is same

What I did is:
1) copied all files from abc to xyz.
2) Exported Database from abc and imported it to xyz.
3) Assigned new Database name, Username and Password to xyz in settings.php.

When I go to www.example.com/xyz Homepage looks perfect but when I go to inner pages it takes me back to domain www.example.com/abc.

How should I update the URLs?

More than likely, you have a redirect base directive in your .htaccess. This is used when serving your Drupal site out of a subfolder of your webhosting provider's webroot. You should check your .htaccess file for the directive RewriteBase /abc and replace with RewriteBase /xyz
If that still doesn't work, check the vhost entry of your webserver for the same directive.
Otherwise, if the site still redirects to "/abc", then you may have a $base_url defined in settings.php causing the redirect.


Insert Javascript in a node I can't figure out how to insert a javascript function inside a node.

It's a countdown script that uses an external js file and i need the function to be called from within a node. (each node will have a different countdown target date)

I set the input filter to php but it didn't work.
All it does is printing the js file content as node content

I put the js file in a folder inside sites/all/scripts and here's how i use :

<?php include('sites/all/scripts/countdown.js'); ?>

Any ideas ?

thanks a lot

Javascript happens on the client-side so there's no need to use PHP at all here. Using the PHP filter is in fact strongly discouraged as it introduces potential security risks.

To include javascript in an HTML page you use the <script> tag like so:

<script type="text/javascript" src="/sites/all/scripts/countdown.js"></script>


Youtube Media with Media Module, won't render I'm using the WYSIWYG module and I enabled the media browser button for it. When I add a youtube video, only the thumbnail shows... Why is this?! (I'm using ckeditor.)

The media module currently only has support for embedding images via WYSIWYG.

What version of media are you using? If you use media 7.x-2.x you can get it to work by using this sandbox module - http://drupal.org/sandbox/DevinCarlson/1823634
(note that you also need separate http://drupal.org/project/issues/file_entity module with 2.x because it has now been split out of media - it was part of media in 7.x-1.x)

That sandbox module allows configuring which view modes are used for different file types when embedding via WYSIWYG.

There is a related issue for the media module here http://drupal.org/node/1792738 - It has been decided in that issue that the sandbox module will be integrated into the media module.
So you can safely use the sandbox knowing that the functionality will eventually be in the media module, at which point you won't need to rely on a sandbox project.

When using that setup of modules I find that in a lot of cases it is also good to use http://drupal.org/project/entity_view_mode - which allows you to create new view modes (the file_entity 7.x-2.x module doesn't provide many view modes out of the box).


How do I access a taxonomy term's field(s)? Specifically, I'm trying to access a field called 'logo' inside of a couple taxonomy terms (Tweet and Wikipedia edit), which is an image. I have a news feed on the front page of my site, and for each feed item that has a term reference to one of these image beside each feed item in the feed. What would be the best way to go about exposing or accessing the logo field from each taxonomy term?

If you are going to be accessing the content of what drupal call entities (data objects, like nodes, users, taxonomies etc), you might considder using the entity module. It adds some nice helper functions. What Nikit writes is not possible, you would do something like this:

$term_id_1 = $node->field_term['und'][0]['tid'];
$term_id_2 = $node->field_term['und'][1]['tid'];

Then you would have to load the terms etc. Instead with the entity module you can do.

$images = array();

$node_wrapper = entity_metadata_wrapper('node', $node);
foreach ($node_wrapper->field_term as $term_wrapper) {
  $images[] = $term_wrapper->field_image->value();
}

$images will now be an array with the image field object that holds info like uri, fid etc.


Is bypassing Drupal's #token protection against CSRF safe for search forms specifically? I see that $form['#token'] is employed in drupal_prepare_form() and drupal_validate_form() as a protective measure against cross-site request forgery.

I am wondering about the necessity of this measure on site-search forms specifically, including core's search_box() and search_form() as well as a form built from scratch in a module that similarly implements a search by feeding arguments into a view.

I have seen it mentioned (in drupal_prepare_form(), in fact, and possibly other places I can't recall) that the search forms would be a viable case in which to work around the token protection. But then, why doesn't core do so by default?

(Note: I'm  not asking for help with code to work around it, as I've figured that part out already.)

I think the biggest question when judging a potential CSRF problem is whether some form of damage will be done if a user is tricked into taking the action. If there is a CSRF vulnerability that deletes a user or unpublishes a node, that would be a problem. But being tricked into executing a search is only potentially a problem in terms of the resources a search takes to execute (which is not that much). Even if the core search doesn't bypass the token, it is accessible as a GET url (search/node/keyword) so someone could be tricked into visiting that URL bypassing the form in front.

Another way to think about it is whether the action is idempotent. A search is an idempotent action (by the W3 definition, log records might be created, but that's not a big deal), so it doesn't need CSRF protection.


Drupal Registration Form In Lightbox With Ajax I updated my post up top to pull in the user form created in Drupal, it now loads it in a lightbox correctly, how can I submit this using AJAX, validate this all in the Lightbox? any ideas?

Any help would be good help :)

    <?php
function ajax_register_menu() {
  $items['request'] = array(
    'page callback' => 'ajax_register_mypage',
    'page arguments' => array('ajax_register_form'),
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'title' => t('MY TITLE'),
  );

  $items['request/submit'] = array(
    'page callback' => 'ajax_register_submit',
    'type' => MENU_CALLBACK,
    'access callback' => FALSE,
  );

  return $items;
}

function ajax_register_mypage($form){
    print '
';
    print 'Hello World';
    print render(drupal_get_form('user_register_form'));
    print '
';
}

function ajax_register_submit() {
    $returnO = new StdClass();
    $returnO->status = true;
    $returnO->message = 'MY INFORMATIVE MESSAGE HERE';

    print drupal_json($returnO);

    die;
}
?>

If I recall correctly, instead of calling render() for your drupal_get_form(), call drupal_render() instead.

<?php

function ajax_register_mypage($form){
  print 'Hello World';
  print drupal_render(drupal_get_form($form));
}

?>

Hope this ends up solving your issue on this one.


unpublish node when edit it I have a content type calles survey, When admin deletes a survey, the survey results should still be accessible and not deleted as well. So I want to unpublish the node when click on the delete button(it will be better to change this delete button to unpublish button). but I dont know how to unpublished a node.
Any solution / alternative / suggestion will be greatly appreciated.

Hope this will help you, In my case i did it by updating the node and node_revision table's status column set to "0".following code is for form submit action you can do it for your delete action..

function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id == 'your form')   {
 $form['#submit'][] = 'mymodule_form_submit';
 }

}

function mymodule_form_submit($form, &$form_state){
if (//your condition)
            {
            $query = db_update('node')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();

            $query = db_update('node_revision')
            ->fields(array(
            'status' => 0,//unpublished the node
                ))
            ->condition('nid',$form['nid']['#value'], '=')
            ->execute();
            }
        //  drupal_flush_all_caches();

}


How can I remove the hardcoded menus from the Navin subtheme? I'm using Navin, a subtheme of Omega. I'm trying to hide the main menu, so that I can add a superfish menu, but I don't know where it's been hardcoded. It's not in a block (admin/structure/blocks). I've checked the theme settings page (admin/appearance/settings/theme_name) The region--menu.tpl.php looks like this:

<?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>
<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php if ($main_links): ?>
    <nav class="navigation">
      <?php print render($main_links); ?>
    </nav>
    <?php endif; ?>
    <?php if ($secondary_links): ?>
    <nav class="navigation-secondary">
      <?php print render($secondary_links); ?>
    </nav>
    <?php endif; ?>
    <?php print $content; ?>
  </div>
</div>

I appreciate any help or suggestions.

<?php
  $main_links = menu_tree_page_data(variable_get('menu_main_links_source', 'main-menu'));
  $main_links = menu_tree_output($main_links);
  $secondary_links = menu_tree_page_data(variable_get('menu_secondary_links_source', 'user-menu'));
  $secondary_links = menu_tree_output($secondary_links);
?>

Get rid of that bit for starters.

If you're not using that, then you can probably also strip out the following:

<?php if ($main_links): ?>
    <nav class="navigation">
      <?php print render($main_links); ?>
    </nav>
    <?php endif; ?>
    <?php if ($secondary_links): ?>
    <nav class="navigation-secondary">
      <?php print render($secondary_links); ?>
    </nav>
    <?php endif; ?>

Which (for reference) should just leave you with the following:

<div<?php print $attributes; ?>>
  <div<?php print $content_attributes; ?>>
    <?php print $content; ?>
  </div>
</div>


Register Page Themeing I just found out the template for themeing the register page is page-user-register.tpl.php.

But, how do I change the labels on the textfields etc?

For instance, I want to rename the E-Mail label to ... somethingelse :-)

Here is a good tutorial to change all the user pages.  http://drupal.org/node/350634.   For E-Mail edit the $variable['form']['x']


How do I avoid the HTML I enter is altered? I use drupal 8.4.3 with ckeditor 4.7.2 (apparently)

When I press the "source" button, I want to be able to write whatever source I want, in just one line if I want to, I don't want the ckeditor to touch my source code AT ALL.

How is that possible? I think I have used 3 hours googling, without making it work completely.

I want to be able to write "

" without it turning by code into:

 (-- LINE BREAK)

I don't want it to touch it!!! it should just be

 (without the closing /)

when I write into the source, ckeditor shouldn't touch it! How is that possible?

It's probably not just CKeditor altering your HTML. You should look into the configuration of your input formats at /admin/config/content/formats. There is documentation on https://www.drupal.org/docs/8/core/modules/filter/overview, although it's not very detailed.

An input format applies one or more text filters to your input. Common filters are the HTML Filter, that allows only a limited number of HTML tags, and the Line Break Converter, which turns line ends into <br> or <p> tags. You can configure your input format, or create a new one, without any filters.

If I recall correctly, even if you don't have any text filters configured, Drupal may still strip some HTML tags that are considered particularly dangerous, like the <script> tag.


forum post editor problem Wysiwyg hello i have my local server setup and everything works great so i migrate from local to webservever

then something stop working.

My permissions in some way resetted and the problem is that even when i have enable and all correct permissions the editor not working.. i cannot even see enable-disable rich text

also overlay not working something happen and stopped.

But the main problem is the tinymce not working even when setup it correct from my local server (i see the setting side by side and choose them) but i again doesnt work any thoughts.

Answered in comment by Dimitris B:

Found answer, in administrator -> configuration at performance section i disable Aggregate JavaScript files which i had enabled, so i realize that i had a problem in my js code so i need to check it up, but after i disable it everything works perfect.


Drush pm-disable needs a higher bootstrap level to run I keep having this periodic issue with the pm-disable (amongst other) commands in Drush. I have kicked the tires on configuring Drush -- I have the datbase connect set to 127.0.0.1, have php.ini in the ~/.drush dir, using MAMP PHP -- same results.

drush status indicates that it connects without issue. My all directory has user and group level read and write, my site directory has read level on user and group (no write). Do I need to enable different chmod settings in my homesite dir or what am I missing?

This is the pm-disable output when it fails.

The drush command 'dis views' could not be executed.                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.                                                                                [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another site with a working database
setup by specifying the URI to use with the --uri parameter on the command line. See `drush topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.31
 Site URI               :  http://mywellbeing.local
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database port          :  8889
 Database username      :  mydrupalsite
 Database name          :  mydrupalsite
 PHP executable         :  /Applications/MAMP/bin/php/php5.5.14/bin/php
 PHP configuration      :  /Users/cameronkilgorew/.drush/php.ini /Users/cameronkilgorew/.drush/php.ini
 PHP OS                 :  Darwin
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/cameronkilgorew/mydrupalsite/repo
 Site path              :  sites/mydrupalsite.local

You're using drush 7.0-dev on php 5.5.14.

Do you have php5-json package? That is required for php 5.5.
Did you follow the extra instructions on github.com/drush-ops/drush related to MAMP? There's one about socket that seems relevant


Field Formatter: how to know where "i'm" I have a node type called fotogallery. In this node type there is a field of type "field collection". With hook_field_formatter_view() I create a custom output for this field.

Now, the same node type is linked to another node type via entity reference. In this case I want to create another type of output for the "field colletion" field. But how I (drupal cms) can know if I'm inside node type "fotogallery" or I'm inside an entity reference ?

Do I need to load the current node (via node_load(arg(1)) and see the "type" value?

A Field Formatter has no awareness of when it's used. It's simply just a unique way to display a field.

You want to use something like Entityreference ViewMode Selector. And create 2 formatters for the Field Collection. 1 formatter is the default output for collections, 1 formatter is the viewed as entityreference formatter.

When you set the entityreference, you would set the formatter as needed.


Is there a way to clone a content type and its fields? I have a content type named "event_xyz" that I want to rename to "event".  I figure I can clone the content type and then delete the original.  But I don't see any tuts or modules on how to do this.

Alternatively, is there a way to rename a bundle's machine name?

I found a closed question related to cloning content types for Drupal 7, but not for Drupal 8.

The best way to do this is the entity_clone contrib module.  I downloaded it, installed it, hit the clone button and all of fields and form settings were copied to the new content type.  It worked very well.


Need to automatically rotate the result of a view once a week (Sunday night) The view (block) displays content (field collection items) on my home page.  I had it set so the client could choose what to display by checking a boolean field.  The view works fine, but now the client has decided they would like the content to be chosen randomly and for it to be automated (to change on a weekly basis).  I need every user to see the same content displayed and I need the same content to stay up a whole week.

What is the best way to accomplish this?  I've tried setting the display to show only 1 and sort on random with the view cache set to 6 days/6 days.  I'm just not sure how reliable this will be.

The problem with that solution is it relies on the view's cache lifetime which might not sync up to Sunday (e.g. a manual cache clear it will reset the lifetime clock on the view cache and expire it 6 days from the manual cache clear).

A better solution would rely on hook_cron() and do the following:

Trigger every Sunday
Set all node fields to false
Randomly select a node and update its field to true.

This could be accomplished with a custom module hook_cron or, I think, the Elysia Cron module.


Difference between Content: Updated date and Content revision: Updated date in Views In views Filter criteria, What is the difference between Content: Updated date and Content revision: Updated date?

I can see that the descriptions provided for both these filters can make things a little confusing. The below description and the image should help you out.

Content: Updated Date maps to node.changed and tells you the latest time when the node was changed.
Content revision: Updated data maps to node_revision.timestamp when a particular revision of the node (not necessarily the latest revision) was created.

You can check this in the query put together by Views, as shown in the image below. Hope this helps.


When using a grouping field in an HTML list, is there a way to determine the group/loop number of the current content being rendered? I want to be able to determine what group number is currently being processed to that I can treat the output of the first group differently than subsequent groups.
Unlike rows, I do not see a way to find the current count of groups or loops through the view such that I could, for instance, do something like the following (i.e., classing group content by group iteration) -

{{ title }}

    {% for row in rows %}

        {{- row.content -}}

    {% endfor %}

{{ title }}

    {% for row in rows %}

        {{- row.content -}}

    {% endfor %}

...

{{ title }}

    {% for row in rows %}

        {{- row.content -}}

    {% endfor %}

I don't know of a way to get the group number from within the grouping (e.g. views-view-list) template, but I would look to do this  split between two templates: views-view and views-view-list.
First, in the views-view template, e.g. views-view--my-view-id.html.twig.
{# ... etc ... #}
{# Loop through the rows, aka groups, and add a wrapper with index identifier. #}
{% for row in rows %}

    {{ row }}

{% endfor %}
{# ... etc ... #}

Second, create your views-view-list template, e.g. views-view--my-view-id.html.twig to build the content for each group:

{{ title }}

  {% for row in rows %}

      {{- row.content -}}

  {% endfor %}

Then you can target the contents of each group in css like:
.group--1 h3 { }
.group--1 ul { }
.group--2 h3 { }
.group--2 ul { }
.etc { }


exporting/importing nodes without losing disqus comments / social media stats I've been working on a website and the live version there is still content being created while i develop the local site.

Whats the best way for me to import the new nodes that have been created on the live site into the local site without losing the disqus comments or social media stats (fb likes etc.) it has?

To export single nodes you can use the Node Export module. This one allows you to export a node, it's fields and contents to a text file which can be imported on another site with the Node Export module.

Assuming you are using the Disqus module: To export comments and social media stats you will have to use the Disqus Migrate submodule. To use either Import/Export, you have to register an Application with Disqus and fill in both your public and private keys in the main Disqus settings page. Make sure your authentication method is set to the deprecated legacy method. Download the PHP API implementation here and upload the disqusapi folder to your sites/all/libraries folder.

Export:

Export your comments using the XML method until the API method is fixed, and save the file to your computer.
Upload the XML file to your Disqus site in the Tools section (generic WXR method), and wait for the import to complete.
Check for errors after importing, but most comments should have been imported successfully. They will appear automatically on any Disqus-enabled nodes on your website.

Import/Sync:

You can do a one-time import at Comments->Disqus Import. Specify the timestamp you want to import from.
You can have comments automatically import from Disqus on an interval basis. Turn this on in the import settings at Site Config -> Disqus -> Import. Turning on syncing will query Disqus for any comments that came in since the last import.


How can I get the date_popup module to display AM/PM in the time selector? In date_popup's README.txt, it states that

  The time selector will add AM/PM if 'a' is in the format string.

Which leads me to believe that

'#default_value' => date("m/d/Y H:ia"),
'#date_format' => 'm/d/Y H:ia',

should result in a textfield for the time picker that looks like:

  [2:25pm]

but instead I just get a blank text field. I can't get any combination of default_value / date_format to result in what I'm looking for. Am I reading the documentation wrong, or can this be achieved?

Update: I couldn't get this darn thing working and decided to disable the timepicker (admin/config/date/date_popup) and added the timepicker from http://jonthornton.github.com/jquery-timepicker/ using the following code:

  $form['#attached']['css'][] = 'path/to/jquery-timepicker/jquery.timepicker.css';
  $form['#attached']['js'][] = '//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
  $form['#attached']['js'][] = array('data' => "var jq9 = jQuery.noConflict();", 'type' => 'inline');
  $form['#attached']['js'][] = 'path/to/jquery-timepicker/jquery.timepicker.js';
  $form['#attached']['js'][] = array(
    'data' => "
      jq9(document).ready(function() {
        jq9('#edit-start-date--popup-1').timepicker();
      });",
    'type' => 'inline',
  );
  $form['start_date'] = array(
    '#title' => 'Start Date',
    '#type' => 'date_popup',
    '#required' => TRUE,
    '#date_type' => DATE_DATETIME,
    '#date_timezone' => date_default_timezone(),
    '#default_value' => date("m/d/Y h:ia"),
    '#date_format' => 'm/d/Y h:ia',
    '#date_increment' => 1,
    '#date_year_range' => '-1:+1',
  );

I remember having a similar issue - I fixed it using a custom module like this, the possible cause was probably that Drupal and jQuery returned different formats...

$GLOBALS['locale'] = $locale = 'fr';

/* [...] */

function x_form_alter(&$form, &$form_state, $form_id){
    // Fix date format in some exposed date filters (cck date)
    $date_format = 'd/m/Y'; /* Should be same as in "sites/all/js/jquery.datepicker/$locale.js" */
    foreach($form as $key => $value){
        isset($value['value']['#date_format']) && $form[$key]['value']['#date_format'] = $date_format;
        isset($value['min']['#date_format']) && $form[$key]['min']['#date_format'] = $date_format;
        isset($value['max']['#date_format']) && $form[$key]['max']['#date_format'] = $date_format;
    }
}

I guess you can adapt this code to your situation and even better, suggest a cleaner solution.


How to add different GTM snippets per environment? We have multiple environments such as Dev, Stage, QA, and Production. Rather than having one GTM snippet that is loaded on every page request in all the environments, we wanted to separate the GTM snippets so that the GTM snippet for Dev is only loaded for Dev, the GTM snippet for Stage is only loaded for Stage, and the production GTM script is only loaded on production.

Currently we add the GTM snippet through the use of our custom theme's html.html.twig template file.

How would I be able to conditionally add different scripts in a Drupal way (e.g. custom module, custom JS)?

We initially thought to create custom modules that would a load mymodule.html.html.twig when enabled per environment. For example, the dev custom module would only be enabled on Dev, Stage custom module would only be enabled on. However that is not working.

In my opinion adding a GTM snippet should be handled by a module, and not theme dependent. The GoogleTagManager can be used to accomplish this.

In your settings.php file you can indicate which snippet to use:
$config['google_tag.settings']['container_id'] = 'GTM-000000';

When you want these snippet variants stored in you version control system, in that case every environment should have some kind of indicator allowing to implement something like:

if ($_ENV('ENVIRONMENT') == 'dev') {
    $config['google_tag.settings']['container_id'] = 'GTM-000000';
} elseif ($_ENV('ENVIRONMENT') == 'stage') {
    $config['google_tag.settings']['container_id'] = 'GTM-AAAAAA';
}

Another option to indicate which snippet to use depending on the current environment (i.e., Dev, Stage, QA or Production), is to use the Configuration Split module. This module contains functionality to create conditional splits.


Programmatically added block does't appears in block admin page I created a programmatically block in a custom module for Drupal 8.1. The custom module and the block plugin are created via Drupal Console.

I installed my module and I clear cache via drush cr, but when I go to the admin block page, my block does't appear.

For view an example, I installed the "examples module" and the "block example module". When I do that, there aren't blocks example" in a block admin page too.

I don't understand.

The content of my block class form my custom module is the following.

/**
 * @file
 * Contains \Drupal\nomads_pdf\Plugin\Block\nomads_pdf_block.
 */

namespace Drupal\nomads_pdf\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'nomads_pdf_block' block.
 *
 * @Block(
 *  id = "nomads_pdf_block",
 *  admin_label = @Translation("Nomads_pdf_block"),
 * )
 */
class nomads_pdf_block extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->t('Hello, World!'),
    );
  }

}

My custom module structure is the following.

Did you use the button "Place block"? The block does not appear in the block layout by itself. The block layout is a bit misleading by providing the disabled section, which suggests that all blocks not used are listed there.

The technical background is, that the block layout only lists blocks that have a configuration. When you install a module with a block plugin this block is not registered with a configuration entity yet. That happens when you press the button "Place block" for the first time. You can do this multiple times to get multiple instances of the block. The configured blocks will keep their configuration entity and will stay in the block layout, even when disabled.


How do we interpret a Drupal's URL? I am a newbie to Drupal, and have used CakePHP and Codeigniter frameworks earlier. In Codeigniter, a URL such as /users/show/1 would be interpreted as it invoking the show() method of the Users class, passing 1 as user ID. Can we interpret a Drupal URL in this way?

If we have a URL similar to /admin/xyz?u=1, where in the admin module can I find this?

Also, I know Drupal uses a good bit of path alias. Would that affect this in a big way?

If your looking at code, all the hook_menu function calls is how the non alias paths get created. Things like users and nodes use a % in the path creation; this turns into the argument for the page callback function. Read more about this here: Wildcard Loader Arguments.
node_menu()

function node_menu() {
...
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );
...
}

user_menu()

function user_menu() {
...
  $items['user/%user_uid_optional'] = array(
    'title' => 'My account',
    'title callback' => 'user_page_title',
    'title arguments' => array(1),
    'page callback' => 'user_view',
    'page arguments' => array(1),
    'access callback' => 'user_view_access',
    'access arguments' => array(1),
    'parent' => '',
    'file' => 'user.pages.inc',
  );
...
}

The function that handles this menu information is menu_execute_active_handler().
Aliases happen as the 2nd to last part of the bootstrap in the drupal_init_path function. It converts /about-us into node/4 for internal use.

For more in depth information check out this link: Drupal menu system (Drupal 6.x)


Internal relative links in Menu by using http:/alias/path/to/link In Drupal 7.22, I would like to link create an additional link to an existing node from with in a menu. This target node already has an alias and its own menu entry. I'd like to create an additional link to that node. I thought the method would be to enter the url as http:/alias/path/to/link. However, this seems to fail.

If you notice from the devel_themer output that the path contains http:/contact. My hope that this link resolves to http://mysite/contact.

You should be able to go to /admin/structure/menu, select the menu you wish to add the link to, and list links. At the top select Add link and enter the title and link. You can use either the alias or system path. Then on the list, place the new menu item where you want it. It should not overwrite the existing menu entry.

Do not prefix the links with http:.


Commerce product fields as optional attributes I'm trying to create some kind of product attributes by adding fields in manage fields in Store | Product types. Is there any solution to give product creator ability to select which fields he want to use when adding product. Creating product types containing all possible situations would be strange.
Example:
I create one customizable product, but I want to give it 4 various attributes. For another creating product I could select checkboxes for different attributes.

You probably want to group products that a similar into the same product types and setup different product types, instead of having a single multipurpose product type that can be turned into anything. The product creator can decide which fields to use by choosing which product type to use. A distinction that will come very naturally for non technical people.


how to make drupal use mysqlnd_ms I have installed mysqlnd_ms plugin , created the mysqlnd_ms.json with following configuration.

{
  "myapp": {
    "master": {
      "master_1": {
        "host": "mysql://drupal@1x4.xx6.x.1x9",
        "port":  3306,
        "user": "drupal",
        "password": "password",
        "db": "site2"
      }
    },
    "slave": {
      "slave_0": {
        "host": "mysql://drupal@1xx.1x1.xx9.2x1",
        "port":  3306,
        "user": "drupal",
        "password": "password",
        "db": "site1"
      }
    }
  }
}

its still not splitting the queries! how will drupal work withmynsqlnd. Do i have make edits in setting.php

That extension's operations are transparent to the application, you only need to configure the host that the DB connection is setup with.

From a Drupal point of view, you just need to update the "host" entry for the relevant database in settings.php to match the name of your mysqlnd_ms application. From the looks of your config file that's myapp, so your database connection might look like this:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'foo',
  'username' => 'bar',
  'password' => 'baz',
  'host' => 'myapp',
  'prefix' => '',
);

If that doesn't work, check that the extension is installed, configured, and enabled.


How can I join content in Drupal I'm having a little bit of trouble with joining 2 different content types in a view.  I'm am using Entities and View modules.

What I have is about 50 satellite offices and each office has a varying number of employees.  I have created a content type of "Office" and created a separate content type of "Employee".  Using the Entities module, I enter a new employee into the system and assign them to a particular office.

Now, what I want to do is basically build a view where I can look at an office, see it's information (address, etc) and also see a list of employees associated with that office.

I've got the relationships and everything set up so the data pulls over, however, the issue I'm running into is duplication of some fields that I don't want to show twice.

Here's what happens:  If Office 1 has two employees, the data returned shows Office 1 twice, each with a different employee.  What I want is for Office 1 to show ONCE, with a list of all employees at that office.

I've tried grouping options, but that doesn't work right either.

Any ideas on how to get this formatted the way I need?

Try to exclude the field you're grouping by from display:


Bypass node access with Panels I'm using modules Content Access and Panels.

I need to modify the appearance of a node according to its accessibility by the user.

With Panels, I made 2 variants with selection rules (page "Node template"):

when the node is not accessible
when it is accessible.

But when the user has no access to the node he has a denied access and not the panel.

Do you know how to bypass node access with Panels?

To overrider the default Access Denied page of the Drupal, you have to change the path of this page.

To change the page path, follow these steps:

Go to admin/config/system/site-information.
At the bottom of the page, there is a Error Pages section.
There is a field Default 403 (access denied) page. Provide your custom panel page link.
And the save it.

I hope it will work.


How is DRUPAL_CACHE_PER_USER handled for anonymous users? If a block is set to use DRUPAL_CACHE_PER_USER for caching, will the block be unique for each anonymous user, or the same for all anonymous users?

For reference from API docs:
hook_block_info
DRUPAL_CACHE_PER_USER

Looking at includes/common.inc source it appears to be based on uid, so I'd assume it would use the same block for all anonymous users (uid = 0), but wanted to double-check in case I could use this instead of DRUPAL_NO_CACHE (doing geolocation-driven results in the block).

elseif ($granularity & DRUPAL_CACHE_PER_USER) {
  $cid_parts[] = "u.$user->uid";
}

(lines 6084-6086)

Yes. If a user is not logged in then uid is 0. So all anon users share the same user id.

I guess you will have to do your own caching, e.g. based on the IP address.


Specific number of values in field setting per role Is there any way to limit user input a field with 1 value in select list, but make it unlimited for admin?

Sure.  You can manipulate the multiple characteristic of the select via a form_alter() hook.  You just have to make sure the field itself is a multiple value field to start with, and then do something along these lines:

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

  if ( /* your user is NOT an admin */ ) {

    if ($form_id == 'YOURNODETYPE_node_form') {

      $form['#field_info']['field_NAMEOFTHEFIELD']['multiple']=FALSE;

    }

  }

  // any other form alters here

}

If this doesn't work out of the box for you, a drupal_set_message() and print_r() of your $form will give you a dump of what you have to work with, and you basically just want to find the multiple array key for the field in question and change it to FALSE for non admins.

But once again, you need to make this field a multiple value field to begin with, but you then don't allow non-admins to enter multiple values into it on the form.

(More information on the Form API can be found here for D7 if this doesn't work as the above is just a quick edit on a D6 testbed here)


Create chart for fivestar note I'm using Drupal 7, and Fivestar.

I try to display notes in the format of a pie chart.

If the note (= rating) is 5,2 on 10, I would like to have a circle of this type :

I tried Charts (with Google Charts as its charting engine) and Google chart Tools, but I do not manage to obtain what I wish (using the Views integration).

With Google chart tools, I have this problem (only one value is shown), and with Chart nothing displays (i do not use aggregation, just fivestar field in views).

Would you know a solution?

A tabular of the data which I wish to display :

Solution 1 - Use Charts to create a pie chart
The sample image in your question doesn't look like a pie chart to me, instead it rather looks like a Gauge chart. If you want to try to create a pie chart anyway, using the Charts module, then have a look at this feature request (which allows you to pass "library specific options"). Comment #9 in it contains a patch that you'll need for it (using Google Charts as the rendering engine).
After you applied that patch, you'll be able to pass any of the specific options to the Google Charts charting engine that correspond to the chart you're trying to create.
If applying the patch is not sufficient, then I'd recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.
Solution 2 - Use Charts to create a Gauge chart
Your sample image in your question rather looks like a Gauge chart. Have a look at the Charts issue about Support for gauge charts. After you apply the patch included in comment # 4 of this issue, you'll be able to use the Charts API to create such Gauge charts (using Google Charts as your charting engine). BTW, you can also use this specific SimplyTest.Me  link (which has this patch enabled).
Here is a sample of 2 such charts I created in my own environment (using that patch):

The first (left) chart is to show a rating like 5.7, and the second (right) chart is to show a rating like 7.2 (both ratings on a scale of 10). Attention: I haven't found any specific option (yet) to show that value of 5.7 (and 7.2) in the Gauge chart, instead of the rounded value 6 (and 7) near the bottom. Though the (red) pointer within the chart seems to correctly reflect the actual values already.
My PHP code for rendering the above 2 Gauge charts looks like so (the various options I used should be self explaining):
<?php

 $chart = array(
    '#type' => 'chart',
    '#chart_type' => 'gauge',
    '#chart_library' => 'google',
    '#title' => t('Gauge Chart'),
    '#min' => 0,
    '#max' => 10,
    '#width' => 300,
    '#height' => 300,
    '#greencolor' => '#00AA10',
    '#greenfrom' => 0,
    '#greento' => 5,
    '#redfrom' => 8,
    '#redto' => 10,
    '#redcolor' => '#FF3333',
    '#yellowfrom' => 5,
    '#yellowto' => 8,
    '#yellowcolor' => '#66BB88',
    '#minorticks' => 5,
  );

echo "<p>Left Gauge chart (= Rating 1) : 5.7 / 10 ; Right Gauge chart (Rating 2) : 7.4 / 10 </p>";

  $chart['rating1'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 1'),
    '#data' => array(array('Rating1', 5.7)),
  );

  $chart['rating2'] = array(
    '#type' => 'chart_data',
    '#title' => t('Rating 2'),
    '#data' => array(array('Rating2', 7.2)),
  );

  $example['chart'] = $chart;

  return drupal_render($example);
?>

If you paste the above code in the body of any content type that allows using the PHP filter, and assuming you have a working internet connection (prereq to use Google Charts), you should get a similar chart in your own environment (provided you also enabled the patch mentioned before).
With the above solution that uses the Charts API, it should be possible to use the same technique for adding an extra column in your tabular Views display, using "rewrite results", in which you also refer to the actual value of the Score column for each of your views result rows (so that you get 1 Gauge chart somewhere to the right of your Score column).
Disclosure: I'm a co-maintainer of the Charts module.


Cache Backport not loading correctly. Unable to change cache.inc location? Drupal 6, trying to get the Cache Backport module working. Every time I load a page, this error fires:

Call to undefined function _cache_get_object() in /var/www/sites/all/modules/cache_backport/cache_backport.admin.inc on line 60,

That is defined in cache.inc within the cache_backport module's folder. It would appear that the file isn't being loaded. Here's the relevant portion of my settings.php file.

$conf['cache_inc'] = 'sites/all/modules/cache_backport/cache.inc';

Simple enough.

I'm using the Domain module and looking around the config files, I did notice references to cache but I can't really tell their purpose. Also, and this may or may not be related, but prior to trying the cache backport module I tried just doing the Drupal 6 memcache module and it never seemed to send anything to it. The memcache area in Reports would load, it was communicating with Memcached, but it never seemed to write anything to it. I feel like it was caused by the same thing.

The Domain module was in fact responsible for this. I moved include './sites/all/modules/domain/settings.inc'; to the very end of my settings.php file and everything started working.

I then added the following code to ensure a different cache_prefix for each of the domains.

$thishost = $_SERVER['HTTP_HOST'];
$site_arr = explode('.', $thishost);
$sitename = $site_arr[1] . '_';
$conf['cache_prefix'] = $sitename;

Credit for that code goes to Drupal 6 APC with domain access module not working for (sub-)domains. In fact, now that I look at that page again, I notice that he has the domain access include on the last time, too. Audible sigh. Don't know how I didn't notice that before.

It also appears that if you want to move Domain's settings.inc to the bottom, you need to make a tweak to that file. Modify modules/domain/settings.inc so the domain_settings_setup_ok function looks like this:

function domain_settings_setup_ok() {
  static $state = NULL;
  if ($state === NULL) {
    if (!empty($conf['cache_include'])) {
      $state = TRUE;
    }
    else {
      $state = !function_exists('cache_get');
    }
  }
  return $state;
}

That is an adapted version of the patch for D7 discussed at https://drupal.org/node/1240472.


Entity Reference - am I using it correctly? I need a bit of help with entity references. I have Customer Profiles entity and Credit Card entity. I'd like to be able to create "credit cards" and attach them to customer profiles so that if I click hte customer profile, I'd see any credit cards attached to them. I'm not sure how to do this. I've created the credit card content type, added a reference field to it that references the customer, but I'm not sure how to display the filtered credit card entries on the customer profile. I've tried adding an entity reference field to the customer profile back to the credit cards but don't know how to filter the results.

My brain hurts a bit at this point.

One way to do it is with Views and a module called Eva (Entity Views Attachment).  Eva allows a view to be attached to a host entity, and understands how to filter the view based using the host entity's id to display only related information.

Since you already have the entity reference field on the credit cart type, the steps would look like this:

Install Eva and Views as needed
Create a View for the credit card content type
In the view, add an "EVA" display
Configure the view to be attached to the customer (under Entity content settings)
Add a Contextual filter using the field that links back to Customer. This will filter credit cards using the customer profile entity


Recommendation for hosting Git VCS from my drupal installation Our community does a lot of coding work (lua, c#, php, etc) and we are looking to move away from the usual repo hosts (BitBucket/GitHub/Jenkins) and make our website more of an all-in-one experience. I've been trying to find guides for hosting a git repo and browser from a drupal installation, but all I can seem to find is installing/updating drupal with git. Are there any modules for hosting a personal git repo?

Look at Case Tracker for project SCM hosting from Drupal:

  Case Tracker enables teams to track outstanding cases which need
  resolution. This module was inspired by the issue handling in project
  module, but unlike Project module, which is specific to software
  development, Case Tracker was designed to be a generic issue tracker.

  Case Tracker is usable right out of the box as a basic ticketing
  system, it's default UI is minimal but feature complete. The module
  was designed to be extended by programmers and site builders to meet
  complex needs, and so tries to avoid making too many assumptions about
  all the ways it can be used.

  Drupal 7

  7.x-2.x - it is an Entity based approach(#1653184: Case Tracker 7.x-2.x - a new approach, with entities) and is on heavy development. As it's based on Entity API, it has a deeper integration with Views,
  Rules, Message and a lot of other modules natively.
  7.x-1.x - has the content types for Project and Cases working without problems. The Notifications, Actions and View integration that needs
  to be tested.

This module is D6 specific but look at Case Tracker Commits as well.

See also Project which powers Drupal.org itself, and the modules it uses such as Versioncontrol Project and its dependant modules.


Custom resources: load entity by uuid I have created a custom resource which extends the EntityResource class. This way I can use all build in functionality that Drupal core provides on the default entity resource, but I can still add some extra checks. This works perfectly fine.

I defined my canonical route in my resource as /api/my-endpoint/{node}. In this way, I can fetch and patch nodes by the node ID. After careful consideration, I want to implement /api/my-endpoint/{node_uuid} or even /api/my-endpoint/{node_custom_field} to fetch (and patch) a node by UUID.

Of course, Drupal doesn't know this param and cannot load the corresponding node object, which results in fatal errors.

How can make I this work?
I tried to implement a custom RoutingParamConverter class, but I didn't got it to work.

As long as you have the uuid of an entity you can use Drupal's entity storage interface to load it given that property. It should be as simple as using the loadByProperties method.

$node_loaded_by_uuid = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['uuid' => $your_uuid]);
$node_loaded_by_uuid = reset($node_loaded_by_uuid);

UPDATE: milkovsky is correct. loadByProperties returns an array. If you want the actual node object at the top of it you will have to use the reset function.


How to disabled Drupal builtin "poormanscron" cron when using Ultimate cron? I want to disabled Drupal 7 builtin "poormanscron" to then put it into a crontab task as it should, but when using Ultimate cron module i do not see an option to disabled Drupal 7 builtin "poormanscron"

Do i have to uninstall ultimate cron?

You don't need to uninstall any module. The setting you are looking for is on admin/config/system/cron/settings/poorman.

Change Launcher to -- Disabled -- from the default Serial, and Poormanscron should not run anymore.

If you disable or uninstall the Ultimate cron module, Drupal shows the equivalent settings in admin/config/system/cron, at the bottom of the page.

In this case, change Run cron every to Never.


How to show 404 page for not found images If I request an image that doesn't exist like mysite.com/test/test_not_found_image.jpg, I get a Not Found white page just like this page: https://www.drupal.org/files/testing_404.jpg.

Is it possible to have Drupal show the styled 404 page that I have instead of that white 404 page?

While @Shawn Conn's answer does work it does cause issues in Drupal because of image cache. If you go to a page that doesn't have the image style created yet it won't create the image because of the .htaccess rule.

The best way to display a 404 page on bad images is to use the Fast 404 module and create a static html page.


Use Webform to email users with query parameter or argument? I want to be able to have a contact form that lets visitors send email to different users (like a staff directory) without exposing the email address or user id. I am going to come up with my own way of identifying users to not expose Drupal specific information. Anyway.

However, I need to:

Pass that value in the URL to identify the user to locate, to know where to send the mail
Load and check the user from that passed value before showing the form
If the user is not a certain role, serve a 404 instead of a form (only certain roles can be contacted).
Preferably have a url like /staff/{FOO}/contact where {FOO} is my custom value.

Would it be easier to just implement this myself, or rely on Webform? I wanted to take advantage of Webform in case the client wanted to add another field later or create other forms (more basic ones), throttle repeat submissions and the dozens of other things Webform can do.

Pass that value in the URL to identify the user to locate, to know where to send the mail
  Load and check the user from that passed value before showing the form
  If the user is not a certain role, serve a 404 instead of a form (only certain roles can be contacted).
  Preferably have a url like /staff/{FOO}/contact where {FOO} is my custom value.

If you want to make a webform integrated module, you can achieve all of the above by altering certain webform's route(s) & maybe service(s).


Let users rank pages I'd like to let users rank pages (thumbs up/down) and display “most popular” pages in ranked order. What's the best way to do this in Drupal?

Socially ranking content is a feature Drupal can provide very well. You will want to use a combination of modules consisting of something like:

Views (used to build the lists of content and order them by votes / popularity),
Voting API (a frame work for scoring / aggregation and will be used to record votes)
Vote up/down (Vote up/down widget for user input on voting). you can even look at something like Fivestar.

Once you have chosen and setup your voting widget on your content you will need to setup some views to display them in lists order by votes. Typically you will create a page view for any landing pages such as a Home Page and a block for displaying in sidebars on content pages. I also use Quicktabs for the Blocks so you can have a nice tabbed interface which lists content by Most recent / Highest Rated / Most viewed etc.

On setting up the actual views you will need to add in fields for what you would like to show in each list. For example on a highest rated you might want the node title and the score for the node as voted for by users. Then you will add in a sort by option for the score so the list is presented in the correct order


How to create a view block of one content type filtered by author? I have a Book Club website which has a page created from a view where different members can add their recommendations. I want to create a block view which can be inserted into a Panel Page for each author, but I am struggling to get the contextual filters and relationships to work.

Below is the basic setup of the view page.

This is the contextal filter setting.

This now works if I put a user name into the context preview section.
I thought if I added a user context to the panel page this would then allow me to add the user name into the block, but I don't get this option.

I eventually got this to work by using a page view with a path /reading-list/% rather than trying to make it work through panels.


Entity reference, save only value I am looking for the best approach to do the following:

I have a content type Product and a content type Invoice, where i can reference products.

I would like to be able to save the referenced products AT THAT TIME (with their price info).
So when the product is changed in the future, the invoice will not be updated with it.

Any suggestions on how to approach this best?

Thanks in advance!

as far as i can see there are 2 options, and both would involve writing some custom code.

1st, provided that you have enabled product revisions, when saving the invoice, save that particular revision number and then load your product based on that revision.

2nd, would be to add product fields that you are interested in, to you invoice (price, desc etc.) and based on the product attached save those in form validation handler


how to unset admin menu links programmatically? how to unset admin menu links programmatically ?

I have created a module with this hook in it

function myModuleName_menu_link_alter(&$item)
{

//  dpm($item['link_path']);
     if($item['link_path']=="/admin/config/people")
    {
     $item=FALSE;
    }
}

the link path

  "/admin/config/people"

is listed with dpm.

how can i remove it from the admin menu?

I have also tried with this hook

  function my module_menu_alter(&$items) {

       // dpm($items['user/%user/cas']);
        unset($items['user/%user/cas']);
  }

hook_menu_alter is want you are looking for. The usage is exactly the same as your example, just don't forget to clear the caches afterwards.

Cheers!


Variations price adjust based on previous variation Using Drupal Commerce, is there a way to adjust the variation price base on the first or second variation selected?

For example I have 3 variations: size, material, color. If I choose Small (that costs $5) and material that costs $10 ($15 total), then when I choose Large at $12, the material should cost $20.

I guess I should use rules. Has anyone done this?

http://www.drupalcommerce.org/user-guide/product-attributes-variations - here you can read about product variations, don't forget to enable field as an attribute field that can change the Add to Cart form

After that you need to create products for all variations with right prices. You can use http://drupal.org/project/commerce_bpc


Media selector returns value ZERO I have a custom form for with media selector from media module. The form field is as below.

$form['image'] = array(
      '#title' => t('Image'),
      '#type' => 'media',
      '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
      '#default_value' => array('fid' => $current_image),
      '#media_options' => array(
        'global' => array(
          'types' => array(
            'image' => 'image',
          ),
          'enabledPlugins' => array(
            'upload' => 'upload',
            'media_default--media_browser_1' => 'media_default--media_browser_1',
          ),
          'schemes' => array(
            'public' => 'public',
          ),
          'file_directory' => 'subpage_banner',
          'file_extensions' => 'png gif jpg jpeg',
          'max_filesize' => '1 MB',
          'uri_scheme' => 'public',
        ),
      ),
  );

When I select an image and post the form, I get the field value as an empty array. below is the print shot of my $form_state variable.

Array
(
    [identity] => 9
    [path] => contact
    [image] => Array
        (
            [fid] => 0
        )

    [fid] => 0
    [language] => en
    [removed] => 0
    [submit] => Save
    [form_build_id] => form-zFkFCgBCHtesrAYOQrQXC3Ug_sMBg68dwgWwRE-Y2Ls
    [form_token] => i_aIpfgcwSz-7d_H0U48C5SUOkWlVAkBTz1M8yokXtg
    [form_id] => sitegeneral_settings_banner_sub_update_form
    [op] => Save
)

How do I get the selected image's fid?

Added the following code

'#tree' => TRUE,

working charm!!

added after:

'#title' => t('Image'),
'#type' => 'media',
'#description' => t('...'),


How to rewrite field with php in views? I need to do a string replacment with php on a title field in views 3 / drupal 6.So i would to know the best way because after research i found these:

use Views PHP module
use Computed fields module
use PHP in the views template
use a template file   like field.tpl.php (only for D7 ?)

Thanks for tips.

I'm afraid you should never use PHP in Views, as the link mentions you should write your own Views handler or Plugin, it's not that hard


Is it possible to get access to files uploaded via FTP in the media module in Drupal 7 I installed media module to select files from server instead of directly upload them but in the library tab only the http uploaded files are available not the FTP uploaded files. Is it possible to get access and select FTP uploaded files via media module?

Is it possible to get access and select FTP uploaded files via media module?

No.

When you upload the files yourself (via FTP or some other means that is not part of Drupal), they will not be recognised or known by the Media module.

There are a helper module called Filefield Sources that let you add files downloaded with FTP to Drupal media management modules.  A variation called IMCE Filefield currently integrates with the IMCE module, but there is AFAIK nothing similar for the Media module.

It has suggested to integrate Filefield Sources with the Media module. However, there does not seem to be anybody working on it, (just a lot of people who want it).

If you really want this, you probably need to add this to the Filefield Sources yourself.


Custom Breadcrumbs remove duplicates I am using custom breadcrumbs and almost all is working well but a few issues. One problem stated in another question, this problem is that on the landing page of my views I am getting home >> Homme >> Homme. I need to remove the duplicate. I see there is a form in the configuration for breadcrumb visibility. Is this where I solve this problem. I see no other way to do this. Does anyone know or have the code I need?

I think you could use theme_breadcrumb($variables) in your template.php to remove duplicates.

Code could be something like this:

themeName_breadcrumb($variables) {
  [...]
  $breadcrumbs = array_unique($variables['breadcrumb']);
  [...]
}


Show repeating event just once in Views while sorting by date When using repeat date API on a field, Drupal allows you to group events so they don't appear multiple times.

However, when sorting by date it seems like Drupal ALWAYS shows all of the entries no matter what.

How can this be avoided?

I just ran into this issue myself.  The solution is to add a filter of the date delta field =0.  This means only show the 0th (first) matching item and hide any repeating values.

Hope this helps someone.
Selwyn


How do I programmatically fix local menus to be shown only for a content type? I am using the following lines in a links.task.yml file.
x.nodename_updates:
  route_name: view.great_view_name1.page_1
  base_route: entity.node.canonical
  title: 'Updates'
  weight: 50

x.nodename_subscriptions:
  route_name: view.great_view_name2.page_1
  base_route: entity.node.canonical
  title: 'Subscriptions'
  weight: 50

The submenus are shown on all nodes. I would like to show them for a single content type, but when I use the entity name in the base_route such as entity.TYPE.canonical, it doesn't work. It works for other entities that are defined in classes with annotations.
I know it is possible to fix it through hook_menu_local_task_alter(), but this is something I believe can be fixed within the links.task.yml file.

I don't konw if there's a better way to do it now but few years ago I did it using a custom access: https://stackoverflow.com/questions/36496998/drupal-8-how-to-add-task-and-contextual-links-for-specific-node-type/36636263#36636263
In my case it was easier because I was creating the routes in my module.
Since your routes are created by views you would need to implement a RouteSubscriber to alter the route, add the _custom_access and _node_types requirements.
/!\ Warning: I am not sure since I never tried it on views routes but it might conflicts or breaks the rules you've set from the views UI to access this view. It should be compatible with a _permission rule, maybe not with an _entity_access rule.
yourmodule/yourmodule.services.yml
services:
  yourmodule.route_subscriber:
    class: Drupal\yourmodule\Routing\RouteSubscriber
    tags:
    - { name: event_subscriber }

yourmodule/src/Routing/RouteSubscriber.php
<?php

namespace Drupal\yourmodule\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('view.great_view_name1.page_1')) {
      $requirements = $route->getRequirements();
      $requirements['_custom_access'] = '\Drupal\yourmodule\Access\ByNodeTypeAccessCheck::access';
      // Replace 'my_node_type' with the name of the node type you want.
      // Since it's an array, you can add more than one node type.
      $requirements['_node_types'] = ['my_node_type'];
      $requirements['node'] = '\d+';
      $route->setRequirements($requirements);

      $options = $route->getOptions();
      $options['parameters'] = $options['parameters'] ?? [];
      $options['parameters']['node'] = [
        'type' => [
          'entity:node',
        ],
      ];
      $route->setOptions($options);
    }
  }

}

yourmdule/src/Access/ByNodeTypeAccessCheck.php
namespace Drupal\yourmdule\Access;

use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Check the access to a node task based on the node type.
 */
class ByNodeTypeAccessCheck implements AccessCheckInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(Route $route) {
    return NULL;
  }

  /**
   * A custom access check.
   *
   * @param \Drupal\node\NodeInterface $node
   *   Run access checks for this node.
   */
  public function access(Route $route, NodeInterface $node) {
    if ($route->hasRequirement('_node_types')) {
      $allowed_node_types = $route->getRequirement('_node_types');
      if (in_array($node->getType(), $allowed_node_types)) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }

}


Memcache interfering with Simpletest Adding some tests to an older Drupal 7 site and a few of the tests check for the presence or lack thereof of custom cache items.

Having this in settings.php seems to interfere with Simpletest using default database cache (this is included to settings.php as a local settings override):

  $conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
  $conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
  $conf['memcache_stampede_protection'] = TRUE;
  $conf['cache_default_class'] = 'MemCacheDrupal';

  // The 'cache_form' bin must be assigned no non-volatile storage.
  $conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

  // Don't bootstrap the database when serving pages from the cache.
  $conf['page_cache_without_database'] = TRUE;
  $conf['page_cache_invoke_hooks'] = FALSE;

  $conf['memcache_servers'] = array('cache:11211' => 'default');

Is there any global flag I can look at at this point to determine whether or not to add these overrides in?

I tried checking the $GLOBALS for a test id and drupal_valid_test_ua but in both cases the memcache information was still used.

If I comment out the memcache settings, I can see the cache tables in simpletest are populated as expected. How can I get around this?

edit: looks like testing specific settings.php is not possible in 7.

I wound up creating a new site in Lando and a new site folder just for simpletest. I created a site directory for my main site and moved settings.php into that, and installed a minimal Drupal site to the other.

This resolved my issue, since the site/db specifically for SUT does not use memcache.


OG - Apply membership to children I'm wondering if there is en option to apply og membership to all the entity referenced children of an node.

I have a content type 'Enterprise' which can reference itself to create a structure of enterprises. F.e. (Enterprise 1 --> Subenterprise 1 --> Subsubenterprise 1)

When enterprise 1 is added to a group all dependent nodes should be added also.

Thanks in advance for your advice

You can do that with Views Rules.

Create a view that gives all directly referred children of a node (with the node as contextual filter), give it a "Rules" display.
Now create a Rules component that takes as argument a node, runs a "View Loop" (you'll see what that is as soon as you've installed the above mentioned module) over your newly created view.
To this loop, add an action that adds the current loop item to your organic group. Save the component.
Add a second action to the loop, which is the component itself, with the current loop item as an argument. (I haven't actually tried this.)
You can call this rule component from within other rules that you can trigger in many ways, say by clicking a simple button or by performing a bulk operation.

My two cents:

Be careful with this, since it is recursive. If you have two enterprises linking each other, then this will recurse infinitely and crash. Maybe add as a precondition in the rule component that the node is not yet a member of the group.
Decide whether you want to use entity references or organic groups for this, but don't use both. What you're trying to do sounds a lot like you have a network of enterprises and sub-enterprises and you want to translate your existing network into organic groups. If someone adds new references, you'll have to update your groups, which is annoying. Decide between entity references and organic groups and get rid of the other.


Drupal 8 - some child pages are not visible on particular book using view I would like to ask for your help as I'm having a trouble in displaying some child pages of a particular Book in Drupal 8 using view. There's a book which displayed all the child pages but there's some book which displayed incomplete child pages and some book, doesn't display the child pages at all.

I created two views, one for the list of all top level book and the other one is for the child pages.

Here's what I have done on view settings:

to display the list of book:

Format: Unformatted list
Show: Fields
Filter Criteria:
  Content Published (=Yes)
  Content: Content type (= Services)
  Book: Depth (= 1)
Sort Criteria: Content: Title (asc)

to display the child pages:

Format: Unformatted list
Show: Fields
Filter Criteria: Content Published (=Yes)
Sort Criteria: Content: Title (asc)
Contextual Filters: (Book Parent) Content: ID
Relationships: Book Parent
Configure Relationship: Book Parent : Required this Relationship

After saving it, I added this to the block layout.

I'm not sure what went wrong on my settings.

Thank you in advance for you help!

I'm not too experience in Drupal.  But normally I would not use Views for the child pages.  If the book module is enabled, the BOOK NAVIGATION block will be available to list with hierarchy like a table of content.  You can select in the option to display only for book pages under a particular book.  Not sure whether this helps.


Show a ctools modal after form submit I have a form:

//...
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Sumbit'),
);

I need when this form is validated and submitted then show a ctools modal.

This is my hook_menu for the modal:

$items['thankyou/%ctools_js'] = array(
    'title' => 'Thank you',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'page callback' => 'thankyou_callback',
    'type' => MENU_CALLBACK,
  );
ctools_include('ajax');
ctools_include('modal');

ctools_modal_add_js();

The callback function:

function thankyou_callback($js = NULL) {
  // Content that we place in the popup.
  $popup_content = t('Thank you!');

  if (!$js) {
    return $popup_content;
  }

  ctools_include('modal');
  ctools_include('ajax');

  $output = array();
  $output[] = ctools_modal_command_display(t('Greetings'), $popup_content);

  print ajax_render($output);
  drupal_exit();
}

My form submit:

function myform_submit($form, &$form_state) {
  // ...
  // show my modal here
  modal.show();  // ???
}

Then, How I show a ctools modal after form submit?

Please, with not ajax callback.

You need call form to Popup by function ctools_modal_form_wrapper

Any error, message will show in popup, to check submit success you need use statement

if (!empty($form_state['executed'])) {
    $output[] = ajax_command_replace('#modal-content', 'Thank you');
}

Or you can use ajax form to call ajax.

$form['markup'] = array(
    '#markup' => '

'
  );
//You need markup for wrapper
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Sumbit'),
    '#ajax' => array(
      'wrapper' => 'pop-up',
      'callback' => 'modal_form',
    ),
  );

And function submit form

function modal_form($form, &$form_state) {
  //Process data when form submit
  ctools_include('modal');
  ctools_modal_add_js();
  $commands = array();
  $commands[] = ctools_modal_command_display('Form Submit', 'Say Thank You');
  print ajax_render($commands);
  exit;
}


Using theme_image_style() I am trying to display thumbnails of uploaded images in a custom form. While I can see the images in my form array after uploading them to the tmp directory in Drupal, here is what I am trying to use to display them:

$url = file_create_url($form_object->uploads[$key]->uri);
$output .= '
'.theme_image_style(array('style' => 'form-preview', 'path' => $url)).'
';

While $url points to the file resource, I cannot show a resized image for the life of me. If I use an img tag and put $url as its source, the images do show up, but they are huge.

Can I not call theme_image_style() because these are just temp images and not permanent? I can make them appear with theme_image().

As always, the Drupal documentation has the answer. You need to move the file to the files directory. Also you should never call a theme function directly but instead call the wrapper theme function so:

theme_image_style(...) // Don't do this ever

theme('image_style', ...) // Do it like this and make themers happy.

From the API docs:

  $variables An associative array containing:

  style_name: The name of the style to be used to alter the original image.
  path: The path of the image file relative to the Drupal files directory. This function does not work with images outside the files directory nor with remotely hosted images.
  alt: The alternative text for text-based browsers.
  title: The title text is displayed when the image is hovered in some popular browsers.
  attributes: Associative array of attributes to be placed in the img tag.


How to login when you have a default page setup with panels? I have been messing with panels.  I set a default layout page that basically has no content and is set for all the pages at the moment.  I logged out like a dummy and now when I go to website/user/login it gives me a blank page.  Is there another way I can login?

Thanks!

If you have access to drush, you can generate a one time login link use drush >    uli. Other than that, I'm not sure other than manually restoring to a back-up - lukedekker

Awesome!  That worked.  I was trying something else the other day with drush that wasn't producing results.


How can I have "Table view" as the default result instead of "Submissions“ When viewing the results page of a webform node, the submissions views is the default one.

We then have the possibility to display data using these secondary links:
Submissions, Analysis, Table, Download, and Clear.

I'm looking for a way to thange the order of these links.
I would like the table view to be the one displayed by default, instead of the submissions view.

The first part of the screenshot shows how the module works; the other half shows the order I would like for the tabs.

You may need to do this in a custom module. In your custom module, implement hook_menu_alter:

/**
 * Implements hook_menu_alter.
 */
function MYMODULE_menu_alter(&$items) {
   // Node webform results.
  $items['node/%webform_menu/webform-results'] = array(
    'title' => 'Results',
     // the page callback here is what will display the table.
    'page callback' => 'webform_results_table',
    'page arguments' => array(1, '50'),
    'access callback' => 'webform_results_access',
    'access arguments' => array(1),
    'file' => 'includes/webform.report.inc',
    // Change the weight to change the order
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,

  );
}

Once you added that to your custom module. Make sure the module is enabled, and clear all caches.


How to remove the size attributes of all fields? Size attributes just get in the way of responsive forms, and I realize most form fields can be overridden by CSS, but field types like input[type="file"] still do not behave well if a size attribute is set.

See this JSFiddle example.

Since field elements are classed out well, I'd much rather purely rely on CSS for field sizes. So, how can size attributes be removed from all fields?

For text fields the size attribute is forcibly added in theme_textfield(), so the only way would be to override that function in your theme and remove that bit of code:

function mytheme_textfield($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'text';

  // 'size' removed from this call
  element_set_attributes($element, array('id', 'name', 'value', 'maxlength'));

  // add the rest of the function...

Exactly the same thing goes for the file element (see theme_file()), and most likely for any other element type you need to do do this for.


Image field unlimited values doesn't save just the first image..the others disapear on save I have a weird problem that appeared with my latest drupal installation
I have a content type with some image fields that have an unlimited value (I can upload more images to the same field)
When I press SAVE only the first image remains saved..the other ones..don't
No error is given..
Nor on screen nor on logs..

my drupal version is 7.8
memory limit 96M
Apache/2.2.13 (Unix) mod_ssl/2.2.13 OpenSSL/0.9.8g PHP/5.2.11 with Suhosin-Patch
Mysql 5.1.38

Seems to be that is a bug from Drupal fixed in the last release (7.9) according the release note.


Adding temporary field to form to print ID's When writing modules, especially in the "hook_form
_alter" hook, I find myself in the same situation many times:

I want to control some $form fields and I'm searching the field ID, the right attribute convention, etc.

I'm trying to print all the fields and their attributes to the output page so I could do that every time I need information about a form fields.

How can I print all the fields complete attributes?
I need to stick it temporarily in the page - how can I send the details to the page (I don't know what are the fields ID's...)?

Devel - Helper functions for Drupal developers and inquisitive admins.

Add in hook_form_alte function dsm($form); and refresh your form page, you will get message with structured info.


How to clean the html output of textfield using CKeditor? I have a textfield using the wysiwyg http://drupal.org/project/ckeditor text editor module.

If I insert a table in the text then the table is wrapped with the following tags

    &nbsp;

I thought that the http://drupal.org/project/htmlpurifier module would remove this tags but it doesn't.

How can I remove these lines?

I have run into this, I'm not sure if there is a configuration value to avoid this. I usually end up installing Empty Paragraph Killer.

  Empty paragraph killer is a filter module, helpful on sites which use
  WYSIWYG editors.

  People often hit the return key twice at the end of a paragraph. Most,
  if not all site layouts manage the paragraph spacing, so the extra
  empty paragraphs created can detract from the look and feel of a site.
  This module filters out the empty paragraphs of all user-entered data
  on a site. It does so by following the fundamental Drupal way -
  non-destructively.


Translate homepage meta Title and description I have a Multilingual Drupal 7 site using i18.

But how do I get my homepage meta Title and description translated?

You need to install the variable translation module.

  The Variable translation module, part of the Internationalization
  (i18n) package, allows you to translate text and settings that are
  stored in Drupal as variables. These variables include text such as
  'site name' and 'site slogan', as well as settings like 'Default front
  page' and 'Default 404 page'.

Go to

  admin/config/regional/i18n/variable

and select the variables you would like to translate.
Then translate the string(s) at

  admin/config/system/site-information


How do I theme repeating dates output field? I currently have a calendar of events and each event has multiple repeating dates. Now when i display them it shows all those repeating dates in a long list. How would i theme this to show only if there are more than 3 dates to display":

Has multiple dates in the coming month

I was thinking of doing this via tpl's, but what should i name my tpl as to override this output?

Using template_preprocess_field seems to do the trick. You can either put this in your themes template.php or in a custom module.

function YOUR_THEME_preprocess_field(&$variables) {

    $most_repeating_dates_to_show = 5; // set limit of how many repeating dates is acceptable to show

    if($variables['element']['#field_name'] == 'field_date') { // Put your actual field name where it says "field_date"

        $num_repeats = count($variables['items']); // get count of how many repeating dates there are

        if($num_repeats > $most_repeating_dates_to_show) {

            $nid = $variables['element']['#object']->nid; // get the nid of the parent node

            // set the title of the link to show how many repeating dates there are
            $link_options = array(
                'attributes' => array(
                    'title' => t('See all :num repeating dates', array(':num' => $num_repeats))
                )
            );

            $link = l('Has multiple dates', 'node/'.$nid.'/repeats', $link_options);

            $variables['items'] = array(0 => array('#markup' => $link)); // here we overwrite the whole array of items so only our link will show

        }

    }

}

I've added a bit of extra functionality turning your text "Has multiple dates" into a link that links to the full list of repeating dates.


Views sort criteria setup by number of fields I am using views with exposed so visitors can search on items that are published by other users.

Content type that views is showing has 50 fields (+ 3 taxonomy fields with around 200 terms).
Only 7 fields are mandatory. Rest are there to better describe the item. Rarely someone uses all fields but most are using half.

Reward for using as many fields+terms as possible per content would result in higher position in view sort criteria.

Example: Users A and B have 2 nodes each.

A1 = 7 fields used

A2 = 12 fields used

B1 = 8 fields used

B2 = 10 fields used

Views results: A1, B1, B10, A12

Is there a way to do this with views ?

It should be something like this. (It is not the exact code, but it will help you.)

function findNodesByUser($userID) {
$result = $query
  ->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1)
  ->propertyCondition('type', $type) //Where $type is the type of node
  ->propertyCondition('uid', $userID)
  ->execute();
}

function createArray() {
    customArray = array();
    $users = entity_load('user');

    foreach ($users as $user) {
        $user_nodes = findNodesByUser($user);
        foreach($user_nodes as $user_node) {
            customArray[$user . $user_node] = count(field_get_items('node', $entity, $field_name));
        }
    }
}


Are Drush vbo-execute actions supported? I've been trying to find an efficient back-end way to delete large numbers of nodes based on some filter criteria to implement data retention policies. I have read that it's possible to perform actions provided by views bulk operations on results from a view via drush - such as in the answer in the screenshot below (in response to this question).

This seems like a very powerful concept because you can use the selection power of views and do operations on large amounts of data from the server side. I tried to do this on my Drupal 9 site. One discrepancy I noticed is that when I go to add the VBO field, I do not have an option for "Bulk Operations: Content" like is suggested in the above screenshot, rather only the one from the "Global" Category:

I tried using that field anyway, and selected the "Delete selected entities/translations" option and saved the view.
When I try to execute the action from the view using the drush command
drush vbo-execute my_view_id action::views_bulk_operations_delete_item
I get the following error:
In ViewsBulkOperationsActionManager.php line 169:

  The "action::delete_action" plugin does not exist.

I cannot seem to find this error in any other forum posts, or any documentation from VBO as to how to identify what actions are available. Is this capability for VBO not available for Drupal 9, or is there some knowledge base I have missed that details how to specify the action?

After much searching to no avail, I decided to dig into the VBO codebase. It turns out that I was using the wrong action id (the 2nd argument to the drush command after the view id). Whatever action id was being used in the post I referenced is not the right one (either it was custom or VBO has since changed the convention for action id's). I discovered this by finding the file that implemented the action (delete) that I wanted, which happened to be in /drupal_root/modules/contrib/views_bulk_operations/src/Plugin/Action/EntityDeleteAction.php. This file has an annotation block that specifies the action id to use:
namespace Drupal\views_bulk_operations\Plugin\Action;

use Drupal\views_bulk_operations\Action\ViewsBulkOperationsActionBase;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Delete entity action with default confirmation form.
 *
 * @Action(
 *   id = "views_bulk_operations_delete_entity",
 *   label = @Translation("Delete selected entities / translations"),
 *   type = "",
 *   confirm = TRUE,
 * )
 */
class EntityDeleteAction extends ViewsBulkOperationsActionBase {
...
}

running drush vbo-execute my_delete_view views_bulk_operations_delete_entity did the trick! No idea why there doesn't appear to be any documentation about this (at least that I can find), but I'm glad I finally figured it out and hopefully this helps someone else having the same trouble.


How to use short codes with arguments I came across this. That shows how you can get a code like {{ cta }} populated with any data you want, and get that inserted in a template. I want the same sort of solution, but for content. In other words, let's say I have a blog post, I want to be able to add:

{{ cta }}

or

[[ cta ]]

or any convention that works. But the end result is that I must be able to populate the variable via code.

BACKGROUND INFO

I have a bunch of events on my website. I often write blog posts where I refer to events on the site. To add dynamic content to my blog posts, I'd love to simply add things like:

{{ events || from:19dec2014 || to: 23dec2018 }}

I would then populate these with the correct information.

Any ideas on how to do this correctly?

Try the Shortcode module. It was the among the first hits when I searched for Drupal 8 shortcode.

For the second part of your question I'd recommend Insert View. You can embed a view via a short code in your content and also pass arguments to it.

  Insert View is a filter that allows users to embed content lists
  generated by the Views module into node bodies and blocks using
  relatively simple tag syntax.

  Why would you want to use an Insert View tag when you could just
  invoke a view using PHP? Simple. When you want to allow users to
  insert views or edit content on a page with an inserted view without
  granting them permission to use PHP.

  The tag syntax is [view:name=display=args]

  The parameters are: view name, view display id, view arguments.

  Valid examples:

  [view:my_view] is replaced by the content listing.
  [view:my_view=my_display] invokes the view using the specified display.
  [view:my_view=my_display=arg1/arg2/arg3] invokes the view using the specified display and passes arg1, arg2 and arg3 to the view.
  [view:my_view==arg1/arg2/arg3] passes arg1 to the view and will use the "default" display set for the view.


Set the id property of a form element using D6 Form API? I want to set the id property of an input element of a form that I'm creating in a module using the form API. I'm doing this  I looked up the documentation and it says this:

id
INTERNAL. Used to populate form elements' id property. In rare cases,
you can set this value yourself on a form element, to override the
default setting.

It doesn't really say when I can or can't use it, so I'm hesitant to try to do this, since I can't rely on it.
I'm writing some javascript that has the id of the element hard-coded into it. Should I use the Drupal-generated id in my script instead?

I would avoid changing that at all and use the Drupal-generated IDs in your Javascript. I have never been forced to do otherwise.

Keep in mind, however, that you'll have better luck if you use classes or if you prefer IDs that don't have a node ID or other sequence-based ID in them. For example, I try to avoid using IDs when theming webforms because if I create the webform on another site, the ID will change.

If there are existing styles for what you want to do, I would check which selectors they are using as well.

Remember that you can add your own classes with the theming layer and then you can use them for your Javascript or jQuery. Sometimes this is the best choice, and I've done it numerous times.

If worst comes to worst, implement hook_form_alter and change the #id in question. If your form continues working, then you're good.


Taxonomy Term for a sports team I have taxonomy terms for teams ( say team one , team two , etc ) and content types of teams that have team pictures of your team.

Im trying to figure out how to create a view that will show a player that selects team one as their team, and then show them on team one.

I have the view created and its a table, I just can't figure out how to get each player on each team.

If I understood right, you want a view to display players of each team. For that, you could:

1) Create a taxonomy vocabulary for each team (which you have already done)

2) Add an image field to the taxonomy term, as you would do to a CCK (admin/structure/taxonomy/[your_vocabulary]/fields

3) Create a CCK for "Player"

4) Add a field to the "Player" CCK of type "Term reference" (choose your Team vocabulary in the settings), so every time you create a new player you can select which team they belong to

5) Add the fields you need into your view, add a filter for the taxonomy term and expose it, so it will come out as a select list

I hope this helps a bit :)