How to actually set a maxlength for textarea field in contact form I need to limit the textarea message of the core module contact form to a certain number of characters.

Here are the facts

The Form API does not allow one to set a maxlength on textarea field types [while plain HTML does]
The Maxlength module , doesn't allow you to actually set a maximum length. It gets its max length from the field's max length, defined on each content type's manage field section
Creating a new form element type using hook_element_info, still doesn't gurantee I can add the #maxlength to the textarea. Besides if I succeed I need to alter again the contact form module to overrride actual message textarea field with mine.

So I can I alter it plain and straightforward?

What is the best idea to alter all textarea fields in the website?

The Form API does not allow to set a maxlength on textarea field types [while plain HTML does]

That's not strictly true....HTML5 introduced a maxlength property for textareas, previous versions do not have it (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

The default templates that come with Drupal 7 all use XHTML, so the lack of explicit support for HTML5 makes perfect sense.

As long as your doctype is HTML5, this will probably work:

$form['element'] = array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 200),
);


Automatic Search with Search API I created a view block based search API module.

I want displayed in this block similar products to the product currently being viewed.

When I get the word "mint" in the value of fixed contexuel filter "full text search", I have products containing "mint" that appear in the right column.

I want the text title field and body field are sought instead of "mint".

I parameterize filters API search index, not to seek unnecessary words.

How to do this ? How to set the pop filter?

Thank you

You are viewing a Product Display Page. Therefore your context is the nid of the Product Display you are looking at. You now need to load the title and body field and pass that as a string to your view's contextual filter.

You can do this in various ways:

Use
hook_views_pre_view
in a custom module

  Allows altering a view at the very beginning of views processing,
  before anything is done.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after.

  Parameters

  $view: The view object about to be processed.

  $display_id: The machine name of the active display.

  $args: An array of arguments passed into the view.

You implement this hook in a custom module
check the $view argument for your view's name and display id
load the Product Display using menu_get_object which will return the $node.
Inspect $node to get the title and body, which you then concatenate and you then
set this as the argument on $args which is one of the parameters passed by reference to hook_views_pre_view

.

Use Views Field
View

  There are a lot of cases in views where you want to embed a list
  inside each row. One example could be, you have a list of groups, and
  for each groups you want to list the first and last name of all of
  their members.

  This can be achieved with this module, as views_field_view allows you
  to embed one view into another view and pass arguments along.

For this method you create a parent view block of Product Display (nodes) and for the contextual filter take the node id from the url. This is the view that will display your related products. After you have constructed it test it so that it shows the exact same product as the product page you are embedding it on.

So now you have a block that shows the same Product Display as the main page shows. Now you need to link it to the search api view.

First change the fields. Make sure that you have title field and body field added to your parent view, then set them to be hidden. Add a global text field and using the tokens from the above two fields add them with a space between them as in : [title] [body] so that the title and body is now one field. Again set this field to be hidden.

Because you installed Views Field View you can now add another field Global:View field. This field allows you to select a view to embed. You now select your search api view. It also allows you to pass parameters to the view, so you select the token for the global text field that is hidden.

Lastly set caching to some time value for this view so that it performs quickly.

ADDED

For option 1 (custom module) the code will go roughly like this (I currently don't have Drupal installed so I can only provide pointers. You will have to inspect the $node object via dpm() to get to the body field, which may be on the Product Display node or on the referenced Product type)

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "VIEWMACHINENAME" && $display_id == "VIEWDISPLAYID") {
    $node = menu_get_object(); // defaults are fine
    dpm($node); // comment out when code works
    if (isset($node->content...)) {  // inspect output from dpm to get field
      $argument = strip_tags($node->content...); // same field from if statement
      $args = array($argument);
    }
  }
}


Shortcode in template I have installed and configured Shortcode in a D8 project. However, when I try to use a short code like [column] or [button], it gets rendered as is in the node view page.

I have used a block panel in the node view page. And the in the block template I have rendered the body field like {{ content['#node'].body[0].value|raw }}.

However, I have noticed, that if I render the content as a whole like {{ content }}, the short codes gets rendered properly as intended.

What am I doing wrong?

You shouldn’t render field values like that. You should be doing it as {{ content }} or {{ content.field_name }}.


Language dependant sidebars vice-versa Due to lack of php knowledge i cant find where i am mistaken and how it`s better to do this. I have several languages one of them LTR and the other RTL and i need sidebars to be displayed vice-versa. It means that in LTR menu would be in the first and in the RTL it would be in the second sidebar. The code returns '1' somehow and breaks the markup.
Please help me to modify this code:

global $language;
switch ($language->language) {
case "en":
if ($page["sidebar_first"]):
print "".print render($page['sidebar_first'])."";
endif;
if ($page["sidebar_second"]):
print "".print render($page['sidebar_second'])."";
endif;
break;
case "ar":
if ($page["sidebar_second"]):
print "".print render($page['sidebar_second'])."";
endif;
if ($page["sidebar_first"]):
print "".print render($page['sidebar_first'])."";
endif;
break;
}

You missed the position of the string operator . You can try the code mentioned below.

    global $language;
    switch ($language->language) {
    case "en":
    if ($page["sidebar_first"]):
    print "".print render($page['sidebar_first'])."";
    endif;
    if ($page["sidebar_second"]):
    print "".print render($page['sidebar_second'])."";
    endif;
    break;
    case "ar":
    if ($page["sidebar_second"]):
    print "".print render($page['sidebar_second'])."";
    endif;
    if ($page["sidebar_first"]):
    print "".print render($page['sidebar_first'])."";
    endif;
    break;
    }


How can I get the field settings in a field preprocess hook? How can I get the field settings in a field preprocess hook?

You can fetch the field settings in a preprocess hook by using the following code.

function YOUR_THEME_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'field_event_date') {
    $node = $variables['element']['#object'];
    $field_name = 'field_event_date';
    $instance = field_info_instance('node', $field_name, $node->type);
    $display = field_get_display($instance, 'default', $node);
    $variables['event_date_formate'] = $display['settings']['format_type'];
  }
}


How to display users associated with a node through Views I would like to create a View that displays users associated with a certain nid.

Under contextual filters, I have checked Content: Nid and selected

Provide a default value - Content ID from URL

Under Relationship, I have selected

Entity Reference: Referencing entity

Then under Fields, I have selected

(User referencing Content from field_office) User: First Name (First Name)
(User referencing Content from field_office) User: Last Name (Last Name)

But nothing is being displayed when I type in my nid into Preview with contextual filters

Essentially what I am trying to do is perform the following query:

$args = array(':nid' => $node->nid);
$results = db_query('SELECT USER_ID FROM USER INNER JOIN node ON USER.OFFICE_ID =
  node.title AND node.nid = :nid', $args);

I have done this before, but accidentally deleted the View. Now I am unable to make the View again, thought the DB structure has not changed at all.

Could someone please point out what I'm missing?

It seems to me that since your node reference field is on your user object and you want to list users, all you have to do is:

create a view listing Users
add a contextual filter corresponding to your entity reference field. The entity reference field on the User should appear in the contextual filters list. Choose that one.
Choose where the contextual filter value is coming from. If your view will be at myview/nid, where nid is the node id you want to use to filter, then you don't need to choose any other behavior. If you'll be displaying this view on a node page, use the default->content id from URL option.
Choose your user name fields without relationships. There is no relationship needed unless you need to bring in fields from the node being referenced.


I'm trying to configure memcache module and failed to load dmemcache.inc Anybody could have an Idea why I get this error
    Failed to load required file sites/all/modules/memcache/dmemcache.inc.

I installed memcache properly on my server, but when I go to drupal Report, I got the above message

I'm using drupal 7

This is from my PHPInfo()
memcached
memcached support   enabled
Version     2.1.0
libmemcached version    1.0.8
Session support     yes
igbinary support    no
json support    no

Directive   Local Value Master Value
memcached.compression_factor    1.3 1.3
memcached.compression_threshold 2000    2000
memcached.compression_type  fastlz  fastlz
memcached.serializer    php php
memcached.sess_binary   0   0
memcached.sess_lock_wait    150000  150000
memcached.sess_locking  1   1
memcached.sess_prefix   memc.sess.key.

**** UPDATE ****
in order to make it work, I added that to the settings file

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

  // The 'cache_form' bin must be assigned to 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;

thanks a lot

Modifications to settings.php are required. Read the docs on how to configure it. Here is an example configuration I use with two memcached servers:

$conf['memcache_key_prefix'] = __FILE__;
$conf['cache_backends'][] = 'sites/all/modules/contrib/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['lock_inc'] = 'sites/all/modules/contrib/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;
$conf['memcache_servers'] = ['172.16.12.51:11211' => 'default', '172.16.12.52:11211' => 'default'];


Show block on specific pages URL attribute I am looking to show a certain block on a page only when a certain url attribute (using alias)

For example:

I have pages /foo/*

I want to show the The block when viewing /foo/*?showblock

Where * is a wildcard.

I have tried typing this into my "Show block on specific pages" portion of the block settings, but the block never shows. Any ideas? Thanks!

You can use PHP visibility on your block settings to achieve this. Drupal block's visibility does not provide the functionality to display blocks based on parameters after ? (aside from ?q= of course) so you need to do this with custom PHP.

Set your block visibility to use PHP as the markup and place this in your code:

<?php
// Show the block if the 'showblock' attribute is available
if (!empty($_GET['showblock'])) {
  return TRUE;
}
return FALSE;

?>

Happy Programming!


Order of drush commands for automated deployment? What order should the following drush commands be ran?

config-import
updatedb
entity-updates

Also, I see entity-updates fail a lot due to field_delete_data* tables existing. How can I delete them as part of my automated deployment?

Drush 10.3.0 now provides a deploy command to standardize how Drupal deployment works. This command performs the following:

drush updatedb --no-cache-clear
drush cache:rebuild
drush config:import
drush cache:rebuild
drush deploy:hook

Database updates always come before configuration import! Support for automatic entity updates has been removed from Drupal core (change record) and entup has been removed from Drush core. Whenever an entity type or field storage definition needs to be created, changed or deleted, it has to be done via hook_update_N().

Here is the updated deployment routine I'm happiest with.
drush state:set system.maintenance_mode 1
drush cache:rebuild
git pull
composer install --no-dev
drush cache:rebuild
drush deploy
drush state:set system.maintenance_mode 0
drush cache:rebuild

This also means you have to run two releases if you want to uninstall and remove a contrib module. First release to deploy the updated config that disables the module. Second release to deploy the updated composer.json and lock file after you removed it with Composer.
To make real consecutive releases possible you might want to pass the current release's commit SHA1 to the deployment script and then replace git pull with a more exact routine (where $1 is the SHA1):
# If not empty 1st argument passed to the script, do:
if [ -n "$1" ]; then
  git reset --hard "$1"
else
  git pull
fi

Otherwise the consecutiveness can not be guaranteed when you push two new releases at once or within a short period. As then the first release's triggered git pull will simply pull the latest changes (from the second release), where instead it should pull only the changes included in the first release. See the full sample repo leymannx/drupal-circleci-behat.
Credit for this git snippet goes to CircleCI. This is how they are doing it in their containers.


Find drupal site root directory path We have hosted one of our Drupal 7 site at Acquia.

How do I find site root directory - /mnt/www/html/mysite/docroot/?

  I'm using dpr(shell_exec("drush status")); command in devel/php

Is there anyother way to find it?

Use DRUPAL_ROOT.

It is defined in index.php as:

define('DRUPAL_ROOT', getcwd());


Add icon to module's menu item in Administration menu I've searched for a bit and I haven't found a solution to my liking: I want to avoid adding more modules to the project.

I'm very new to Drupal, so I have minimal knowledge on that matter. I have this project which somebody else has made. They created a module which adds a menu item on the Administration menu. What this module doesn't do, is add an icon to the menu item, which makes it look bare.

I want to add a custom icon I've made next to the menu item text. The reason it needs to be a custom icon and can't be fontawesome (or anything of its liking), is because it has to be a variation of the site logo.

Is there a way to accomplish this without adding more modules to the project, or is adding more modules the only way?

It's Drupal 8 with Lightning on Debian 9 with Apache2.4 and PHP7.2.

I figured it out. Now, this might not be the very best way to solve it, and some things should probably be changed, but this will be fine for now. Let's assume the module name is pizza.

First, create a directory called css. Inside this folder, create a css file with the name of the module. In this case it would be pizza.css.
Since there needs to be an icon next to the module's menu item title on the administration menu, this is the CSS we'll need (or similar):

.toolbar-icon-pizza-main::before{
    background-image: url('../../../../../sites/default/files/pizza-icon.png');
}

Second, we will need a libraries file in the module's root (where pizza.info.yml is located); call it pizza.libraries.yml. Inside this file write something along the lines of this:

toolbar-icon:
  version: 1.0
  css:
    base:
      css/pizza.css: {}

Here, base probably should be changed to theme, since this is an aesthetic to the module.

Third, move into pizza.info.yml, we need to include the library we made into the module. Add this to the bottom:

libraries:
  - pizza/toolbar-icon

Fourth, move into pizza.module, where we're going to add this:

/*
 * Implements hook_toolbar_alter()
 */
function pizza_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'pizza/toolbar-icon';
}

This fixed it for me.
Source:
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


Ordering taxonomy view by date added I have an taxonomy and an view that displays it.

This view has default sorting by Taxonomy term: Weight (increasingly). I would like to add, as second criteria (when the weights are equal) the date when taxonomy term has been added.

Unfortunately on the list under criteria -> add I cannot see anything date-related:

Where should I find the date of term has been created?

Try using the Taxonomy Creation Date module. It adds creation and updated date rows to the database, so you should be able to use it in view.


Update no results search text I want to change the default search help text 'Check if your spelling is correct.
Remove quotes...' that is displayed when there are no results.

What's the best method of practice for this? Should I override the value in a template.php function? If so how do I go about this?

The easiest thing for you to do would be to override the actual template file which displays that language.

Look at the template file called search-results.tpl.php in the core search module.

It has the following code at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

Copy the entire template file (you don't even need to rename it, it'll override the file in the module) and paste it into your own theme's /templates folder.  Re-write the section I've pasted at the top to be whatever you want.  The part that prints the search_help() is the bulleted list you're looking to change.

Of course, before the system will pick up your new template file, you need to clear all your caches!

Let us know if this works!


How do I get the taxonomy term ID from its name? The only function on the list of taxonomy.module functions that looks like it does what I want appears to be a private function (_taxonomy_get_tid_from_term).

What function am I supposed to use if all I know is the taxonomy term name and I need to find out its ID?

taxonomy_get_term_by_name() will do the trick:

$terms = taxonomy_get_term_by_name($row->field_term_name);
if (!empty($terms)) {
  $first_term = array_shift($terms);
  print $first_term->tid;
}


no search_api_solr results when search term ends with number I have search_api_solr with views (I use as external Solr server https://hostedapachesolr.com. )

There is this strange issue:

1/ When I search for 951, there are correct results

2/ When I search for V951L, correct results

3/ BUT ... when I search for V951: there are NO results at all ...

This weird behavior stays the same, even when I alter the "views" settings or the search_api_solr settings.
It's like the system is confused that the search term begins with a letter and ends on numbers.

Does anybody knows how to fix this ?

Best regards

I would try this.

Go into The solr server configuration - assuming it's named 'solr'
/admin/config/search/search-api/server/solr/edit

In Advanced, see if "Targeted content domain" is set to scientific. And see the description next to it to see why I'm thinking this might be your issue.

Save. You'll probably need to re-export your config zips and definitely need to clear and re-index.


How to show the number of times a page has been shared by all services total? Is it possible to show a small block (using code or a module or something) that shows how many times the page a user is on has been shared using ANY of the available sharing methods?

For example, I'm trying to use the social sharing module AddThis and I'm showing the Facebook, Twitter, and Pinterest, and Email icons (although I also want to use the 'more' icon to show all the others).

And I want a little box to the right of those that just shows how many times the page has been shared. Is this even possible?

you could use:
Social Share Counter Module

This module is clearly inspired by the share buttons used by Mashable.
This module gives the share counts for only Facebook,Twitter and more
which has some excellent features in more elegant manner. If you have
a website, then you definitely need this module.

If you still want to use AddThis, then use Social Stats Module

This is a statistics module. It provides data from various social
media sites. The data which is saved per node. It includes data from:
Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one
count, share count & total count Total Share Count : total across all
available social networks Note: This module is intended to collect the
statistics per node from the networks mentioned above.
It does not actually provide sharing widgets for the social networking
sites. They have to added manually, or using other modules. List of
the modules recommended to use alongwith Social Stats are:

Service links
AddThis


WYSIWYG+CKEditor outputting span with style attribute I have a strange behaviour on the text editor on my D7 site.
I am using WYSIWYG-7.x-2.1 module with CKEditor v.3.6.3.7474.
If I type:

test
test
test

on the editor then Disable rich-text I can see:

test

test

test

Which is correct. Now if I Enable rich-text and then put my cursor at end of line 1 then press delete, it makes the 2nd line join the end of the first line:

testtest
test

Then I press Return again to separate those lines:

test
test
test

Now if I Disable rich-text I get:

test

test

test

As you can see it has created a span tag with line-height css.
It not only does this for paragraphs, it also changes heading tags, like H2 will get changed to a span with style attributes that duplicates the display of h2 but it's a span inside a paragraph tag...
A lot of different developers have worked on this website, but I can't reach them to ask what they did, they probably won't remember anyway.
So I'm asking if anyone else has had this issue and could point me in the right direction. Is it CKEditor config? WYSIWYG config? Drupal config? Version bug? Tried to search Google but don't get much relevant results.

So i might not have the most informed answer, but i think i have a solution:

I face the same problem on our D7 site.

It turns out, if you use Chrome, content you paste in the WYSIWYG usually gets these strange line-spacings. (Regardless of if you choose "paste as plain text", or copy-paste from Notepad).

Use Firefox - and you wont see any <span style="line-height: 1.538em;"> stuff in the HTML!

If anyone knows how to use Chrome and not have these span elements show up - please let me know!

Cheers,

R


How to add a flat amount to an order. Using Drupal commerce module I need to add a flat amount to an order using the http://drupal.org/project/commerce module.

Lets say I have a order with 3 products then I need to add an amount of 230€ to the total order cost. This amount is a flat amount (it will ever be 230€), it doesn't care how many products there are in the order.

I would use a Sales Taxes type tax but since it only accept percentages it is not useful for me.

You should be able to accomplish that using Rules.

Create a product that has the flat amount of 230€ and use the Rules action "Add product to the cart" to add that product to the cart.

To create the rule:

Create a Rule for event "After adding a product to the cart"
Add the "Order contains a particular product" condition to check if the
order already has the flat amount product
Then add the "Add a product to a cart" to add the flat amount product to the order

You could add the same rule for the "After removing a product from the cart" event, so if they remove the flat rate product, it would just re-add it to the cart.


Composite Primary Key for a Content Type Is there any way to create a composite primary key or equivalent for a content type in D7? I really need a way to stop the duplicate content for the same content type.

Thanks

An easy way to do this is with the Unique Field.  This provides a WYSIWYG interface for adding node validation to the node save form to check one or more fields' uniqueness.

The module is not bulletproof, though.  There are some scenarios where you can get around it.

  This module is intended to function when a node is being validated prior to being created or updated. It does not prevent nodes from being programmatically saved with duplicate values (including when a node is reverted to an earlier revision).

The reason is that the check is done at the code level via validation and is not a database enforcement via composite keys.

A similar module, that also provides a lot more features in addition to the uniqueness check, is Field Validation.

If you want to give the composite key thing a shot, I would make a test site and edit one of the field tables by hand to make the composite key.  Then install/enable Unique Field and see what happens with the cases that the module doesn't cover.


Why don't content changes appear on front end? I'm new to Drupal and have been asked to update a page's content. Thought this would be easy, but I'm having trouble.

I login, click on Content, find the page I want to edit and click Edit. I make changes to the content (just text) and click 'Save'. I navigate to the page I changed and refresh but nothing has changed.

I tried clearing both my browser's cache and Drupal's to no affect.

I double checked the URL and it matches.

I reloaded the page(node?) on the back end to confirm it had saved my changes, which it did.

How do I actually update the content of a page?

Found I was saving it as a draft, not as published.


I want to import content I have 2 sites running Drupal 8; the first one is a Drupal 8 beta 10 site, while the second one is a Drupal 8.0.5 site.

I made many changes to content types, but almost all the fields are identical (such as body, date, entity reference).

How can I import all the content from the first to the second one? In Drupal 7, I could use node_import, which doesn't exist in Drupal 8.

In time Drupal will have Drupal 8 -> Drupal 8 migration, but it will be a while since migration from D6 and D7 is more important. Right now there aren't any easy solutions for this.

The most sound solution would be to create a service on the beta site that exposes the data on the beta site and create a script that fetches this.

You can use RELAXed Web Services to help creating webservice on the beta site.


How to move fields into secondary region where Menu Settings are located? We have a need to move the language selector field to right column in the same section as the Menu Setting (see screenshot). Using Twig Debugging, we found that the template node-edit-form.html.twig can be used, but we could not find a way to selectively move select fields such as the language selector. We did notice a Secondary Region in the twig template, but could not see a way to selectively move the field so that if the field exists on the content type.

Goal:

Add language selector to the secondary region.
No additional styling is needed, just move the field.

How do we move the fields to the secondary region on the node-edit page??

This can be done in two ways:

1) Use the Field group module.

Field Group has added the ability to move items to the right sidebar on the node edit form, via the "Details sidebar" group type in the dropdown.

2) Write a hook_form_alter() in a custom module.

If you have more complicated needs than what Field Group provides you can do this in custom code.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Select the desired entity add/edit form.
  if (is_array($form['#theme']) && in_array('node_form', $form['#theme'])) {

    // Ex 1. Move an existing field container wrapper to the sidebar.
    if (!empty($form['field_myfield']) && $form['field_myfield']['#type'] == 'container') {
      $form['field_myfield']['#type'] = 'details';
      $form['field_myfield']['#group'] = 'advanced';
    }

    // Ex 2. Move an existing field to the expanded 'meta' section of the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#group'] = 'meta';
    }

    // Ex 3. Move a field group provided by some contrib module to the sidebar.
    $form['somecontrib']['widget'][0]['#group'] = 'advanced';
    $form['somecontrib']['widget'][0]['#open'] = FALSE;

    // Ex 4. Create a custom collapsible container in the sidebar.
    $form['mycontainer'] = [
      '#type' => 'details',
      '#group' => 'advanced', // This line places the container in the sidebar
      '#weight' => 99,  // ensure it displays last or use -10 to show it first.
      '#title' => t('My custom sidebar settings'),
      '#tree' => TRUE,
      '#access' => TRUE,
    ];

    // Ex 4.1 Move a field into the custom container in the sidebar.
    if (!empty($form['field_myfield'])) {
      $form['field_myfield']['#weight'] = -1; // reset weight
      $form['field_myfield']['#group'] = 'mycontainer';
    }

    // Ex 4.2 Some fields have an inner widget that need to be moved instead.
    if (!empty($form['field_myfield']['widget'])) {
      $form['field_myfield']['widget']['#weight'] = -1; // reset weight
      $form['field_myfield']['widget']['#group'] = 'mycontainer';
    }

  }
}


Where to see the result of hook_menu() What is the purpose of hook_menu(), if I can create menus from the administration pages?

function onthisdate_menu() {
  $items = array();

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'page callback' => 'blog_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  $items['blog/feed'] = array(
    'title' => 'RSS feed',
    'page callback' => 'blog_feed',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

so now where do I see the result of this function in the admin panel or in the site where the module is rendering?

hook_menu() is the method used by modules to add their own menu items. Most of the menu items you see on Drupal are added by modules with that hook.
The user interface allows you to add extra menu items that are not added by modules.

If you are asking the difference between creating a module that adds menu items with hook_menu(), and adding menu items with the user interface, hook_menu() allows to do things that are not possible with the user interface. For example, the menu that is visible when you hover the gear icon visible for a block is created with menu items added with  hook_menu(). (It requires the Contextual links module, which is a Drupal core module.)

The tabs that you see, for example, on a node page, are created with hook_menu(), or hook_menu_alter(). You could not create them with the user interface.

What you can create with the user interface are links that go:

In a menu block

In the Menu links

In the Secondary links


Translate strings in custom module I'm working on a module for a D7 site that generates a block. Unfortunately all the HTML is hard coded and I need to make it translatable. I have done the following:

Changed

$output = "
Page title here
";

to

$output = "
".t('Page title here')."
";

but no amount of clearing caches or refreshing strings gets "Page title here" to appear in the translate interface. I've loaded the page and even changed the text but it does not show up. I'm aware of the case sensitivity of the search

Is there something I'm missing?

As usual, I work it out shortly after posting a question. Here's what I needed to do if anyone else has this issue.

The block I was trying to translate was only configured to display on the en version of the page, so I enabled it to be displayed on the other language's page as well.
I enabled translation for the block as a good measure.

After that the string popped up in the translation interface.


How to fire a Rule after adding a new file in multi-value field? Working with Drupal 7.56, Rules 2.10, Conditional rules 1.0-beta2 and File Entity 2.4

I can't fire a rule when I add a new image in a multi-value Image field (related to File Entity for inline fields).

I need to act when a new file is added and also when an existing file is updated (each image has inline fields for caption and details) but I can't find the right way to build my Rule?

At the end, I need to fire a rule when a new image (file) is added to send data (fid, url, inline fields values) to an external database and I need another rule when I updated the inline fields of an image (file) to update the external database.

Does anybody has a tip here?

Already tested : Event "Before saving content", Condition "Data comparison" between updated and unchanged node (NOT equals returns always true...), module File Field Rules...

Related :

Using Drupal 7 Rules, how to react to a file upload and change a node field?

Writing custom PHP code in Rules to check if a file field has a new value

Here is my last try (a little bit modified for clarity) with a simple message on site to check if the rule fires :

{ "rules_image_insert" : {
    "LABEL" : "image insert",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_pictures" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-pictures" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "file", "id" : [ "list-item:file:fid" ] },
                "PROVIDE" : { "entity_fetched" : { "picture" : "picture" } }
              }
            },
            { "CONDITIONAL" : [
                {
                  "IF" : { "entity_is_new" : { "entity" : [ "picture" ] } },
                  "DO" : [
                    { "drupal_message" : {
                        "message" : "NEW picture!!",
                        "type" : "warning"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

To process a multi-value field with Rules,  you should use a completed different approach, which is related to the Rules Condition "List contains item" (and/or its negations).

Have a look at this rules example (in Rules export format), which processes a multi-value field also, though in my case it is a list of eMail Ids (replace "eMail ID" by "picture" to match your case):

{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-email-addresses" ] },
          "ITEM" : { "previous_email_id" : "Previous eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node:field-email-addresses" ],
                      "item" : [ "previous-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [previous-email-id:value] was removed from the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just replace the machine name "field-email-addresses" by "field-pictures" (prior to import), you should be able to experiment with this rule in your own site to see it at work.

Here is a sample of the messages I get when I update an article, and while doing so I add 1 more eMail ID and at the same time I remove an existing eMail Id:

Value user3@example.com was removed from the multi value field.
Value user2@example.com was added to the multi value field.

So the clue to make this work is:

first iterate over all field values of your field of the unchanged node (to find the removed values).
then also iterate over all field values of your field of the changed node (to find the inserted values).

Obviously, this does note explain how to find the "updated" values. But think about my sample scenario: another way to look at it is that I updated value user3@example.com to user2@example.com. Not sure if it is a complete answer to your question, but admit it is already pretty close, no?

Note: As an alternative to using the Conditional Rules module (as you also seem to be doing already), you can also rework the relevant part of my Rules example into performing equivalent Rules Components. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Is it possible to use public:// for inline images (in text) to protect against changes in config? There's a similar question here, but it concerns D6 or D7. It seems to me the suggested solution won't work in Drupal 8 for two reasons:

It's very unadvisable to attack the database directly with SQL, you should be using Entity queries and the API
As of D8, inline images become managed files, and are referenced as being attached to the nodes in which they appear - another reason for using the API.

I'm in the middle of writing a Drush command whose purpose is to go through all the inline images migrated from an existing (D6) site, detect them, enter them into the system as managed files, and attach them to their nodes. Looking at the file_managed table in the database, I see that the file URI is always public://something.jpg (for example), so that if you add an inline image via CKEditor then (with the default settings) it will be public://inline-images/mypicture.jpg (for example).

Well that seemed to me very cool, because it protects you from changes in the public files settings (for example, if you're building a site with shared code for multiple domains and the public files folders will change when it goes into production). So I started trying out using a URI in body text something like this:

But this doesn't work: the image doesn't show up and if I try saving it, the "public" gets removed so that it looks like this: .

When I enter an inline image through CKEditor in the normal way, I get something like this:

Is there any way of persuading the inline images to use "public://"? Or should I be looking at the Media Entity module (which I wanted to avoid, because it's overkill for my requirements)

Your issue is (currently) covered in the Drupal issue queue here against Core-8.2.x. This was committed to 8.2.x 4 months ago and I would imagine is in core - reading the issue should let you know which parts have been resolved.

I haven't found any non-core workarounds for this issue at present, the basic concept (from D6/D7 is an input filter to translate public:// URIs into canonical URIs when the content is rendered).

Issue Link: https://www.drupal.org/node/2666382

EDIT

It appears that only part of this change has been finalised, there is another issue suggesting that final resolution for this problem will occur with 8.3.x

Issue Link: https://www.drupal.org/node/2755223

It's possible (based off your description) that things are working as intended i.e. public:// values should be replaced with their canonical counterpart during the rendering. If this isn't the case I'd suggest following up with the second issue link above.


Open Id Connect SSO on cross platform sites I have 3 sites(all were sub domain sites)

Server(id.test.com) - .NET
Client1(client1.test.com) - Drupal
Client2(client2.test.com) - .NET

Am using OpenId Connect for login. My login & logout using drupal site is successful. But when i login through Client2 and navigates to Client1 site automatic login was not made, when i initiates a click in "Login using Generic" button, login occurs.

Is that possible to login automatically? I have checked OpenId Connect SSO module which supports only for Drupal sites. Is there is any other way to achieve this?

The OpenID Connect module is designed only to login your users when they use the login button(s).

The SSO module will propagate the logins to your Drupal sites, if you are using Drupal as authentication provider/clients.

If you are using a cross-platform setup, you will have to create your own auto-login propagation in a custom module. Depending on your authentication provider, you may (or not) be able to define post-login actions to use. Or you may yourself utilize post-login hooks of your Drupal site to trigger logins on the remaining sites.

Unfortunately, the solution you are asking for not only depends heavily on your authentication provider, but also is far out of the scope of Drupal Answers.


How to modify the page at admin/structure/types? Using Drupal 8, I'm trying to modify the page at "/admin/structure/types" .This page is not a form (instead it is an entity list), so it cannot be modified with hook_form_alter.

_entity_list: The value is entity_type. Provides a list of entities using the EntityListController of the respective entity. E.g. _entity_list: view_mode returns the render array of a list of view modes.

Which hook can I use to modify an entity list ?

I have tried

mymodule_structure_types_prepare_form
mymodule_structure_prepare_form

and none of those is triggered.

see Can you change the list builder class used by an entity?

Using hook_entity_type_alter() you can override the list builder for nodes.

You can add a custom NodeListBuilder in your module that extends or replaces /core/modules/node/src/NodeListBuilder.php

This class is pretty simple, so it should be easy to add or remove rows to the table displayed.


Maintenance page being rendered as an entire page load after the main page load I've noticed that I've got a maintenance page being rendered in its entire HTML markup format after my pages. The site is not in maintenance mode, and this is not intentional behaviour. I'm trying to debug, but even as a reasonably experienced Drupal developer I still don't understand all the mechanisms at work here. Guidance on that would be welcomed.

I had been using the module CDN, to experiment with integrating a CDN. That was using that area at the bottom of the page, but when I disabled it, and uninstalled it, it has not stopped the problem.

I then enabled Theme developer 7.x-1.x-dev just to help me see what was going on, and the maintenance page render has stopped appearing. I then disabled Theme developer again and it has returned. Does this help anyone to suggest something?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

[...]

This also displays on my admin theme. Does this mean it is not something to do with my custom theme? Is there anything in particular that I could look or has anyone seen this behaviour before?

I'm still waiting to see an answer to the question of what causes maintenance mode to be displaying messages. So I don't know specifically whether the recoverable fatal error (this issue) being thrown by the buggy 7.x-2.4 version of XML Sitemap module was what caused the avoidance of a general WSOD/ crash and yet a display of an odd maintenance mode message.

I had not noticed they'd released 7.x-2.5 and so I've updated that which has stopped the behaviour altogether. Happy days :)


How to rearrange the sort buttons in a view There don't appear to be any Twig templates that allow you to move the exposed sort buttons to a different location in the view display. Does anybody know if these templates do actually exist?

Sure there is a twig for the exposed sort form. But normally you rearrange form elements inside of a form by adjusting the weight property. If you want to move the button outside of the form in another place of the view you need some tricks, look here https://stackoverflow.com/questions/7020659/submit-form-using-a-button-outside-the-form-tag/23456905

If you want to rearrange the view in general, like moving the complete exposed section to another place, you can do this in views-view.html.twig:

{{ title_prefix }}
  {{ title }}
  {{ title_suffix }}

  {% if header %}
    <header>
      {{ header }}
    </header>
  {% endif %}

  {{ exposed }}
  {{ attachment_before }}

  {{ rows }}
  {{ empty }}
  {{ pager }}

  {{ attachment_after }}
  {{ more }}

  {% if footer %}
    <footer>
      {{ footer }}
    </footer>
  {% endif %}

  {{ feed_icons }}


What is the D6 equivalent of D7's hook_filter_info? I am backporting a module from D7 to D6, and I am not familiar with Drupal 6.

The following three lines runs a chunk of text in the variable $input through the Markdown filter to produce $output.

$filters = module_invoke('markdown', 'filter_info');
$info = $filters['filter_markdown'];
$output = $info['process callback']($input, NULL);

Provided the Markdown filter module is enabled, it works fine on Drupal 7.  On D6, the call to module_invoke returns NULL (so the rest fails).

The cause is obvious, hook_filter_info did not exist for Drupal 6, so this is invoking a non-existing hook.

It looks like hook_filter is supposed to do the same thing in D6, so I try:

$filters = module_invoke('markdown', 'filter', 'list');

This results in the following array filters[0]['Markdown'].  I don't know how this helps, or - if it is the right start - where to proceed.

Can anyone tell me how to run a chunk of text through a text filter in Drupal 6?

In Drupal 6, filter modules just implement hook_filter(). In particular, to process text from a filter, you should use code similar to the following one.

$result = module_invoke('markdown', 'filter', 'prepare', 0, -1, $input);
$result = module_invoke('markdown', 'filter', 'process', 0, -1, $result);

I assume the delta for the input filter is 0, which means selecting the first input filter implemented by the module.
The first call to module_invoke() could be not necessary, but most input filter prepare the text that is going to be preprocessed, mostly to avoid conflicts with other filters, including the ones implemented by Drupal core. In fact, check_markup() uses the following code.

// Give filters the chance to escape HTML-like data such as code or formulas.
foreach ($filters as $filter) {
  $text = module_invoke($filter->module, 'filter', 'prepare', $filter->delta, $format, $text, $cache_id);
}

// Perform filtering.
foreach ($filters as $filter) {
  $text = module_invoke($filter->module, 'filter', 'process', $filter->delta, $format, $text, $cache_id);
}


How to get node id on hook_page_build(&$page) I wrote a hook like so:

function john_page_build(&$page)
{
  $akeys = array_keys($page['content']['system_main']['nodes']);
  print $akeys[0];
}

On pages with urls like http://mysite.com/page/43, it will print the node id for that page.  However, on a page with url like http://mysite.co/page/43/done?sid=2, drupal gives a warning saying that $page['content']['system_main']['nodes'] does not exist.

Is there a consistent way to get the node id WITHOUT parsing the url?

Still comes through the URL indirectly, but this is the easiest way to get it: menu_get_object.

<?
if ($node = menu_get_object()) {
 $nid = $node->nid;
}
?>

Note that if there is a node, it was already loaded by the menu system anyway and this is loaded from the static cache.

Refer this discussion for more detail.


Set global data like $user On my project, I have a custom table for some custom permissions for users. I want all permissions for a user loaded on each page like $user. I created a custom module and set the global variable $cperms in hook_init() which contains all custom permissions for current logged in user.

These values are available on site pages but I am not sure it is good to use hook_init() to set global data. Is there any proper method?

It sounds like you're reinventing the wheel here; as @burnsjeremy mentions, there's already an effective system built into Drupal for storing permissions.

hook_permission() allows any module to define its own custom permissions that can be set per-role. Once implemented, user_access() can be called to check a user for custom permissions.

If you need some data that is more granular (i.e. at the per-user level), the global $user object has an array property called data. $user->data is loaded/saved with the user object and should always be available to you.


Top Author of the week How to get the Top Author of the week based on user points? I have tried http://drupal.org/project/userpoints_ranking but it has no such options. I am using drupal 7I have vote up/down module and user-points module enabled and a Rules to add user points for every vote automatically, based on that vote i want to have Top Author of the week.

The Userpoints module has Views integration to make this happen:

Create a new view using Userpoints Transactions as the base table.
Add a Relationship, Userpoints Transactions: User.
Select your fields: User: uid & Userpoints Transactions: Points.
Filter on Userpoints Transactions: Timestamp with the Value Type set to An offset from the current time... so you can input your strtotime() offset (e.g. by rolling week, "-7 day").
Enable the Use aggregation option.
Lastly, for the Aggregation Settings on Userpoints Transactions: Points, set the Aggregation Type to Sum.


Programmatically create a user account I know that I can programmatically create a user using the following code, in Drupal 7.

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

What is the equivalent code in Drupal 8?

For Drupal 8, the code to create a user entity is the following one.

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = \Drupal\user\Entity\User::create();

// Mandatory.
$user->setPassword('password');
$user->enforceIsNew();
$user->setEmail('email');
$user->setUsername('user_name');

// Optional.
$user->set('init', 'email');
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->set('setting_name', 'setting_value');
$user->addRole('rid');
$user->activate();

// Save user account.
$result = $user->save();

The code can be found on Create a user account programmatically in Drupal 8.


Debugging custom database queries Is there a convenient way to ask a particular database object to print its query?

Every now and then, I write a DBTNG db_op() in a module, and far to often, I don't quite get the queries right.

I know that devel can output the query log, but that's all queries, which, in this type of situation, is a problem more often than not.

I want to do

$result = db_select('node', 'n')->fields('n')->execute();
dpm($result->queryWithParameters);
dpm($result->finalQuery);

There is a dpq() function in the devel module which seems to fulfill this need.

  Print a SQL string from a DBTNG Query object. Includes quoted arguments.


Get url of referenced entity in twig based on target_id I have a content type with a field « referenced entity » called field_suggestion_articles.

User can choose related content and a view displays this list of related content at the bottom of the content. The views uses "content" (display mode, a template like teaser) and not fields.

I use a loop to display this list in node--article--related-content.html.twig:

{% for key,value in node.field_suggestion_articles.value %}
    {# display the title #}
    {{ content.field_suggestion_articles[key] }}

    {# display a text field #}
    {{node.field_suggestion_articles[key].entity.field_resume_suggestion_article.value|raw}}

{% endfor %}

But I don’t know how to get the node urls of these related content.

When I dump node.field_suggestion_articles.value, I get the target_id of the node so I guess I should use it to retrieve the url. But I’ve tried a lot of solutions found on Drupal forums and here on stackExchange but without success.

Could you point me in the right direction ?

What they've done on this post should do the trick How do I get the node URL in a Twig template?

So in your case this should work:

{{ path('entity.node.canonical', {'node': node.field_suggestion_articles[key].entity.id}) }}


Upgrading from Pressflow The ultimate goal here is to take a somewhat large (about 15,000 nodes) and complex (many contrib and custom modules) site from Pressflow 6 to Drupal 7, so I am assuming I should make the shift to Drupal 6, then upgrade to Drupal 7. Is that the safest path? Is there a better way? And if this is the best way, I was curious about the strategy or things to think about when making the move from Pressflow 6 to Drupal 6.

I have seen a lot of things about going from Drupal to Pressflow but not so many going in the opposite direction. I did find this question: is there a safe way to convert a pressflow website to drupal 6?

But like everything I found about moving from Drupal to Pressflow, people just say it is a drop-in solution, but what does that actually mean? I have done a diff between base Drupal 6 and Pressflow 6 and I can see the differences. But if I do a diff on base Drupal 6 and our Pressflow 6 site there are a lot more differences and it doesn't appear that just dropping in the Drupal 6 core and overwriting what is there will turn out well (though I will have to try this as an experiment to confirm).

In short, I am looking for a more in-depth answer to how to migrate from Pressflow 6 to Drupal 6, other than just saying it is a drop-in replacement. For example, what files/dirs definitely have to be replaced, which files/dirs should you definitely not replace, what if any changes are required to the DB (my impression is that there are none), etc?

Thanks!

The only point is that you should disable and un-install the Pressflow modules, the rest is the same that drupal 6.

The big problem will be with the custom modules. The best always is try to make the migration.

If you don't want to migrate you can use feeds to move from drupal 6 to drupal 7. But in this way you must build the site in drupal 7.

Oskar


How to perform action from form opened in modal? I have a form where I have a link that opens a modal window with another form(something like adding a block to a region).

I would like to perform the action on the opened/second/modal form during submission as usual but I also want to tell the current window to close the modal and to hit a specific button(which is ajaxified and it will rebuild the form so the changes made via the second form would be visible in the main form - they are based on the same data source).

Is there a way to achieve this with ajax command from the second form?

A good example is View form. When a new window is opened(adding a field, or configuring some part of the View), actions in that window are reflected in the form itself after the window is closed.

I recently had to do something similar, and I took a good amount of time to understand how Drupal 8 ajax works.
Here are the steps:

Step 1: Ajaxify the link to open the modal, this is easy and you've probably done it already.

$form['ajaxed_link'] = [
  '#type' => 'link',
  '#title' => $this->t('Click to open the modal'),
  '#url' => Url::fromRoute('route_name', ['route_parameters']),
  '#attributes' => [
    'class' => ['use-ajax'],
    'data-dialog-type' => 'modal',
    'data-dialog-options' => Json::encode([
      'height' => 400,
      'width' => 700
    ]),
  ],

Step 2: Create the form that will open when the #url is called and create a route for it as well. Remember to make the submit button there ajax too, and specify an ajax submit handler using the callback key.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Ajaxed submit button'),
  '#ajax' => [
    'callback' => [$this, 'ajaxSubmit'],
  ]
);

Step 3: Define a function for the callback and make sure it returns an ajax response with the right commands. The first command closes the modal and the second command invokes the click on the desired button (use the correct jquery-selector).

public function ajaxSubmit(array &$form, FormStateInterface $form_state, Request $request) {
  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new InvokeCommand('#jquery-selector', 'click'));
  return $response;
}

Take note that it's a good idea to provide a non-ajax fallback return value from the ajaxSubmit callback for clients where JS is disabled. Do this by setting a form redirect in the regular form submit handler.

public function submitForm(array &$form, FormStateInterface $form_state) {
  ...
  $form_state->setRedirect('route_to_previous_form');
}


How can I add HTML tags into menu title? How can I add HTML tags into menu title?

I'm also tryed the following code.

function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    $vars['items']['standard.front_page']['title']='<i class="icon-home"></i>';
  }
}

It also converts tags into HTML entities.

You need to tell drupal that the string is safe. When you use t() this is done  automatically. But this would make no sense here, because there is nothing to translate.

In this case you can use an untranslatable markup:

use Drupal\Core\Render\Markup;

function adminimal_theme_preprocess_menu(&$vars) {
  if ($vars['menu_name'] === 'main') {
    if (isset($vars['items']['standard.front_page'])) {
      $vars['items']['standard.front_page']['title'] = Markup::create('<i class="icon-home"></i>');
    }
  }
}


Creating rule to update node title When a visitor registers on my site, I have a set of rules that create several nodes. One of those nodes is a photo gallery.

The rule for the creation of the gallery title, includes the following: [account:name]'s Photo Gallery and that works fine.

But if the user changes his name later on, the name on the photo gallery is not updated.

I have been struggling with the creation of a rule to do just that but I haven't found the option or configuration that allows me to update the node title.

Any help on this would be greatly appreciated.

Thanks. :)

You could do that with Rules.

Add a new Reaction Rule (e.g: Update user gallery title)
Event: "After updating an existing user account"
Action: "Fetch entity by property":

type = node
title = [account:name]'s Photo Gallery

Loop over 'list item' and add action
Action: "Set data value": Set list_item item title
Save list_item.

Update: rule export:

{ "rules_update_gallery_title" : {
    "LABEL" : "Update user gallery title",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "node",
            "property" : "title",
            "value" : "[account-unchanged:name]\u0027s gallery"
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "list-item:title" ],
                "value" : "[account:name]\u0027s gallery"
              }
            },
            { "entity_save" : { "data" : [ "list-item" ], "immediate" : 1 } }
          ]
        }
      }
    ]
  }
}


Custom layouts with the Display Suite module How can I make a custom layout with the Display Suite module in Drupal 8?

I checked the example for Drupal 8, but that didn't work for me.

Could anyone help me?

In your theme folder, create a THEMENAME.layouts.yml file:

clean_empty:
  label: Clean empty page layout
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: templates/nodes/clean-empty
  regions:
    title:
          label: Title
    ds_content:
      label: Content

Then just create your twig file. In this example, create a clean-empty.html.twig file inside THEME/templates/nodes:

{#
/**
 * @file
 * Custom display suite layout
 *
 * Available variables:
 * - title
 * - ds_content: content region
 */
#}
{{ title_suffix.contextual_links }}
<h1>{{ title }}</h1>
{{ ds_content }}


Update the settings of a View Display programmatically I can load a ViewExecutable and create a new Display programmatically:

$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

But how can I update the settings for the new display programmatically?

The display is an instance of \Drupal\views\Plugin\views\display\Page but I can't see any way of saving options to it.

The setOption method exists, but how can persist the options to storage?

Answering my own question:
The settings are not made on the display, but on the handler.

$view = Views::getView('existing_view');
$display = $view->newDisplay('page', 'New page', 'page_2');

// ViewExecutable::setHandlerOption($display_id, $type, $id, $option, $value)
$view->setHandlerOption('page_2', 'argument', 'nid', 'admin_label', 'Foo');
$view->save();

Options and values correspond to the values in a View YAML config file, under display_options.

Important is that you find out the correct $type argument.

I had a look at the array keys returned from ViewExecutable::getHandlers.

"field"
"argument"
"sort"
"filter"
"relationship"
"header"
"footer"
"empty"


Having username as a path - Profiles 2 and Pathauto I have a problem with integrating the Pathauto and Profiles modules. Basically, I would like to have the username as URL, e.g. example.com/username. This should link to the profile page (not the account page). I know how to do it for account ([user:name]) however this method does not work for the profile patterns. There is only certain number of patterns available for profile paths and no username I am afraid. I tried node:author:name, but this doesnt work as well?

Can anyone help with this, or suggest any other solution?

you can automatically path save the user name when user access the user/uid page
add a submit handler in form alter and

$form['#submit'][1] = 'redirect_to_profile_username_page';

// here get the user name field

function redirect_to_profile_detail(&$form, &$form_state){
$uid = $form_state['build_info']['args'][0]->uid;
$user = user_load($uid);
$clean = $user->name;
      $Alias_1 = get_alias('source','user/'.$uid,1);
        $pathAlias = !empty($Alias_1) ? $Alias_1['alias'] : FALSE;
        if($pathAlias === FALSE){
                path_save($args = array("source" => 'user'.'/'.$uid,"alias" => $clean));
                $pathAlias = drupal_lookup_path('alias',$clean);
        }
       $form_state['redirect'] = $clean;
     }

this will redirect the user/uid page to that particular username as url page

here we are creating a aliase for user/uid so when you access sitename/username that user profile page will be loaded.


dsm vs drupal_set_message vs debug vs dpm vs watchdog for developing dsm requires the devel module but I guess you have that installed anyway if your developing modules.
debug and watchdog having the advantage that is writes to the log file.

I can see the advantage of watchdog on a live site so users don't get bugged by messages while debugging the site. but is harder to use ( you have to write more code )

dsm and dpm are short and simple to use but don't always show output.

So are I think debug is the best way to go while developing modules (on your test server). But apparently it doesn't handle array's that well.

Which one do you use and why do you think that is the best / better or should I use the different functions for different purposes?

If devel is available, i use mostly dpm. If not, I use drupal_set_message(print_r($array, true)). This helps me in the most cases. If both are not available or visible, I use the Watchdog.


Drupal6 reference URL date in views filter? I apologize if this is already explained somewhere, I haven't found it.

I have a view in drupal6 based on the date browser example.  I want to show all items having a date greater or equal than the date from the path:

for example, #somesite#.com/events/2012-08-01

with arguments it shows events that are equal to the date in the
path; can it show greater or equal?
with filters it can show greater or equal to a hard-coded date,
but can it reference the date from the path somehow?

Is there some other module or best way to do this?

Update: perhaps this is the answer Date argument as view filter

UPDATE: I solved this by using the "Views PHP Filter" http://drupal.org/project/viewsphpfilter
after that i was able to choose Node PHP filter and added code to select the nodes based on the passed date like this:

$my_req = $_SERVER["REQUEST_URI"];

preg_match('/my_page\/(.*)-(.*)-(.*)/', $my_req, $matches);

# Get the month from the URL or use the current month:
if(isset($matches[1])){
  $my_Y = $matches[1];
  $my_m = $matches[2];
  $my_date = $matches[3]+1;
} else {
  $my_Y = date("Y");
  $my_m = date("m");
  $my_date = date("d")+1;
}
$the_date = $my_Y . "-" . $my_m ."-". $my_date;
$nodeids = array();
$query = "SELECT nid FROM content_type_event WHERE field_start_value > \"$the_date\" AND field_start_value < DATE_ADD(\"$the_date\", INTERVAL + 16 DAY) ";

$my_result = db_query($query);
while ($my_row = db_fetch_array($my_result)) {
  $nodeids[] = $my_row['nid'];
}
return $nodeids;


Integrating file management with Organic Groups Using Drupal 7 and OG 2.x. I'm looking for a file manager to use so that each group has a files tab with the ability to create, move, delete files/folders for their group and read/write permission is only for the members of the specific group.

Is filedepot the only module for this? I have found elfinder, CKFinder, and IMCE, but it's unclear whether these are reasonably simply to integrate with OG.

Has anyone integrated a specific file manager with OG and is happy with how it's working?

Partial answer is that CKFinder doesn't integrate with OG out of the box, or easily at all. They do offer an access control list, but you would need to know the specific directories and specific people who need access. It won't work to create folders/permissions on the fly when creating groups or add/remove permissions as members are added/removed to the group. They mentioned that a custom plugin may be possible to do to modify the access control list but that it would be quite a bit of work. Java was recommended for the custom plugin.


Drupal commons running very slow, what are the key modules to disable? I'm running Drupal commons latest version 6.x-2.9 on MAMP 2.1.1 (clean install).

Drupal commons running very slow when I'm in the administer section. There's tons of modules and I'm not sure which are the key ones causing the slowness.

Need advice on that.

This is normal for a Drupal site with a lot of modules. There are many SQL queries and huge use of memory to provide these admin pages, but if you look the site as a normal visitor, will see that this isn`t the same.

Commons, specifically, i had many issues related to very slow admin pages, when developing a large social network, with the many modules from Commons itself and many others specific from the project.

To improve this, you can:
 * tune your MySQL (the first thing to do is set your tables as INNODB, that you help a lot)
 * use memcached
 * use PHP APC
 * Look around http://web.archive.org/web/20110516021804/http://www.morningtime.com/Drupal-6x-Performance-Guide/513 (the MorningTime site removed the link, so you`ll only be able to see in the webarchive)


Verifying that Webforms Hooks are firing I'm new to Drupal but relatively proficient in PHP.  I'm attempting to use the Webform module as a ticketing system.  What I'd like to do is hook into the webform submission insert (hook_webform_submission_insert) and create an object of type 'support_ticket' each time a webform is saved.  For now, I'm just trying to make sure that I'm hooking in properly, and it looks like I'm not.  I'm using the code below in a template.php file of a custom module:

function pvfk_webform_submission_insert($node, $submission){
   drupal_set_message("IN Insert");

   //Declare a new StdObj

   $new_node = new StdObj();
   //Set the type
   $new_node->type='support_ticket';

   //Set the Title
   $new_node->title='NEW TICKET';

   //Set the body
   $new_node->body = 'TICKET BODY';

   //Set other content fields
   // $new_node->field_name[0]['value'];

   //Finally use functions to save, submit, and insert the new_node
   $new_node = node_save($new_node);
   node_submit($new_node);
   content_insert($new_node);

I've cleared my cache and created new webforms - but neither a new piece of content is created nor do I see the message.  Am I missing something here?

Hook functions are run only when they are put inside a .module file.

So you should move your function into your pvfk.module file. Then visit your /admin/build/modules list so Drupal will refresh hooks list.


How to link to last comment on a node page? I have some nodes with lots of comments that use a pager. I want to link from the top of the node page to the last comment.

Is there a simpler way than building the link like this (source):

Get number of (published) comments for a certain node;
Get number of comments per page (it can differ from on content type to another);
1+2 = number of pages;
Get cid of the last comment;
Create a link like /node/[nid]?page=[page]#comment-[cid]

I don't think there's a simpler way than that, but you can combine two of those steps into one so you at least only need to make a single database call:

function node_last_comment_link($node, $link_text) {
  // Get the num active comments and most recent comment id
  $data = db_query('SELECT MAX(cid) AS cid, COUNT(cid) AS cnt FROM {comment} WHERE nid = :nid AND status = 1', array(':nid' => $node->nid))->fetchObject();

  // No comments, no link
  if ($data->cnt == 0) {
    return FALSE;
  }

  // Get the num comments per page
  $var_name = 'comment_default_per_page_' . $node->type;
  $sensible_default = 50;
  $num_per_page = variable_get($var_name, $sensible_default);
  $page_num = floor($data->cnt / $num_per_page);

  //Build and return a URL
  $query = array();

  // No point adding ?page=0
  if ($page_num > 0) {
    $query['page'] = $page_num;
  }

  $fragment = 'comment-' . $data->cid;
  return l($link_text, 'node/' . $node->nid, array('query' => $query, 'fragment' => $fragment));
}

I've given that a quick test and it seems to work but it might need a bit of massaging, especially if you have threading turned on :)


Blocking node creation after validation We have a lot of spammers (which are logged in users) creating content on our site. They are creating photo nodes without photos (which I have recently allowed as a way to catch them and ignore them, sort of a honeypot). I have also added the honeypot module but the 10 second delay doesn't seem to be working too well...

Is there a way to catch these nodes that don't have photos and block them from ever actually being created? I was thinking that it could be done in the presave hook, but unsetting the node didn't seem to work.

Edit

I could make the image required, but the bot is filling out all of the required fields so far, and it isn't hard to upload an image using a script.

I have implemented what I put in my answer and it seems to work, and I am giving the spammers 10 tries/day before they get banned. This may or may not be too lenient.

So far I have caught and banned 14 spam accounts (~1 hour of it being live).

Maybe this is the solution... doesn't create the node, sends them to a blank 403 page.

function _utils_photo_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch($op){
    case 'presave':
      if(empty($node->field_image[0]['fid'])){
        _utils_check_spammer($node->uid);
        //try again?
        die(header('Location: /node/add/photo', TRUE));
      }
      break;
  }
}
//meta code
function _utils_check_spammer($uid){
    if (in_spam_table && spam_count > spam_limit_for_today)
        //nice knowing you...
        ban_user($uid);
    else
        //you get some more chances
        increment_spam_count($uid)
    endif;
}


Fatal Error Running Drush 4.4 with Drupal 7.2 Do you have any idea on what might be causing this error in Drush w/ Drupal 7.2 (worked fine in Drupal 7.0)?

  Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /path/to/includes/database/mysql/database.inc on line 42
  Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
      Error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /path/to/includes/database/mysql/database.inc, line 42

Line 42 of database.inc contains the following line:

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,

I thought this was related to PDO extension missing, but it is indeed installed.

Here is the output of drush -v -d status:

  drush -d -v status
      Bootstrap to phase 0. [0.03 sec, 1.28 MB]                            [bootstrap]
      Drush bootstrap phase : _drush_bootstrap_drush() [0.03 sec, 1.41 MB] [bootstrap]
      Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.07 sec, 3.18 MB] [bootstrap]
      Initialized Drupal 7.2 root directory at /path/to [0.09 sec, 4.06 MB] [notice]
      Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.09 sec, 4.06 MB] [bootstrap]
      Initialized Drupal site default at sites/default [0.09 sec, 4.06 MB] [notice]
      Drush bootstrap phase : _drush_bootstrap_drupal_configuration() [0.09 sec, 4.06 MB] [bootstrap]

Fatal error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /path/to/includes/database/mysql/database.inc on line 42
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Undefined class constant 'MYSQL_ATTR_USE_BUFFERED_QUERY' in /path/to/includes/database/mysql/database.inc, line 42 [0.1 sec, 4.56 MB]

EDIT:

phpinfo indicates that pdo, pdo_mysql are all installed. However, when I run

pecl remote-info pdo (and pdo-mysql), I get a (among others):

  Installed   - no -

So it appears that via the web requests, the extensions appear as installed, but not from the command line (same instance of php, v5.3). Is there a way to tell pecl what phpinfo already knows ... ?

Ok, another one for the "learning experience" column:

I specified

DRUSH_PHP=/path/to/php

right before this line in drush wrapper script:

if [ ! -z "$DRUSH_PHP" ] ; then

Works now.

Thanks @kiamlaluno & @Berdir for your time and input. Hopefully this helps others.

KM


Drupal 7 multilanguage front page using templates I need to have 2 separate front page tpl pages for a multilanguage site I'm building, one for the english layout and one for the chinese layout. If the default language is zh-hans, I would like it to serve the custom tpl page-cnfront.tpl.php.

I managed to find an answer to my question for Drupal 6, which provided the following code:

function mytheme_preprocess_page(&$variables) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'en') {
    $variables['template_file'] = 'page-customfront';
  }
}

I tried to modify it for my site in Drupal 7 like so:

function mytheme_preprocess_page(&$vars) {
  global $language;
  if (drupal_is_front_page() && $language->language == 'zh-hans') {
    $vars['theme_hook_suggestions'] = 'page__cnfront';
  }
}

but I think something is wrong, because I get a WSOD when I add this to my template.php.
What is the correct way to do this?

theme_hook_suggestions is array

$vars['theme_hook_suggestions'] = array('page__cnfront');


Conditional fields not working with hierarchical select module Case: I am using the Hierarchical Select module for allowing users to choose taxonomy terms from a particular vocabulary. Based on the chosen terms (deepest level), I want to display a field using the Conditional Fields module.

Currently, the Conditional Fields module is working for simple select widget. But not for Hierarchical Select. Is there any hook or patch available?

Actually I found Conditional field to work with HS but you must enter numeric value of the dependee. For Example if you want to display the field only when term "abc 1" is selected then you check what is the numeric value of that field in the database .lets say the value is 12. That's all you need to enter an its working


How to enable inline editing on Views in Drupal 8? It is said to enable the core module "Quick Edit" to be able to easily edit nodes, but there still isn't an easy way to add inline editing in Views. All I want is for text fields to show as inputs which I can change, and then press edit at the bottom. Exactly what is currently achieved with "editablefields" for Drupal 7.

Is there a way to do this in Drupal 8?

Note: Basically my question is the same as this, but for Drupal 8.

Quick Edit of nodes in Views works. You can see this on the frontpage, which is a View.

However this works only for Views which show content.

If you have a View which shows content and want to choose the fields and customize the layout, you can create a custom viewmode, configure the fields there and put the layout in the twig files of the view mode.

Of course this does not provide all features of a View which shows fields and the module Editablefields. For this you would have to wait until this module is ported to D8.


On content, choose the taxonomy parent and display all the children I have a content type with a taxonomy field based on a hierarchical taxonomy with 3 levels. I use Simple Hierarchical Select (SHS) to select and display the terms.

I want to have a view that displays the chosen terms on each content page, but I also want when I choose the parent term to show all its children without selecting every one of them.

I made a content view with a Content:ID contextual filter. As a formatter I use SHS but it displays only the selected term at the selected depth, no other options. I tried with another contextual filter on the taxonomy depth, also with another taxonomy view to take the children of a term and then use views field view to embed it on the primary view, no success at all.

Any ideas?

For anyone interested in the future, I managed to solve this using the Entity Reference Tree Widget module, which provides the exact functionality as described on question.


Rules - New events inside code not shown in interface I am trying to insert a new event inside an already existing module. The module is Nodeaccess https://www.drupal.org/project/nodeaccess it's used to grant users edit/delete permissions to single nodes.

inside sites/all/modules/nodeaccess i have made the file nodeaccess.rules.inc which contains this code:

/**
 * @file
 * Rules integration.
 */

/**
 * Implementation of hook_rules_event_info().
 */
function nodeaccess_rules_event_info() {
    return array(
        'nodeaccess_grant_permissions' => array(
            'label' => t('Permissions are granted to a user'),
            'group'=>t("NodeAccess"),
            'variables' => array(
                'granter' => array('type' => 'user', 'label' => t('The user who granted the permissions.')),
                'granted' => array('type' => 'user', 'label' => t('The user who got the new permissions.')),
                'node' => array('type' => 'node', 'label' => t('The node on which the permission has been granted.')),
            ),
        ),
    );
}

Looking at different guides on the web it looks like this is all you have to do to get a new event but in the events list i can't find it.
I have tried:

refreshing the cache
disabling/enabling nodeaccess module then refreshing the cache (and rebuilding permissions as it was requested)
disabling/enabling rules module then refreshing the cache
adding the rule entry in a *.rules.inc file i've seen it's being imported (namely the feeds.rules.inc file from the feeds module which already existed when i installed the rules module)

Nothing worked so far

EDIT: i have changed the function name and the entry name (both from "node_access" to "nodeaccess" ) but it's still not showing. I have discovered that if i add an entry on a file i know it's being imported and keep the prefix of the entry, then it shows up

The problem is the function name. Since the module name is nodeaccess (and not node_access), function name should be nodeaccess_rules_event_info

However, it is not recommended to add anything to a contributed module (unless you are going to contribute back to the module's issue queue).

If this rule is specific your project, you can add it in your own custom module.


Bartik's code - manage logo and favicon I want upload an image for my theme, like the logo or favicon with bartik (or other theme).
Where's the code for doing that with bartik ? (it's not in bartik/theme-settings)

In fact, i want this features : The user choose his background like the logo

Thanks.

If you just want to show the logo or the screenshot of the theme in your drupal site, just replace your own images with the logo.png or screenshot.png in yoursite/themes/bartik/, remember you have to name them 'logo.png' or 'screenshot.png' exactly.

Not sure if this is what you want. Good luck.


use conditional fields to change a label on a field Is it possible to change the label on a field using the conditional fields module.  What I want is to call a field "Effective Date" in one case and "Published Date" in another but have it be the same field.

is that possible with the conditional fields module or any other module?

I answered this similar D7 question How to change a fields label name based on another fields value?

(function ($) {

   (function Forever(){ // we create a function called Forever

   var grabselectedtext = $('#edit-field-test-und option:checked').text();
   // this grabs the text of the field you want to depend on.

     $('label').each(function(){
      if ($(this).attr('for') == 'edit-body-und-0-value') {

         if (grabselectedtext != '- None -') {
           $(this).text(grabselectedtext);
         } else {
             $(this).text('Field Two');
           }
         }

     });

   setTimeout(Forever, 1);

   })();

})(jQuery);

You want to attach this JS code to a library. Then attach the library via a hook_form_alter and check for form ID and content type.


Possible reasons why status report page is blank I'm using Drupal 7.23 on my test site and since a couple of days the status report page is completely blank (no theme, no menu, nothing). No info shown at all. Other (report) pages are shown without noticeable issues.

Does anybody have an idea what could cause this?
I have a almost similar 7.23 life site that shows this /admin/reports/status report perfectly.

Any log-file to check?

I didn't manage to get the php logging, but I do know now why this report page was blank. I had installed a not complete functioning module named Backup and Migrate Opencloud that needed Libraries 7.x-2.0 or higher. I was still on 7.x-1.0. After I updated to the latest libraries version the status report page showed up again.


Difference between hook_node_view() and template_preprocess_node() with seeing messages When I add a form to a node's render tree using hook_node_view(), eg

<?php

/**
* Implements hook_node_view().
*/
function MODULE_node_view($node, $view_mode, $langcode){
  if ($node->nid == 9 && module_exists('contact')) {
    module_load_include('inc', 'contact', 'contact.pages');
    $cForm = drupal_get_form('contact_site_form');
    //$cForm['#action'] .= '?destination=' .    request_path();
    $node->content['contact_form'] = array(
    '#markup' => drupal_render($cForm),
    '#weight' => 20,
    );
  }
}

then I get my messages displayed right after the submission.

I do the same thing with template_preprocess_node(), the messages are displayed one request after the submission.

I suspect this is related to the execution order.  Can someone shed some light on the difference here?

It is the execution order. hook_node_view() acts on the node object as it is being assembled. When template_preprocess_node() is called, the node is ready to be rendered. For instance you may use template_preprocess_node() to change the date format.


Update hooks not being run when module enabled - chicken and egg problem I've created a custom module to be used for deploying configuration updates like enabaling modules, reverting features, executing db queries, etc...

The module initially has an empty .module file, a .info file and a .install file with three hook_update_n functions.

When I enable the module, the schema version is set to the last "n" value of the update hooks, but the functions inside those hooks aren't executed.

What's the proper way to enable a "utility" module like this during deployment, and still run the update hooks via update.php?

Should the functions go in a hook_install instead?

Seems like a "who's on first" type problem.

Thank you.

A module with an install file gets run at install, for an example if you install/enable a module with one hook_install and three hook_update_ only the hook_install will be ran.

The best way to do what you want to do is create a module like you want, with a empty hook_install then just keep adding hook_update_ functions as you need to do more stuff, then when you are done run update.php to run all the hooks.

It may also be a good idea to separate the types of stuff you want to do into groups (like create new items, and add them to the database, then another hook could be delete x and y, and another could be rename a and b) and add them as hook_update_ so for example if you need to run something more then once for an example or maybe down the road, you could just call update.php and run that specific hook_update_ function (if you for example wanted to run delete x and y more then once, you can).


show image field twice with different image style In my content type, I am using an image field.

But in display, I want to show this image twice. Once with large style, and another with medium.

How can I do this?

If you're displaying your field programmatically you've to use:
For Large :

<?php echo theme('image_style', array(
    'style_name' => 'large',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

For Medium :

<?php echo theme('image_style', array(
    'style_name' => 'medium',
    'path' => $node->field_image['und'][0]['uri'],
    'alt' => t('Image'),
    'title' => t('Title'))); ?>

Your can also call any format you added on back office his name


How to set up a text format that replaces the tokens? In the custom Drupal 8 block, there are no tokens.

/admin/structure/block/block-content

How to set up a text format that replaces the tokens ?

I need to use in a custom block, the title of the current page, the creation date of the current page, ...

Token Filter is a very simple module to make token values available as an input filter.

This doesn't mean that all tokens will work in every location. For example, if you use a [node:field_foo] token in the text of a block, the token system will not know which node you are referring to and will not replace the token.
It is up to you when you are implementing this module to be aware of the context for token usage and use them appropriately

https://www.drupal.org/project/token_filter


How can I make db_select recognize an empty field? I am writing a db_select in D7 to get various user fields, including the URI's of user's avatars (if it exists).

My initial attempt looked this:

$query = db_select('node', 'n');
$query->join('users', 'u', 'n.uid = u.uid');
$query->join('file_managed', 'f',
  'f.fid = u.picture OR u.picture = :null', array(':null' => 0));
$query->fields('f',array('uri'));

This almost do the job.  The only glitch is that if the user has no avatar, the field uri always contains the uri pointing to f.fid #1.  In that case, I want it be missing or empty.

As a workaround, I now execute two db_selects: First one for all users that have an avatar:

$query->join('file_managed', 'f', f.fid = u.picture);

Then one for all users without:

$query->join('file_managed', 'f', u.picture = :null', array(':null' => 0));

I then just concatenate the results. This produces the desired result, but is a bit clumsy.

I would like to do it with one db_select if that is possible.

Just do a left join on 'files_managed' table

$query = db_select('node', 'n');
$query->join('users', 'u', 'n.uid = u.uid');
$query->leftjoin('file_managed', 'f', 'f.fid = u.picture');
$query->fields('f',array('uri'));
$query->fields('n',array('nid'));
$query = $query->execute();
dpm($query->fetchAll());


Getting VERY strange AJAX/JS 404 errors I'm at a loss as to what could possibly be wrong, but I'm definitely seeing some crazy 404 errors, all of which seem to stem from /user/0/orders

For example, if I add a page using the CKeditor for the body, then edit it, the console error will be POST http://www.mysite.com/user/0/orders 404 (Not Found) and the CKeditor will not be displayed.

I'm also receiving an error on some autocomplete fields as follows:

An AJAX HTTP error occurred.
HTTP Result Code: 404.
Debugg information follows.
Path: http://www.mysite.com/user/autocomplete
StatusText: Not Found
...
Page not found
The requested page "/user/0/orders" could not be found.
...

Anyone have a suggestion I might try?

Thanks.

Ok well I seem to have "solved" the issue.

I had a node with the following PHP code to take the user to their order page when accessing user/me/orders:

<?php
  global $user;
  $orderpath = 'user/'.$user->uid.'/orders';
  drupal_goto($orderpath);
?>

When I deleted that PHP code, everything started working again.

Anyone know why the above code could cause the problems indicated in my question?


Complex Drupal setup using Views, Entity/Node Reference and custom content type OK, here is my setup, i will then explain what im trying to achieve:

I have a content type of DELIVERY another content type of BOOK and another content type of FEEDBACK

Now, any given user can have anywhere from 1 to 12 DELIVERY content types created (these are created using Rules automatically when they sign up). I use the Node Reference field to attach a BOOK to the DELIVERY content type, if the user has more than 1 delivery content, i will be attaching different books to each delivery content each month. When i attach a book to the users delivery, they can then create a FEEDBACK content to leave feedback under that particular DELIVERY.

So for example,

User 1
  - Delivery 1
       - Book 1
       - Book 2
  - Deliver 2
       - Book 3

I want the user to be able to create a Feedback content and select the relevant book that the feedback belongs to and once saved it should appear under the particular delivery content.

How can I achieve this?

You should be able to add a node reference field on the Feedback content type. When your user creates a new Feedback node, they should be able to select the correct Delivery node to associate it with.

You will most likely want to constrain the user's selection options to Delivery nodes associated with that particular user so that User 1 doesn't leave feedback about User 2's delivery. One way to do this is to create a custom autocomplete function and use hook_form_alter() to edit the Delivery node reference field on the Feedback node create/edit form.

On a Delivery node, to display Feedback nodes that are associated with that Delivery node, you can create a View that has shows Feedback nodes that are associated with the currently logged in user and references the current node nid (use contextual filters for both).


How do I alter prices? This is a follow up to Ubercart alter product price when product added to cart.

I have an attribute called "Billing Term". It has options: 6 months, 12 months and 24 months. If 6 months is selected, 0% discount must be applied. 6 months, 5% discount must be applied. and 24 months, 10% discount must be applied.

I set up the attributes to make no change to the price, because I can't find a way to make attributes adjust a price by percentage.

The best solution to my problem would be to find a way to specify attribute discounts in %. But I couldn't find a way to do that. If you know of a way, please do tell, as that is for sure better than my other options below.

So, with all attribute adjustments to be 0, I figured I could something similar to what was done here (but this post is for Drupal 7). So I tried this:

function comply_advantage_uc_cart_alter(&$items)
{
  print '<pre>'; print_r($items); die(); <--- this makes apache run out of memory
  print '<pre>'; print_r(arrray_key($items)); die(); <--- this prints out "2", and then "3" and then "5" etc.
  $items[45]->price = 29393; <--- this doesnt adjust the price

}

I was hoping to do something like this:

$items[5]->price = $items[5]->price * 0.95; // to apply 5% discount

How can I accomplish this?

I found out that $items[5] type is CartItem.

Figured it out:

function comply_advantage_uc_cart_alter(&$items)
{
    $item->price->setValue($item->price->value * 0.95);
}

Hope it helps someone!

** IMPORTANT **

It looks like if you use

$item->price->setValue($item->price->value * 0.95);

Yo might end up altering the price several times. So I had to actual recalculate the price completely, without using $item->price->value, or it would deduct 5% multiple times.


Creating a module arguments page with a shorter URL I'm creating two pages with a custom the module. The first page makes an API call to create an XML object and then lists all objects. Each object contains 10 entries but i only display 3 of them. From here clicking on an object directs users to a module argument page.

Is there anyway for me to create an argument page that doesn't have 10 different entries in the URL?

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  //general page
  $items['my_module'] = array(
    'title' => 'My Module List',
    'description' => 'My module list Page',
    'page callback' => '_my_module_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
      );
  //single event page
  $items['my_module/event/%/%/%/%/%/%/%/%/%/%'] = array(
    'page callback' => '_my_module_arguments',
    'page arguments' => array(2, 3, 4, 5, 6, 7, 8,9,10,11),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

My suggestion is concatenating arguments by a dilemma (something like -) and in callback function explode them simply by Php Explode function.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  //general page
  $items['my_module'] = array(
    'title' => 'My Module List',
    'description' => 'My module list Page',
    'page callback' => '_my_module_page',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
      );
  //single event page
  $items['my_module/event/%'] = array(
    'page callback' => '_my_module_arguments',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function _my_module_arguments($args){
 $items = explode("-",$args); // you can use another dilemma instead -
  //$items[0] first arg
  //$items[1] second arg
}


Using one exposed filter on different date fields So been looking at this for a bit now and nothing springing to mind so question and advice needed. On Drupal 8.

What I want:
I have a content type with three date fields (Date A, Date B and Date C). Using a view I can create an exposed filter to filter dates between ranges, before, after, etc on say Date A. I can do the same for the other date fields.

I would like to restrict it to one date field at a time. So select the dates for Date A OR Date B OR Date C but never more than one date field.

Question
Sounds simple. I cannot find a simple way to do this so unless I have missed the obvious am going to have to create a module. Before I look into that and start the ball rolling are there any existing solutions I have missed?

Assuming there is no easy way my thought was to create a new module.This would allow one date input and then a select box to choose which field to perform the operation on.

I have not yet looked at this in depth so as to using JS/AJAX to achieve this or a PHP solution (Class or hook), I am open to suggestions.

Thanks

Create three different views, each with one exposed filter. Use css class to control visibility, use a bit of javascript to move around.

Refer How to create views tabs in D8?