Injecting additional content from multiple sources into a block using twig I have a module which presents a table of contents from a twig template of examples on to how to use the module. This listing is located at /flot-examples. I would like additional modules to be able to add links to this list. The main module, flot_examples has a block, plugins defined like this:

{% block plugins %}
{% endblock %}

This way, any plugin modules can add
plugin example to the list

If I have only one plugin, I think I could override the route to /flot-examples by the plugin, call {{ parent() }} and inject content into {% block plugins %} However, if I have multiple plugins, they all can't do that.

I also see that there is a way for the parent to identify child scripts as 'appendable':

{% use [child_module].html.twig with appendable as appendableContent %}

This would work, but the parent module would have to be given a list of the child modules. If this is the best way to accomplish this, I imagine I would have to:

1)add an array to the parent module, flot_examples, (where?) so that...

2)the child modules would append their names to (where?) so that ...

3)when this array is passed to the twig template (flot_examples.module and somewhere else?), it can loop over the array (in the twig temple) to generate the {% use .... %} statement.

I guess I can see another strategy would be to move this directory listing out of a twig template, and just use render arrays. Then would the child module use preRender functions to append additional list items to the render array, somehow?

Are any of these on the right track? Which would be "the best" or "the easiest" way?

I went with a hook instead. There must not be a way to do this in twig.

This section resides in a controller in the parent module:

$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

And this resides in the child [module].module file.

<?php
use Drupal\Core\Url;
function flot_spider_examples_flot_examples_toc_alter(&$item_list) {
 $options = [
      ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
    ];
 $item_list[] = t('Spider Chart (with spider plugin)', $options);

}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.


Nest one content type in another to be able to add single fields I would like to have one content type "Basic" and then another content type "Premium" that has a few extra fields than the basic one. The idea is that I want my users to pay for premium publications (using Commerce Node Checkout Module) if they want to use those extra fields. Basic content will always be free.

It is very likely that I will need to make changes to the basic content type fields that I want to also be reflected in the permium content type. Is there a way to kind of "subtheme" the content type so that it reflects the basic one whenever changes are made but still carries a few extra fields that are independend of these changes?

That's quite a cool question...

I think If I were doing it, I would have the basic form available to all standard users of a standard permissions role...

Then when a customer has paid for the privilege to use more advanced fields, I set up a rule to promote their role to an advanced user role after checkout.

You can then use a module like Field Permissions to determine which fields your basic users can edit, and which fields your advanced users can edit.

And, you only need one content type.


Add custom text field to field settings form In the admin when click edit on Manage Fields page it shows settings for that field. Can we add a custom property (checkbox) here like the required checkbox?

For example, for a decimal field it show 'Label' textbox, 'Required field' check box, 'Help text' textarea and so on. Can I add my own checkbox or textfield to this form?

What you'd have to do is define your own field type in a module, then use hook_field_settings_form to set the global options for that field (or hook_instance_settings_form for a specific content type's implementation).

Here's a general guide to creating your own field in Drupal 7, but to get a handle specifics of creating a custom settings option take a look at other modules' implementations of it.

For example, Drupal Commerce makes a set of options from existing customer profiles:

function commerce_customer_field_settings_form($field, $instance, $has_data) {
$settings = $field['settings'];
$form = array();

if ($field['type'] == 'commerce_customer_profile_reference') {
  $options = array();

// Build an options array of the customer profile types.
foreach (commerce_customer_profile_type_get_name() as $type => $name) {
  $options[$type] = check_plain($name);
}

$form['profile_type'] = array(
  '#type' => 'radios',
  '#title' => t('Customer profile type that can be referenced'),
  '#options' => $options,
  '#default_value' => !empty($settings['profile_type']) ? $settings['profile_type'] : 'billing',
  '#disabled' => $has_data,
 );
}

return $form;
}

Yours sounds more simple - but the same general idea. Get the field and instance data, do something with it, make another mini form and return it so it gets rendered.


How do I change/modify an update content message When someone edits a node, or a profile content type there is a message set with drupal_set_message() that appears at the top of the page. It can look something like this:

  Education 45971 has been updated.

How do I change/modify this message before it is displayed to the user? Is there any hook I can use?

On Drupal 6 you have Status Messages Alter, a port for D7 sits in the issue queue.

  Status Messages Alter provides developers with a new hook called
  "hook_message_alter." This hook enables developers to alter the text
  that is displayed in status messages before the messages are themed.


Drupal 8, clear specific cache In Drupal 8 we have the command drush cr which is the new version of the deprecated drush cc all.
However we had drush cc menu and some more specific cache clear commands.
If I try to execute them, I get weird symfony error.

What I want to achieve:
Find the replacement commands for drush cc (specific cache) in Drupal 8.

What I have checked/tried already:
The documentation is a bit scarce:
https://drushcommands.com/drush-8x/cache/cache-clear/

Manually typing all types of commands like drush cr menu, etc. They don't seem to work.

Regards,
Oleg

drush is not ready for that right now (as far as I know), so you'll need to write custom drush-scripts or do some other execution. drush cr rebuilds the whole cache, drush cc is not working with drupal8.
the method drupal_flush_all_caches shows how to flush all core caches.
$module_handler = \Drupal::moduleHandler();
  // Flush all persistent caches.
  // This is executed based on old/previously known information, which is
  // sufficient, since new extensions cannot have any primed caches yet.
  $module_handler->invokeAll('cache_flush');
  foreach (Cache::getBins() as $service_id => $cache_backend) {
    $cache_backend->deleteAll();
  }

  // Flush asset file caches.
  \Drupal::service('asset.css.collection_optimizer')->deleteAll();
  \Drupal::service('asset.js.collection_optimizer')->deleteAll();
  _drupal_flush_css_js();

  // Reset all static caches.
  drupal_static_reset();

  // Invalidate the container.
  \Drupal::service('kernel')->invalidateContainer();

  // Wipe the Twig PHP Storage cache.
  PhpStorageFactory::get('twig')->deleteAll();

  // Rebuild module and theme data.
  $module_data = system_rebuild_module_data();
  /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  $theme_handler = \Drupal::service('theme_handler');
  $theme_handler->refreshInfo();
  // In case the active theme gets requested later in the same request we need
  // to reset the theme manager.
  \Drupal::theme()->resetActiveTheme();

  // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
  // sufficient, since the list of enabled modules might have been adjusted
  // above due to changed code.
  $files = array();
  foreach ($module_data as $name => $extension) {
    if ($extension->status) {
      $files[$name] = $extension;
    }
  }
  \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
  // New container, new module handler.
  $module_handler = \Drupal::moduleHandler();

  // Ensure that all modules that are currently supposed to be enabled are
  // actually loaded.
  $module_handler->loadAll();

  // Rebuild all information based on new module data.
  $module_handler->invokeAll('rebuild');

  // Clear all plugin caches.
  \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();

  // Rebuild the menu router based on all rebuilt data.
  // Important: This rebuild must happen last, so the menu router is guaranteed
  // to be based on up to date information.
  \Drupal::service('router.builder')->rebuild();

  // Re-initialize the maintenance theme, if the current request attempted to
  // use it. Unlike regular usages of this function, the installer and update
  // scripts need to flush all caches during GET requests/page building.
  if (function_exists('_drupal_maintenance_theme')) {
    \Drupal::theme()->resetActiveTheme();
    drupal_maintenance_theme();
  }

There's a module too, enable admin_toolbar's admin_toolbar_tools submodule to have it all in the toolbar:


How can I use Display Suite with a Drupal Commerce view? I am new to Display Suite and want to use it with the Drupal Commerce checkout forms. In particular for the review stage, which is made from a view.

I want to display the order summary in the left column and the customer profile address details in the right column.

I can see how Display Suite is used for regular nodes, but can not find any information about how it can be used for views fields. Is this even possible?

In the FORMAT section of the views edit page, there is a "Show:" option.

If you choose "Fields" (oftentimes the default for any Entity view, including nodes) then you cannot control the output of those fields with Display Suite.

There is an option "Rendered Entity".

You can alter the settings for this option, and select any view mode that you have created/configured with Display Suite. For example you can create a view mode "Foo", and select that view mode in the settings for the "Rendered Entity" option. This will work for any entity.

So you want to create a new view mode for your Commerce entity, select the layout of your choice, put the fields you want in the regions of your choice (maybe the two column 50/50 layout), and in your view Select "Rendered Entity" and select the proper view mode.


Adding 'AddThis' sharing functionality to a Drupal Commerce Checkout page How can you add the 'AddThis' sharing buttons to a Drupal Commerce checkout page?

I tried adding an AddThis field to the product content type as I do for the other content types to wish I want to add this module but that doesn't seem to add it to all the pages in the Drupal Commerce checkout process.

If anyone knows how to do that that would be great. Thanks!

As you discovered in your comment, the recommended approach would be to have the AddThis block show up on the checkout/* pages. The question is: what are you sharing, exactly?

If you're wanting to include the sharing process as part of checkout, a new, custom pane would be the best place for this.


How to add Wishlist/Add to Cart in all products shown in front page in drupal 7? I am work on commerce_kickstart site. I was created 3 views in my front-page. In each view 3 products are there. I want to add Wishlist/AddToCart below in the list of every product. How can i do this. Please Help. Thanks

Install and enable the Commerce Wishlist module and in views add the Commerce Product: Add to Cart form field, then you can see Wishlist/AddToCart button. Also Enable the checkbox "Link products added to the cart from this display to the current path the customer is viewing where the View is rendered".

Don't forget to set permission and configuration.

  Features

  Provides an “Add to Wishlist” button on the display product node;
  Creates a customizable list with Views to display all products on the Wishlist – both as a page and as a block;
  Recognizes and stores product variations;
  Makes it possible for users to easily delete or switch products in their Wishlist to their Shopping Cart with the click of a button;


How to create a "go back" or "cancel" button on the node add form? I'm trying to add a "cancel" button to my content type.

In hook_form_alter(), I'm using this code:

  if ($form_state->getFormObject()->getOperation() == 'default') { // On node add, make it clear "cancel" deletes any input
    // Do not show cancel button to people who have not completed their profile.
    if ($user->hasPermission('create MYTYPE content')) {
      $form['actions']['submit_cancel'] = array (
        '#type' => 'submit',
        '#weight' => 999,
        '#value' => t('Delete all input and return to previous page'),
        '#submit' => array('MYMODULE_userpageredirect_callback'),
        );
      $form['actions']['submit_cancel']['#attributes']['class'][] = 'btn-danger';
    }
  }

....

/**
 * Cancel changes and return to previous page
 * @param array $form
 * @param FormStateInterface $form_state
 */
function MYMODULE_userpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $route_name = 'user.page';
  $form_state->setRedirect($route_name);
}

This creates a cancel button that returns the user to the user page when they click cancel.

Problem

If a field is marked required, and the user has not input any text in the field, the browser prompts the user to input a value into the field before the cancel button will work.

Adding '#limit_validation_errors' will help override validation,

$form['actions']['submit_cancel'] = array (
  '#type' => 'submit',
  '#weight' => 999,
  '#value' => t('Delete all input and return to previous page'),
  '#submit' => array('MYMODULE_userpageredirect_callback'),
  '#limit_validation_errors' => [],
);


How to use hook_form_alter in the .theme file to alter the form fields? I need to know how to use hook_form_alter in .theme file as i have to alter the form fields related to user_register_form.

I tried putting the below code in the .theme file but it does not even reach the function

/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Adding custom validation for the welcome page type field.
  if ($form_id == 'user_register_form') {
     print_r('Reaching in here');exit;
  }
}

If you want to alter a specific form, and you know the ID, use hook_form_FORM_ID_alter() rather than the generic version:

function THEMENAME_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add alterations specific to the user registration form
}

Make sure you clear the cache after renaming the function.


JSON:API to Migrating Taxonomy References isn't mapping OK, for a number of reasons I'm doing a Drupal 8 - Drupal 8 migration using the JSON:API module on the source site.  I've run into an issue attaching taxonomy terms to nodes.  Here's as far as I've gotten :

1) I created a vocabulary called "Photo Categories"

2) I've created and run import_drupal_taxonomy_photo_categories to import the terms.  This works perfectly.  I have manually checked to ensure they all get in.  I use the UUID as the migration's unique identifier.

3) I have a content type called Photos, it has a field called Photo Category which references the Photo Categories vocabulary.

4) From the source JSON in the relationships section I see this:

"field_photo_category": {
   "data": [
     {
       "type": "taxonomy_term--photo_categories",
       "id": "84c1e8bd-16f7-429f-b299-50fe43297d47"
     },
     {
       "type": "taxonomy_term--photo_categories",
       "id": "00931a31-d129-4c55-a962-f7ba11fed5a4"
     }
  ],
  "links": {
    "self": "https:\/\/seanreiser.com\/jsonapi\/node\/photo\/1396b571-0ece-4a07-ab17-7327e030dfb5\/relationships\/field_photo_category",
    "related": "https:\/\/seanreiser.com\/jsonapi\/node\/photo\/1396b571-0ece-4a07-ab17-7327e030dfb5\/field_photo_category"
  }
}

5) In the source > Fields section of import_drupal_type_photo I have:

-
  name: field_photo_category
  label: 'Field Photo Category'
  selector: /relationships/field_photo_category/data

6) In the process section I have:

  field_photo_category:
    plugin: iterator
    source: field_photo_category
    process:
       plugin: migration_lookup
       migration: import_drupal_taxonomy_photo_categories
       source: id

As I understand it this should loop through the field_photo_category.data and do a migration lookup on each id.  But nothing is getting mapped.

I have verified that the ids match the ids in the data section match the UUID from the taxonomy term JSON.  I have checked the database and verfied that ids appear in migrate_map_import_drupal_taxonomy_photo_categories.soure1 and they map to the appropriate tids.

I have installed the migrate devel module and when I run the migration with --migrate-debug this is what the destination section look like:

  'field_photo_category' => array (2) [
        array (1) [
            'source' => string (36) "84c1e8bd-16f7-429f-b299-50fe43297d47"
        ]
        array (1) [
            'source' => string (36) "00931a31-d129-4c55-a962-f7ba11fed5a4"
        ]
    ]

So, my question, what am I doing wrong?  I have the rest of this part of my migration laid out and this seems to be the final obstacle.

Thanks in Advance

Entity reference fields need to fill their target_id column

field_photo_category:
  plugin: sub_process
  source: field_photo_category
  process:
    target_id:
       plugin: migration_lookup
       migration: import_drupal_taxonomy_photo_categories
       source: id


How to modify term reference field in Drupal 7 custom content type? I am using a term reference field in a content type in Drupal 7 which is a long hierarchical list of categories. In the input form, I want to show them as checkboxes and it gets displayed as a flat list of around 100 items and that of course is not user friendly at all. What hook do I use or where do I manipulate the code of the generated field so that I can display them in a hierarchical way and at the same time use some jQuery to show hide the sub categories. I guess I can intercept it in the theme preprocess and modify the field but I believe theres a better way?

Try the Taxonomy Term Reference Tree Widget.

  This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.

Sounds like it would be perfect for your needs, but if not it's fully themable and already has the jQuery functionality built in so would be a very good place to start.


Get user ID for database insert I have a form inserting into a database in Drupal 8. I would like to insert the user id. I have the following code:

$userCurrent = \Drupal::currentUser();
$uname = (int)User::load($userCurrent->id());

Without the (int) Drupal throws an error saying it cannot be converted into a string. With the (int) Drupal always returns 1. What am I doing wrong?

UPDATE: As stated I would like the user ID not the user name. Sorry if it doesn't make sense, I am very new to Drupal and there is not a lot of documentation for 8 yet.

Do you want to get the username, as the variable name suggests?

$uname = User::load($userCurrent->id())->name->value;

Your question does not make sense, why load the user with the id to get the id, you already have?


How can I sell time slots using drupal Commerce? I want to allow customers to purchase products for a specific time slot and within a date range. Can this be done?

I want to achieve the following.

Allow products to be sold within a certain date range.
Also allow products to be sold for a certain time within that date range, for example between 1200 and 1300 or 1200 and 1220.
Show availability of those dates / time slots on a calendar for people to choose from.

Looks like you are looking for Commerce Booking:

  This module provides tools to use Drupal Commerce as a powerful event booking system. Any entity can be an 'event' and a single booking can contain any number of tickets.


How to implement an option for users to limit access to nodes/comments to users with the same role while posting it? How can I offer users an option on all node/comment postings to limit access to their own user role group? Essentially making the conversation accessible only for the members of their own year who they are together with in person.

Each year gets its own user role. There are multiple years of group members using the site, and sometimes members would like to limit sensitive content to themselves, as old members retain access to the site otherwise.

Ideally, it would just be a single checkbox that reads 'make this content private to your peer group' without offering any other options, which should restrict the content to their own peer group and to admins.

The short answer is: Yes, you can do this with the Group module.

Here are some instructions on how to do so:

Install the Group module and its dependencies.
Enable the Group Node module as well (a sub-module of Group).
Navigate to admin/group, or click the new Group link in the admin toolbar.
Create a Group Type "Year".
Configure the permissions for that group type to allow members to create and/or view nodes (outsiders will not have access unless checked).

There are numerous things you could add to the mix, such as a "Year admin" group role. But giving a sitewide admin the "Bypass group access" permission will do just fine as well.

You can also delete the group_admin role under Group > Group Roles should you not need it.

If you find any bugs or need support you can also use the Group module's issue queue.

Disclosure: I'm the module maintainer.


Seeking module/technique for giving site visitors a download "gift" in exchage for their email A friend has an eBook site where he sells his eBook. A customer bought a large bulk order for use as a large group gift, but he wants my friend's site to be able to collect the email addresses of all the people who goto the eBook site and retrieve their gifted eBook.

So, we're seeking some module or technique that an anonymous user can visit a page, and by supplying their email to a form, they get access to download their pre-purchased eBook.

Now, I know how to write a module to do this, but my friend can't afford me, I'm already working full time, an so on... anyone know of some technique or module to accomplish this without writing a new module?

Seems like something along the lines of a CCK form for getting each email, which would then need to be verified by something like the Email Verification module, and once passing that test the user simply gets a role assignment for access to the download page.

However, being a code-monkey, I have no idea how to handle the glue logic of this solution without writing a module.

I would use Webform Rules Module. On submit and validation of an email address have a Rule that redirects the user to a download page. Of course, since it's Rules you might be able to conjure up all kinds of wonderful complicated things. I also found these lovely tutorials on Rules at NodeOne. However, you might be able to write a module faster than it would take to work through all those videos.


How to add tabs to a form? On a node add/edit form I have "upload file" and "link to url" form fields. I would like to create tabs for "upload file" and "link to url" for each field.

I would like ajax style tabs that don't require a reload of the page. Is there a solution for that in Drupal or do I need some css magic?

Use the Field Group Module. It comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
Field Group:

Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
The field group project is a follow-up on the field group module in CCK. The release will only exist for Drupal 7 release and higher, so since the existence of the Fields API in core.
By moving field group to a separate module, this may open some new perspectives.


How to update a menu link created with MenuLinkContent::create()? I know how to search for menu items created with *.links.menu.yml:

$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute('user.page');
foreach ($menu_links as $menu_link) {
  // Do something
}

However I'm looking for a way to search for and update a menu item created with MenuLinkContent::create():

$home_new = MenuLinkContent::create(array(
  'title' => t('Home'),
  'link' => array('uri' => 'internal:/'),
  'menu_name' => 'main',
));
$home_new->save();

After creating this menu item, how do I look it back up again to modify it?

If you remember the id after saving the menu link

$id = $home_new->id();

You can load it directly:

$link = MenuLinkContent::load($id);

If you don't know the id, you can load the menu link by a property:

$links = \Drupal::entityTypeManager()->getStorage('menu_link_content')
  ->loadByProperties(['title' => 'Home']);

if ($link = reset($links)) {
  // found a link with title "Home"
}


Enabled Panels In-Place Editor module but cant see the edit icon I am using Panels and have enabled the Panels In-Place Editor module but cannot see the edit icon on the page, the one that should be in top rhs corner.

What am I doing wrong?

you need to select the Renderer mode:

Standard or   In-Place Editor

Standard
Renders a panel normally. This is the most common option.
  In-Place Editor
Allows privileged users to update and rearrange the content while viewing this panel.


How to theme /comment/# page Currently example.com/comment/# shows the contents of the node that the comment is posted to. I want the page to only show the comment.

I'm assuming the page does not theme via .tpl.php. And if it isn't, do I put something like this in the template.php, and how do I override the current content of that page:

$comment = _comment_load($cid);
return theme('comment',$comment);

There's no conventional way of doing this as far as I'm aware but if you want to do this it can probably be achieved with some processing in your theme.

function THEME_preprocess_page(&$variables) {

  // DO SOMETHING WITH request_uri() or similar

  if (isset($SOME_VARIABLE)) {
     $variables['theme_hook_suggestions'][] = "page__comments";
  }
}

Then create a copy of your page template as page--comments.tpl.php and take out what you dont need.

This is nasty though and not the 'Drupal' way of doing things.


Make a block display in one page and not in other I am using Drupal 7 with omega and adminimal theme. I use adminimal theme for my iframe in the site (using entity iframe module). I would like to display a block in the adminimal theme alone, but not in my omega theme.

I used the default block settings, "Only the listed pages", but this display the block in both the themes.

So is there a way to configure the display options per theme?

Any help would be widely appreciated.

In the block's Region settings you can specify the block to be displayed in which region of respective themes(Admin and site theme) as below:


Developing coding skills I am finally retired and have a bit more time on my hands. I'm pretty good with CSS and building a site from Drupal 8 using it "out of the box". But I'm  hopeless when it comes to additional PHP coding, and adding patches etc.

Lots of the advice I see on Drupal Answers goes over my head - can anyone point me in the direction of lessons in simple coding for Drupal?

Welcome to the community! It's nice to see interest from people who come from other angles :)

Although this type of question isn't suitable for this platform, I'll try to answer anyway. If you want more help I recommend you try chatting on IRC with other Drupal developers and see what they recommend.

Unfortunately no one has managed to write a programming book for non-programmers, at least I'm not aware of any. If that were possible then no one would write programming books for programmers ;)

You'll probably need some PHP intro course if you want to start with Drupal, then pick up any Drupal development book that is beginner friendly.

You could probably also get by by using code snippets available online in tutorials and on drupal.org. There's plently already available if you're trying to solve common problems.

But the Drupal projects don't include only the engine part, there's the database side of things. You can try to learn basic SQL. There are excellent books you can find, and plenty of freely available intros online too.

You mentioned patches, that is a workflow side of things, versioning code, you need to learn Git for that. Also a lot of free online help in that department.

It's a long way to go if you're a newbie but want to get to a point where you can solve most Drupal problems yourself. If you're not doing it for your own pleasure, if you want to build projects for others, maybe honing your existing skills would be better, in partnership with someone else who complements you. There are plenty of Drupal programmers who can't CSS and don't have the breadth and depth of knowledge about existing Drupal modules, how to configure Views for common cases etc.


Why does my view duplicate the same content ( translation )? I have a multilingual site for Properties with 2 languages ( English - Arabic ) and I have a view that give me the all properties that I need to sell.

But when I enter to this view every multilingual content will duplicate like is shown in this image:

This is the filter criterion :

Any idea to solve the duplication problem?

after searching I found the solution for my problem :

This may happen if you have applied filters on any date field.
So.

in Views Advanced Settings under OTHER options, select "Query Setting" and check "Distinct" option.

That's it .


How can I save arrays of values in the database? I am trying to save multiple values from a textarea to a database table.

I use the following code, but I feel it is the wrong way.

foreach ($user_emails as $key => $value) {
  $insert_banned_emails = db_insert('banned_users');
  $insert_banned_emails
    ->fields(array(
      'email' => $value,
    ))
    ->execute();
}

Is there a different way for achieving the same result?

I would use the following code.

foreach ($user_emails as $value) {
  $query = db_insert('banned_users');
  $query->fields(array('email' => $value))->execute();
}

Alternatively, you could use the following code.

$query = db_insert('banned_users')->fields(array('email'));

foreach ($user_emails as $value) {
  $query->values(array('email' => $value));
}

$query->execute();

With MySQL, the query uses the multi-value syntax.

With other databases, the executed queries will be one for each call to $query->values(), wrapped in a transaction. This means the queries will be rolled back when one of them fails. In fact, the code executed from InsertQuery::execute() is the following one.

  // Each insert happens in its own query in the degenerate case. However,
  // we wrap it in a transaction so that it is atomic where possible. On many
  // databases, such as SQLite, this is also a notable performance boost.
  $transaction = $this->connection->startTransaction();

  try {
    $sql = (string) $this;
    foreach ($this->insertValues as $insert_values) {
      $last_insert_id = $this->connection->query($sql, $insert_values, $this->queryOptions);
    }
  }
  catch (Exception $e) {
    // One of the INSERTs failed, rollback the whole batch.
    $transaction->rollback();
    // Rethrow the exception for the calling code.
    throw $e;
  }

In short, I would use the code you are using if the inserted values are independent from each other; I would use the code I shown when the values depend from each other.

In your case, the emails are independent from each other. If you would use the second snippet I shown, the database table will contains all the values, when the sub-query don't fail, or none when a single sub-query fails.

You could also use drupal_write_record(), even though I much prefer the other snippets.

foreach ($user_emails as $value) {
  drupal_write_record('banned_users', array('email' => $value));
}

I don't see any pro in using this snippet, though.

Reference

Insert queries


How to display all taxonomy terms as links and point them to nid in views I created a taxonomy vocabulary and terms.

I created a content type with the taxonomy.

I added contents.

I would like to create a views block that will display all the taxonomy terms as links as well as each link should point to its NID.

For my views block:

I selected the taxonomy field.

I selected "Rendered taxonomy terms" in Formatter.

Click the Taxonomy field.

Selected output this field as link.

Entered node/[nid] as links path.

It did not work.  Also, links are not pointed to NID. Can you please help how to edit the views settings?

Views settings:

Assuming that the basis of your View is a node, you can add a field to your View: Content: Link (which is a link to the node of the View's row) and use the Rewrite results > Rewrite the output of this field with the contents of the taxonomy term (if I'm not mistaken [field_cities_we_serve1]).


Merge two drupal views with different base types ('user' and 'node') Is it possible to merge two views, one based on users and one on nodes?

The purpose of this is to create a directory of contacts, however some of the listings will be site users and some will not be - they will be created by admins.

It has crossed my mind to just use a content type that users can create; the downside of this is that if they update their details they'd have to update their node too...

Why not simply use a content type only?

You can for example add an optional user reference field to a content type, which points to the user to whom the contact belongs. Then you can embed the content type into the user profile, if you want that. For example by using the Panels project.

For normal users, you could write a few lines of custom code to automatically populate the user reference to the current user and hide the field from them. You could also add a check that they can only create a single contact, if you want that.


Can you filter nodes in a view by the last date of one node referencing that node So I have two content types Tours and Concerts. Concerts has an entityreference field that references a tour. I want to filter a view of Tours and only show tours that still have upcoming concerts. Once all concert in a tour are over I no longer want to show the tour. Is there a way to do this? Could you use hook_field_extra_fields to calculate the date and then somehow filter by that value in views?

The following steps should set this up...

Create a view of tours
Add a relationship of type "Entity Reference: Referencing entity" to the concerts
Make sure "Require this relationship" is ticked
Add a filter for the date field on the concert type
Select "Text" under "Date selection form element"
Ensure the relationship you set up is selected in the "Use relationship" dropdown
In the filter settings, change Operator to "Is greater than"
Change "Select a date" to "Enter a relative date"
type "now" under "Relative date"


Add image file programmatically in drupal 6 i want to upload an image on my site. I have a custom form in a module with

  $form['picture'] = array(
  '#type'   => 'file',
  '#title'  => t('Avatar'),
  '#prefix' => '<img src="' . $user->picture . '">'
  );

  $form['#validate'][] = 'product_validate_picture';

and in my validate fucntion :

$validators = array('file_validate_extensions' => array('jpg png'),
                    'file_validate_image_resolution' => array('500x500'));

$file = file_save_upload('picture', $validators);
dsm($file);

The problem is that i do not get the picture returned by the form, i only get "0" which is an error. So, did i do something wrong, or another method is better to get and save a picture returned by a custom form?

Thanks.

This is not good job save file in validation phase and really  where you get file from posted data ?
file exist in $form_state['value']['picture]

mybe below code help you

function yourmodule_form_submit($form, &$form_state) {

    $file = $form_state['values']['picture'];

    $validators = array();
    $file = file_save_upload('file', $validators, 'public://');
....


Alphabetically ordering vocabulary terms in a translated I have 5 English-Italian terms in a views exposed filter:
Academic | Accademico
American Studies | Studi americani
Medieval Studies | Studi medievali
Music | Musica
Reviews | Recensioni
The English language appear in alphabetical order and, as you can probably guess, the rendering order for the Italian translation is:
Accademico
Studi americani
Studi medievali
Musica
Recensioni
The desired order is:
Accademico
Musica
Recensioni
Studi americani
Studi medievali
I sort of halfway understand what is happening here. My question is whether this is something that is best remedied by hook_form_alter() or whether there is some obvious translation configuration I am missing in Views?

I found an old solution for Drupal 7 and just changed it until it worked. ;)
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state) {
  if (array_key_exists('MYEXPOSEDFILTERKEY', $form)) {
    asort($form['MYEXPOSEDFILTERKEY']['#options']);
  }
}

It's fairly simply and works as at that point the options are already translated. So, you just need to sort the options in the respective filter.


Change specific block look & feel I have a block like this:

Languages

Nederlands

English

Français

(From the language switcher module)

But now I would like to have something like this:

<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
  Action
</button>

Action

Another action

Something else here

Separated link

Where do I have to change this?

Create a template file in your theme.

block--locale.tpl.php


Is Windows XP and XAMPP able to render complex development sites in Drupal 7? I am developing a site, and in the Linux server it goes very fast, with peaks of memory of 40 MBytes, according to Devel module. However, when I test it exactly the same in Windows XP and Xampp, it takes a long time to serve each page, even if the memory usage is a little less - (25 Mb !? ). When Drupal 7 is freshly installed, with default configuration, it is very fast, but when I add modules, etc., it takes ages to load any page, even if the memory usage is low as I said. Memory limit of PHP is 128 Megabytes.

Sorry if my question was not well formatted. It happens that the theme installed was rebuilding on every page load, and that consumed lots of RAM. I switched off the rebuild, and it worked very fast, as expected. It was not a specific OS problem, but a performance one due to theme rebuilding


Drupal 7 - access to page content in template.php In Drupal 7 I'm trying to access the body field of a page from template.php. I want to find a keyword in the text and then send subsequent text to a separate variable so that I can format it in page.tpl.php

I can access the node using
    $vars['node']
but can't find a way of accessing the content part of the node.

I can access the content in page.tpl.php using:
    $node->body[$node->language][0]['value']
but cant use the same or similar syntax in template.php

In page.tpl.php the content of the page is available in $page['content']. It seems that your are mixing two different concepts here: pages, any page on the site (including administration page, taxonomy terms page, and other not directly editable pages) and nodes, editable content. This can be rather confusing as a default Drupal installation provides a page content type. So you end up with page nodes, which are nodes of a the page content type.

The layout of the content of a page displaying a node, is handled in the node.tpl.php template. In this template, the body of the displayed node is available in $content['body'].

If you really need to access a field (handled using the Field API) of the node object ($node) from the page preprocess function in your template.php, you can use:

function THEME_preprocess_page(&$variables) {
    $node =& $variables['node'];
    $value = field_get_items('node', $node, 'FIELDNAME);
}


Problems displaying full article - teaser only My problem is that when I manually define teaser and body of the article, only the teaser displays after clicking "Read more" (the text entered in "Body" section isn't visible in any case)
I've defined max lenght of teaser to high value (2000) because I would manually set part of article which is visible in teaser mode but I think it should not impact on displaying full body.

It sounds like the "Format" for the Default display is wrong. What is the "format" value shown in http://YOUR.DOMAIN/admin/structure/types/manage/YOUR_CONTENT_TYPE/display? Typically it should be "Default". If the Default Display is set to "Summary or Trimmed", then you'll get the effect you mention, with the Summary in both the Teaser and Default versions.

You can check this by changing the settings and doing Preview on the node edit page. Preview shows the Teaser and Default versions simultaneously.

Also, is "Custom Display Settings" checked for the Full Content, or just the Teaser? Typically it would be just the Teaser. If you have set Custom Display Settings for Full Content, then check the settings as above.

By the way, <!-- break --> works fine in Drupal 7. I use it.


Using drupal-scaffold correctly I am in the process of starting new projects using drupal/recommended-project over the Drupal composer project template. One of the differences I have noted is that the Drupal scaffold tool fires every time even when just installing a new module or theme.

In this case, I get write permission warnings about settings.php, and I have other concerns such as .htaccess or robots.txt being replaced.

I read some of the docs and added this in my composer.json file:

"drupal-scaffold": {
    "locations": {
        "web-root": "docroot/"
    },
    "file-mapping": {
        "[web-root]/sites/default/settings.php": false,
        "[web-root]/.htaccess": {
            "mode": "replace",
            "path": "assets/drupal/.htaccess"
        }
    }
},

This prevents settings.php from being touched, and replaces the .htaccess file from Drupal with one containing our modifications. The drawback that I see here is if .htaccess had some security changes, I would have to do a manual diff and put the custom rewrite rules back in.

Is this the proper way to use drupal-scaffold?

I use the patch method mentioned on https://www.drupal.org/docs/develop/using-composer/using-drupals-composer-scaffold#toc_4

e.g:

"name": "my/project",
...
"scripts": {
  "post-drupal-scaffold-cmd": [
    "cd docroot && patch -p1 <../patches/htaccess-ssl.patch"
  ]
}

Then if the core file changes it will either merge correctly or the patch will fail and you'll see that in your composer command and can make the relevant changes to your patch


EFQ SQL error when using filedCondition on two different taxonomy terms I'm using the below code to select a 'store' content type which has two taxonomy fields: category and brand.

$queryStore = new EntityFieldQuery();
$queryStore->entityCondition('entity_type', 'node')
  ->entityCondition('bundle','store', '=')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_city','tid', $city_id, '=')
  ->addMetaData('account', user_load(1))
  ->execute;

 if ($_GET['category'] != 'Choose a category'){
   $queryStore->fieldCondition('field_category','tid', $category_id, '=');
 }
 if ($_GET['brand'] != '') {
   $queryStore->fieldCondition('field_brand','tid', $brand_id, '=');
 }

However when I choose a brand like Chanel and a category like Food (naturally such node doesn't exist since Chanel doesn't do food), I get the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) AND (field_data_field_city0.deleted...

I'm using Drupal 7.
Is there a way to avoid such error?
I appreciate any help given

Thanks

If you check your error you will notice that your query is trying to look for a column named field_data_field_city0.deleted... , it appends a 0 to it. This problem occurs because the type of value you choose for that column in field query is not correct.

Can you check an confirm if field_city is a taxonomy type of field. If you can access your DB check the table field_data_field_city and check what is the name of last column.


Twig extension issues I'm trying to write a simple twig extension to render a menu inside twig template files.

I created a custom module for this purpose. It's folder structure looks like this:

-modules
--MenuRender
---src
----MenuRenderExtension.php
--menurender.info.yml
--menurender.services.yml

The *.info file is a standard file, the *.services files looks like this:

services:
  menurender.twig_extension:
    class: Drupal\MenuRender\MenuRenderExtension
    tags:
      - { name: twig.extension }

And the MenuRenderExtension class is as follows:

namespace Drupal\MenuRender;

class MenuRenderExtension extends \Twig_Extension {

  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * @return array
   */
  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('renderMenu', [$this, 'renderMenu'])
    ];
  }

  /**
   * Provides function to programmatically rendering a menu
   *
   * @param String $menu_name
   *   The machine configuration id of the menu to render
   */
  public function renderMenu($menu_name) {
    // 50+ lines so i cut this part as it's mostly clean PHP
  }

}

I am constantly getting this error msg in apache's error log

Service 'menurender.twig_extension' for consumer 'twig' does not implement Twig_ExtensionInterface

Any one have a clue ?
p.s. new to drupal8

Your module name should not be camel case, but should instead be mymodule (not MenuRender). Your namespace needs to reflect that, too. It should likely live under a folder in src called TwigExtension, and your module name in the namespace should match the directory (i.e. Drupal\mymodule, not Drupal\MyModule).

Here is a module that uses TwigExtension for comparison.

What's likely happening is the application is unable to locate certain things due to the file naming and namespacing.


Managed to delete Event_Calendar_Status and cannot reinstate When trying to get rid of notification emails every time I create a calendar event, I have managed to delete the ?built-in? event calendar status term. I have tried to reinstate it but machine will not allow the same name as original. It's causing an undefined index Notice which will not now let me save any new events.

Have not got much stuff on the site yet, so may have to disable, uninstall and reinstall the calendar module?

This appears when creating new calendar event:
Notice: Undefined index: event_calendar_status in event_calendar_form_alter() (line 293 of web1/user47631/website/sites/all/modules/ event_calendar/event_calendar.module)

Grateful for any help or suggestions...

Cynthia

I have not checked the module, but here are few things I can suggest take a database backup before you take any step.Uninstalling calendar module should be not helpful, as it seems settings to be changed in event_calendar module.

How you deleted the status term,did you make any direct changes to database?can you revert back those changes? You can setup event_calendar module on fresh drupal installation to track what changes can be done to make it work.

Not sure, but keep uninstalling and reinstalling event_calendar module as last option.

I guess event_calendar provides UI for mailing notifications settings, as the project page says

  This module also gives an Admin UI to change status (approval/denied)
  of events and a mailing system.


adding a field to the form during form_validate I am working on a node form in which my users can add sport-teams (which I'll handle through a taxonomy) that are related to the node (say it's a blog-entry about your local rugby-team and you want to relate it to the team's taxonomy entry). To each team entry, I also have a db-table with a corresponding zip-code of the teams headquarter (say your local rugby team comes from cardiff).

Now the users can also add teams, that are currently not in the taxonomy list (through the use of taxonomy-autocomplete (i.e. tagging)). When that happens, during form_validate, I fire a form_set_error() and ask the user to type in the City the team is coming from.

In effect, I want to add a field to the form during form_validate. But how do I do that?

I tried, to no avail, adding the following to the $form variable in the form_validate function:

$form['field_new_team_location'][$i] = array(
'#type' => 'textfield',
'#title' => t('new team location'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,
'#description' => t('description')
);

EDIT Alas, although Charlie S' answer helped me to put up a field during validation (read: the html gets displayed; I can write in them), but it seems I cannot access it in a follow-up validation. In fact, when I hit save again, neither $form nor $form_state have the newly created fields in them! Any help accessing my fields is much appreciated!

2nd EDIT With what Charlie S said, it works. One thing that holding me up was that the form only gets rebuilt when no error messages are being cast. In other words, every required field has to be supplied before the form gets rebuilt and the user is able to input something in the new fields.

In form_validate(), make sure your arguments are being passed by reference:

myform_validate(&$form, &$form_state)

Then the last thing you should have in _validate() is:

$form_state['rebuild'] = TRUE;

Edit: You will want to handle the actual adding of the element in the form builder. This is tested and working:

function customform_custom_form($form, $form_state) {
  $form['field_a'] = array(
    '#type' => 'textfield',
    '#title' => 'Field A',
    '#required' => TRUE,
    '#weight' => 1,
  );

  // Add field b depending on the value of field a.
  if (isset($form_state['input']) && !empty($form_state['input']['field_a'])) {
    $form['field_b'] = array(
      '#type' => 'textfield',
      '#title' => 'Field B',
      '#weight' => 2,
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#weight' => 99,
  );

  return $form;
}

function customform_custom_form_validate(&$form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
    form_set_error('field_b', 'Please enter something in Field B.');
    $form_state['rebuild'] = TRUE;
  }
}

function customform_custom_form_submit(&$form, &$form_state) {
  drupal_set_message('You entered ' . $form_state['values']['field_b'] . ' for Field B.');
}


Order nodes via drag 'n drop I'm looking for an easy way for my clients to re-arrange the order of nodes.
When creating a content type I added a "weight" field for them to change, but of course with a lot of content this is a lot of work.

Is there any module that allows drag 'n drop to change the order of nodes being displayed in a view?

I think DraggableViews is what you are looking for. Here is a quote about it (from the module's project page):

... makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
Have you ever rearranged Blocks, sorted Taxonomy terms or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
With DraggableViews you can apply this tabledrag.js to any Views-generated table.


Don't link menu in the active page My Q is equal as Remove link from active page in menu

  I need the active page in my menu not to be a link.

  So let's say I'm on the services page, I need my menu structure to
  look like this:

home

services

portfolio

contact

How can I do that in drupal 8?

Update
what about this thing in my theme menu--main.html.twig?

{% if item.attributes.hasClass('active') %}
{{ item.title }}
{%- else -%}
{{ link(item.title, item.url) }}
{%- endif -%}

In D8 the handling of active links is split between php and js, so that the menus can be cached independently from the page they appear on. A solution in php or twig is only possible when you switch off caching of menus, but this is not good for performance. So a better approach is probably in javascript.

Remove the link tag by selecting the links with the class is-active:

mytheme/js/remove-active-links.js

(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.removeActiveLinks = {
    attach: function (context) {

      $(context).find('a.is-active').contents().unwrap();

    }
  };

})(jQuery, Drupal);

You need to define a dependency on the core active-link.js, which sets the class is-active, so that your js file runs later:

mytheme/mytheme.libraries.yml

remove-active-links:
  version: 1.x
  js:
    js/remove-active-links.js: { }
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.active-link

Background information

The js code above is the most basic solution, but it loads jQuery also for anonymous traffic, which is not a problem if you already use it.

If you want to avoid jQuery see ActiveLinkResponseFilter, which is a response subscriber adding the class is-active for anonymous requests.

You can then alter the result in a custom response subscriber with a lower priority, similar to the js code above.


How does #value_callback really work (nested elements, ...)? EDIT: Separated 4th question.

I've just recently started working with custom elements and already came across some weird behavior / questions I'd like to see answered.

1) How does #value_callback work, what should you return in it, etc. ?

Imagine you have pretty simple custom element without set #element_validate:

function TST_element_process($element, &$form_statem, $form) {
  $element['testing_test'] = array(
    '#type' => 'textfield',
    '#default_value' => 'ABC',
  );

  return $element;
}
function TST_value_callback_1($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  return ($input['testing_test'] . '_valc_');
}
function TST_value_callback_2($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  return array($input['testing_test'] . '_valc_');
}

'TST' => array(
  '#input' => TRUE,
  '#tree' => TRUE,
  '#process' => array('TST_element_process'),
  //'#element_validate' => array('TST_element_validate'),
  '#value_callback' => 'TST_value_callback_1', // or TST_value_callback_2
),

And form:

$ar['inp'] = array('#type' => 'TST');

1A) When you use TST_value_callback_1, the callback gets called and runs but doesn't alter the result value in any way (in submit the $form_state['values']['inp']['testing_test'] contains pure input -> ABC).

1B) In case of TST_value_callback_2 the $form_state['values']['inp']['testing_test'] still contains unaltered input but there's also value in $form_state['values']['inp'][0] which contains the 'right' value (ABC_valc_).

My questions are:

1.1 what exactly are you supposed to return in #value_callback and why do the individual callbacks work in the way they do (or don't do in case of the first one).

1.2 is there any way how to make the #value_callback store the data in 'element root' ($form_state['values']['inp']), i.e. in the same place as if I used form_set_value in #element_validate?

2) How do individual #value_callback work on custom element that is made of other elements?

Let's say you have a custom element (A) that is made of a nested set of other elements with set #value_callback.

for($a = 0; $a < 10; $a++) {
  $element['indiv_elems'][] = array(
    '#type' => 'indiv_element',
  );
}

Then a number of things can appear in $form_state[values][<element_name_in_FAPI_array>] depending on how you approach #value_callback in the custom event (A) (and some of those things make little sense to me).

2A) When you don't use #value_callback in (A) at all, the $form_state[values][<element_name_in_FAPI_array>] will contain array of raw inputs (not processed by its #value_callback function) from each phone_numbers element.

2B) When you set #value_callback in (A) but let it return (let's say) empty array(), the $form_state[values][<element_name_in_FAPI_array>] will contain array of  inputs from each indiv_element element processed by their (individual  #value_callback function) .

My question is:

2.1) Why do the values not get processed by individual #value_callback when parent element's #value_callback is not set. Basically why is there difference between 2A) and 2B).

3) Do I understand this flowchart  correctly that #value_callback is called before #element_validate?

I'm also aware that it will be quite time consuming to answer this question, so many thanks and love ahead! :)

One thing i want to add before replying to your questions. Drupal core FAPI doesn't allow multiple #value_callback. It allow only one #value_callback per element type. Even You don't have to add #value_callback key in your hook_element_info() if your value callback follow the format form_type_' . $element['#type'] . '_value'.
// See code in include/form.inc from function _form_builder_handle_input_element line 2034

$value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';

1) How does #value_callback work, what should you return in it, etc. ?

value_callback provides a way to process values before they are returned to the form submit function. You need to provide a #value_callback if you want to do fancy processing on the input. If you just want #value set to #default_value, you don't need this hook at all, since that will happen anyway. This function is mainly useful if you need to do something non-standard with the value, like transpose an array into an option list.
Value callbacks should consider three conditions:

Input is being provided directly. This happens when a form is submitted.
No input is provided, but the field definition has a default value.
No input is provided and there is no default value.

1.1) what exactly are you supposed to return in #value_callback and why do the individual callbacks work in the way they do (or don't do in case of the first one).
So value callback is supposed to check the $input !== FALSE and then modify the $input value as per your logic. If its false that means $input value is not provided in this case you can return the $element['#defalut_value']. So in your first value callback TST_value_callback_1 if you want to make that work you have to return the value with the same array key something like.
function TST_value_callback_1($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  $input['testing_test'] = $input['testing_test'] . '_valc_';
  return $input;
}

In your second value callback TST_value_callback_2  it was adding value to $form_state['values']['inp'][0] because you was returning an array with index 0 having the value ABC_valc_ like array(0 => 'ABC_valc_');
// code from include/form.inc from function _form_builder_handle_input_element line 2109

// Set the element's value in $form_state['values'], but only, if its key
// does not exist yet (a #value_callback may have already populated it).
if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  form_set_value($element, $element['#value'], $form_state);
}

1.2 is there any way how to make the #value_callback store the data in 'element root' ($form_state['values']['inp']), i.e. in the same place as if I used form_set_value in #element_validate?
Setting the #tree to false in your form element should do the trick.
$ar['inp'] = array(
  '#type' => 'TST',
  '#tree' => FALSE,
  );

you will be able to get the value in $form_state['values']['inp'] but in this case #value_callback will not do any affect, and $input in #value_callback is set to NULL  i don't know why. So you better use the ($form_state['values']['inp']['testing_test'])
2.1) Is there any way to enable 2.2 behavior without setting #value_callback in ?
2.2) Why are individual #value_callback functions run (and their outputs are saved to $form_state) only when parent (A) #value_callback is run (even if it doesn't reference or call the individual functions in any way)?
Hopefully my above explanation help you to understand the role of #value_callback. Even though custom element that is made of a nested set of other elements, are also elements so individual value callback will be called for each subelement. There is too much too explain Please take a look at _form_builder_handle_input_element
3) Do I understand this flowchart correctly that #value_callback is called before #element_validate?
yes #value_callback is called before the #element_validate callback. For more explanation See Creating Custom Elements
For practical example see examples module.
See also:
https://api.drupal.org/api/examples/form_example%21form_example_elements.inc/function/form_type_form_example_checkbox_value/7
https://api.drupal.org/api/examples/form_example%21form_example_elements.inc/function/form_example_phonenumber_combined_value/7


How to get the parent entity title inside image.html.twig I want to get the node title inside an image.html.twig override so I can use it to replace the 'title' and 'alt' attributes of the image.
So far I was able to pass simple variables with THEME_preprocess_image(&$variables) but no luck getting the title of the parent node.

The cleanest solution that I could find is to get node object in image-formatter.html.twig which is a wrapper to image.html.twig.

Add THEMENAME_preprocess_image_formatter to your THEMENAME.theme

function THEMENAME_preprocess_image_formatter(&$variables) {
  $variables["node"] = $variables['item']->getEntity();
}

Copy core/themes/classy/templates/field/image-formatter.html.twig into your THEMENAME/templates directory.

Now you can get the node title in this twig file using {{node.getTitle()}} or {{node.label()}}

The twig file might look like this

Node title: {{node.getTitle()}}

{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

Don't forget to rebuild cache (clear cache) for the changed hooks/twig files to be seen by your Drupal installation.

Alternatively if you want to just change the alt and title attributes of your image based on the node title here is one way to do it (covers question in the comments)

function THEMENAME_preprocess_image_formatter(&$variables) {
  $node = $variables['item']->getEntity();
  $variables["image"]["#alt"] = $node->label();
  $variables["image"]["#title"] = $node->label();
}


Automate the creation of settings.php and files directory I am using Drush make files and Drupal Installation profiles to streamline the creation of new Drupal websites (which are created in the sites directory of my Mac).

Everything is working fine. The Drush make file automatically downloads Drupal and all the modules I normally use on each site.

However, for each new Drupal website, I have to create a files directory and a settings.php file and then set them to writeable.

Is there any way I can automate this process, so these files are created when Drush downloads the files for the Drupal website?

Try using the drush site-install command. Name your installation profile with the command argument.


How do I return a Twig template inside the build method of a block class? Am new to Drupal and this week I learned quite a bit about module development, and for today the case is:

For my new module, I create a custom block that renders a markup, and from the folder structure, the class looks like this:

Note: fax is the module's machine name.

fax/src/Plugin/Block/FaxBlock.php

<?php
namespace Drupal\fax\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;

/**
 * Provides a 'Fax' block.
 *
 * @Block(
 *   id = "fax_block",
 *   admin_label = @Translation("Fax block"),
 * )
 */
class FaxBlock extends BlockBase implements BlockPluginInterface {

    public function build() {

        return array(
            '#markup' => $this->t('This is just a text initially'),
        );
    }

}

I know that in the build method we can also return a form for instance:

 public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\rsvplist\Form\RSVPForm');
 }

And that we can put HTML inside the array if we want.

Question: how can I instead create a template a return that inside the array?

so, instead of returning a markup like this:

'#markup' => $this->t('This is just a text initially'),

I could have a template somewhere:

This is a great example

and then return the template in the build function.

How can I return a template inside the build method of my block?

In your modules *.module file you must implement hook_theme() like this:

/**
 * Implements hook_theme().
 */
function fax_theme() {
  return [
    'fax_custom_theme' => [
      'variables' => [
        'test' => NULL, # Makes the {{ test }} variable available in the template.
      ],
    ],
  ];
}

Then you can return this in your block:

$test = 'My custom variable';
return [
  '#theme' => 'fax_custom_theme',
  '#test' => $test, # Assigns a value to the {{ test }} variable.
];

This makes the {{ test }} variable available in your theme.

Then add your template to the module under fax/templates/fax-custom-theme.html.twig.

Template names are using dashes instead of undercores.


how can I activate modules and themes? I am very new to drupal, so, sorry for my basic question. I have tried to instal new modules and themes. The installation process went OK, I got a"successfully installed" message. But when I want to activate the new module, it does not show up on the HOME / ADMINISTRATION / MODULES list.
The Update Manager module is activated, I am logged on as an administrator, I have all the rights set, but I still cannot see the newly installed modules or themes.
Any ideas would be appreciated. Thanks. Greg

You can enable your installed modules here.

/admin/modules

and your theme here

/admin/appearance

You can double check to make sure the modules & theme are really there by navigating to your site modules & themes folder.

/sites/all/modules
/sites/all/themes


Moved Drupal 6 site to new server - can't login I'm migrating a client's site to a different server because we're changing web hosts. The domain name still points to the old site for now and I either use an ip address or a temporary url to preview the new site. However, since I moved it, I can no longer log in, I get an "access denied" error message. Is this a known issue? How can I resolve it?

EDIT: I oddly don't have this problem when I download the site to my hard drive and run it locally.

This happened to me so many times back in the days of Drupal 6.

99% of the time it was caused by the anonymous user record having been removed from the users table in the database.

Try adding a user to that table with a uid of 0 (and all other fields empty); if the above is what's causing the problem, that should fix it.


How to alter textfield auto-submit delay? I have a view with exposed filters using AJAX and auto-submit feature.

The problem is it reacts too fast, submitting the request after every key up very fast, so that the view is reloaded before users could finish to type search text...

I would like instead to choose how many millisec it waits before sending request...

I tried different ways to do that, this working one was suggested by Andy in comments to a close but different issue, thanks to him !

In fact CTools autosubmit has a hardcoded delay on submitting fixed to 500ms.

A possible way is to switch auto-submit.js to your own modified copy. However if you do this, you'll need to check if auto-submit.js has changed every time you do an upgrade to CTools. :

function neptune_js_alter(&$javascript) {
  if ($some_condition) {
    $new_autosubmit = drupal_get_path('theme', 'YOUR_THEME') . '/js/auto-submit.js';
    $javascript['profiles/commons/modules/contrib/ctools/js/auto-submit.js'] = drupal_js_defaults($new_autosubmit);
  }
}

And set your value into auto-submit.js :

//Lines 87 and following
    var timer = 3000;
          .keyup(function(e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          })
          .bind('change', function (e) {
            if ($.inArray(e.keyCode, discardKeyCode) === -1) {
              timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
            }
          });

To be more flexible you may want to add an attribute to the input you need to change :

function MODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {
  $form['MY_INPUT']['#attributes'] = array('class' => array('ctools-auto-submit-delayed'));
}

And then change value for this class only

    var timeoutID = 0;
    var timer = 500;
    if ($(this).hasClass('ctools-auto-submit-delayed')) {
      timer = 3000;
    }
    $(this)
      .bind('keydown keyup', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID && clearTimeout(timeoutID);
        }
      })
      .keyup(function(e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      })
      .bind('change', function (e) {
        if ($.inArray(e.keyCode, discardKeyCode) === -1) {
          timeoutID = setTimeout($.proxy(triggerSubmit, this.form), timer);
        }
      });

This would be more elegant & flexible to pass directly the timer value to js, but I have no time to think more about it.

PS : there is an existing patch about that issue but it returns errors in my config.


How to start views list at specific ID I have a list of images(nodes) displaying horizontally and I would like to start from a certain id in this list. The way I have it now it starts at most recent added image(node).

Is there a way to start at a specific id in views?

NOTES:  Would like it to look like the second image on page load. You can see in the first image there is white space to the left. I want this to be filled by an image. The navigation is fixed.

I would suggest perhaps using a Nodequeue - http://drupal.org/project/nodequeue.

This way you can order the images in whichever order you like.

Alternatively, if it is just one node that you want to appear first and then sort by something else you could perhaps utilise the 'sticky' feature?

OR do you want the order to start from ID 5 and continue 6, 7, 8 etc?


Commerce Customizable Products I hope I could receive some help concerning Commerce Customizable Products. I am looking for a possibility to, when adding a product, selecting the options a customer could add on the 'add to card form'.

For example: Pizza A can have the toppings X, Y and Z. However, Pizza B can only have the toppings Y and Z.

How do I manage, when I add the pizzas to my store, that I can select which supplements can be added? When I have 100 pizza's, I can configure the toppings, but don't have to have 100 different taxonomy lists.

I hope my question is clear. I have watched Josh Miller his screencast on YouTube about customizable orders.

Kind regards,
Tim

The only workable solution that I've come up with sits in a feature request in that module's issue queue; I haven't had a chance to try it out yet. Basically, I believe you can use a field on the product type as an options mask for the same field on the line item type. When a field is present on a line item type and shown on the Add to Cart form, its options will typically default to whatever is in the field settings. However, if you put that same field on the product type as a multi-value field, you could then use a form alter of the Add to Cart form to only show the options on the Add to Cart form that were selected for the product.

Again, this is just an idea - not implemented yet. But it seems like a very feasible way to accomplish what you want (and it's based on some architecture I actually helped a community member implement during a cocktail reception at DrupalCon Munich ; ).


Flag module integration with Message module I am using Rules, Message, Message Notify and Flag modules.
I added a message to the activity stream when user flags a node as "Favorite".

My problem is I am getting notification, but the node that was flagged seems to be missing from the message entity. Please guide for the steps, or where I may be wrong

UPDATE:
Adding rules in export format for better understanding and reference. In mail being send through rule, every token is working perfectly, but not in message added to activity stream.

{ "rules_user_likes_a_node" : {
    "LABEL" : "User likes a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_group_flag" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "node", "value" : [ "flagged-node" ] },
          "PROVIDE" : { "variable_added" : { "node" : "Added variable" } }
        }
      },
      { "mail" : {
          "to" : [ "flagged-node:author:mail" ],
          "subject" : "[flagged-node:content-type] [flagged-node:title] est aim\u00e9",
          "message" : "Hello [flagged-node:author:name],\r\n\r\n\r\n[flagging-user:name] loved[flagged-node:content-type] [flagged-node:title]",
          "language" : [ "" ]
        }
      },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commons_activity_streams_user_likes_a_node",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "message" : "Created entity" } }
        }
      },
      { "data_set" : { "data" : [ "flagged-node" ], "value" : [ "flagged-node" ] } }
    ]
  }
}

Actually, I tried "Set a data value" action, but was setting wrong variables in it. Using it right way and adding "Save entity" action (I think without this also it may work fine now) worked for me.

Following is the rules' export format in case someone need it in future:

{ "rules_user_likes_a_node" : {
    "LABEL" : "User likes a node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_group_flag" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "node", "value" : [ "flagged-node" ] },
          "PROVIDE" : { "variable_added" : { "node" : "Added variable" } }
        }
      },
  { "mail" : {
      "to" : [ "flagged-node:author:mail" ],
      "subject" : "[flagged-node:content-type] [flagged-node:title] est aim\u00e9",
      "message" : "Hello [flagged-node:author:name],\r\n\r\n\r\n[flagging-user:name] loved[flagged-node:content-type] [flagged-node:title]",
      "language" : [ "" ]
    }
  },
      { "entity_create" : {
          "USING" : {
            "type" : "message",
            "param_type" : "commons_activity_streams_user_likes_a_node",
            "param_user" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "message" : "Created entity" } }
        }
      },
      { "data_set" : {
          "data" : [ "message:field-target-nodes:0" ],
          "value" : [ "flagged-node" ]
        }
      },
      { "entity_save" : { "data" : [ "message" ] } }
    ]
  }
}


How can I disable all outgoing emails from a site all at once? There are some automated outgoing emails from my Drupal site like by core system mail, ubercart, webform and Rules.

The reason is that I also have a test site which is exactly the copy of the production site. And I would like to disable all the outgoing emails so that no mails will be sent from the testing one by mistake.

I have installed "phpmailer" "mime mail" "mail editor" modules.

Is there an out-of-box way to do this?

The Maillog module is for exactly this purpose, as

  Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core.


Use taxonomy path for a node's path alias Is it possible to use a token to reference the alias of a taxonomy term in the pattern of an automatic alias for a node type where that term has been selected, in Drupal 8? (Let's assume a single taxonomy term is selected.)

For example: If one has a taxonomy of Names where the values are James, Margaret, Daniel and each name has a path assigned to it (/news/jim, /news/peggy, /news/dan) is it possible to construct an automatic path for "News" node types where the pattern is something like [taxonomy:Names:path]/[node:title] so that if one selects "Margaret" from the Names list and gives the node a title of "Summer Vacation 2017," it will result in the automatic node path of /news/peggy/summer-vacation-2017?

All the references to path aliases based on taxonomy that I have found use the entity value of the term, which I don't want. I don't want /news/margaret/summer-vacation-2017 as the result of the above example.

Using pathauto, it should be quiet easy with a pattern like :

Normal way :

news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

With hierarchy :

news/[node:{NAME_OF_TAXONOMY_FIELD}:entity:parents:join-path]/[node:{NAME_OF_TAXONOMY_FIELD}:entity:name]/[node:title]

In your case, this should work

[node:{NAME_OF_TAXONOMY_FIELD}:entity:url]/[node:title]


Control access to a custom blocks edit page I have a small module which creates and adds some custom settings for a block. Now I would like to control access to this blocks edit page. All users should be able to display the block, while changing the actual the configuration only should be available to certain users.
Since I am not able to use hook_permission() I am not really sure how to best solve this so any help would be much appreciated.

Edit

I have tried this without any success:

function MYMODULE_block_info() {
  return array(
    'MYBLOCK' => array(
    'info' => t('MYBLOCK'),
    'cache' => DRUPAL_CACHE_GLOBAL,
    ),
  );
}

When I clear the cache and tries to go to the blocks edit page the url changes but nothing happens. It is like I am still standing on the block overview page?

function MYMODULE_permission() {
  return array(
    'administer MYBLOCK' => array(
    'title' => t('Administer MYBLOCK'),
    'description' => t('Administer MYBLOCK settings.'),
   ),
  );
}

function MYMODULE_menu_alter(&$items) {
  $items['admin/structure/block/manage/MYMODULE/MYBLOCK/configure']['access arguments'] = array('administer MYBLOCK');
}

Edit

If I use user_access() in hook_block_configure() I almost achieve what I want. I don't know if this would be a valid way to solve this problem:

function MYMODULE_block_configure($delta = '') {
  $form = array();
  if ($delta == 'MYBLOCK') {
    if (!user_access('administer MYBLOCK')) {
      drupal_set_message(t('You are not allowed to edit the @block block.', array('@block' => $delta)), WATCHDOG_WARNING);
      drupal_goto('admin/structure/block/manage');
      drupal_exit();
    }
    // Setup form for the block here.
  }
  return $form;
}

/**
 * Implements hook_permission().
 */
function my_module_permission() {
  return [
    'my_module_custom_permission' => [
      'title' => t('My Module Custom Permission'),
      'description' => t('Explain what this permission allows the user to do.'),
    ],
  ];
}

/**
 * Implements hook_menu_alter().
 */
function my_module_menu_alter(&$items) {
  $items['admin/structure/block/manage/block/5/configure']['access arguments'] = ['my_module_custom_permission'];
}

If you use the code above, follow the steps below.
Steps

Replace all instances of 'my_module_custom_permission' to a machine name that makes sense.
Update the 'title' and 'description' for the custom permission.
Replace all instances of the word 'my_module' with your module's machine name.
Change the $items path from what I have to the block path you are trying to update.

Important to note
If the block you are editing was created from the frontend of the Drupal website, then it can be deleted. If it gets deleted and then recreated, the block's ID will change. Which in turn changes the path to the block's configuration page.
Testing
Make sure to give your test user the permission we've just made and make sure they can edit the block configuration. Also, test a user who does not have the permission and make sure they can not edit the block configuration.


Add uid to existing menu link I have a custom menu MyMenu and I have four menu items.
What I want to do is to add the current uid as a parameter at the end of the link.

In D7 I could use menu_tokens module which is not available on D8.

I tried to create a routing file in my custom module.

So in my routing file MY_MODULE.routing.yml I added :

MY_MODYLE.my_applications_redirect:
  path: '/my-applications'
  defaults:
_controller: '\Drupal\MY_MODULE\Controller\MyApplicationController::redirect_to_my_applications'

And in MyApplicationController.php :

namespace Drupal\MY_MODULE\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * A controller that redirects to the my applications page.
 */
 class MyApplicationController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function redirect_to_my_applications() {

    global $base_url;
    $user = \Drupal::currentUser();
    $path = '/my-applications/'. $user->id();

    $response = new RedirectResponse($base_url . $path);
    $response->send();
  }

}

Also in the menu I have set the path to /my-applications.

Do I miss something?

PS. The "my-applications" page is a panel page.

As i can see from the menu token that the module has a pre-released version for drupal 8 as development release, so maybe you could try it out or at least search in its code to find a way to accomplish your needs.

I have recently built a drupal 7 website and i have used the menu token to create a hover over drop down usermenu with username and profile picture.

See image below (i drawed in black on top of it because the site in not yet online)

If you like, i can right back small tutorial on how i achieved that !


hook_cron_queue_info 'time' value I've been searching around, but I can not find a good explanation (or understanding) what the 'time' value in hook_cron_queue_info actually does, or how to set it to work properly.

From: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_cron_queue_info/7

it is said that: 'time': (optional) How much time Drupal should spend on calling this worker in seconds. Defaults to 15.

I don't quite understand that. Does calling the worker mean time allowed to execute the cron queue job?
And does the next cron queue job starts after this time? Or when the previous job is completed?

It's literally what the description says it is - during a cron run, Drupal will spend a maximum of the seconds you provide in that value processing that particular queue, regardless of the number of jobs in it.

If you're looking for the relevant code it's in drupal_cron_run()

foreach ($queues as $queue_name => $info) {
  if (!empty($info['skip on cron'])) {
    // Do not run if queue wants to skip.
    continue;
  }
  $function = $info['worker callback'];
  $end = time() + (isset($info['time']) ? $info['time'] : 15);
  $queue = DrupalQueue::get($queue_name);
  while (time() < $end && ($item = $queue->claimItem())) {
    $function($item->data);
    $queue->deleteItem($item);
  }
}


Why do my custom javascript modules not work anymore after updating bootstrap? I have some custom javascript modules in my Drupal site that worked perfect. Yesterday I performed an update for bootstrap and unfortunately the custom javascript modules doesn't work.
I get bellow errors to chrome developer tool console:

  Uncaught TypeError: $ is not a function

If you want to see the problem, you can here: http://www.neashmera.gr/


Which Views hook do I use to alter the view results page before it loads? I have a view that I want to change two items right before the page loads - the title, and the zipcode that determins the location to filter by.

My module detects a person's location and replaces the default value in the Views filter so that the results are properly sorted by that area.

So, the title changes to 'Viewing items around Charlotte, NC' where Charlotte, NC is the dynamic element.

I have created a module, but I am not sure what views hooks I need to use to achieve the results, especially getting the view to execute with the new location.

Here are the views hooks for D7
http://api.drupal.org/api/views/views.api.php/group/views_hooks/7

Do I pre_view it? pre_render? Alter the query with the new location details before its executed?

Here is a sample of my module trying to use hook_views_pre_view

function zipcode_filter_views_pre_view  ( &$view, &$display_id, &$args) {

    $view = views_get_view('baby_clothes_pages');
    $view->set_display('default');
    $view->set_exposed_input(array('postal_code' => $zipcode));
    $view->display['default']->handler->options['title'] = $title;

}

note: this reference influeced the code I used. However, the documentation is wanting. Am I even on the right track with this? http://groups.drupal.org/node/10129

The answer was to remove the views_get_view function as well as the set->display function. There was also no need to try to execute the exposed input. All that was needed is to simply set the default values for the variables I wanted in the views_pre_view hook, and then Views takes care of the rest as it finishes doing its thing. Here is the resulting, correctly working code:

function zipcode_filter_views_pre_view  ( &$view, &$display_id, &$args) {

    $view->display['default']->handler->options['title'] = "this is the new title";
    $view->exposed_input['distance']['postal_code'] = $_SESSION['zipcode_filter']['zip'];
    $view->exposed_input['distance']['search_distance'] = $_SESSION['zipcode_filter']['distance'];

}

Although, I don't understand why this works - Why do I not need to specify a display? Why did having the other parts of earlier code cause it to not work properly?


importing blogs from another database with different content type fields I need to import blogs from a drupal database to another drupal database. Both the old and new drupal content types have different fields. I would like to get some hints about the sql queries or drupal api functions to be used and the process to be used to get data from old database.I have access only to the mysql database and not ftp/admin side.

Try using the feeds module and export to a CSV file then import the data under the new respective fields. You may need to add extra fields to the new content type to prevent data loss


How to prevent image files being duplicated while importing nodes with the Feeds module? I have a large catalog import where the items often refer to a single common image (such as "brand_logo"). When I import the images via CSV parser, if the item refers to the same image file, an incremented duplicate is created.

Example: Using the example files supplied with the module, I modified 2 books to use the same image file, which are imported to files/field/image/ as 51JQbhO0MmL.jpg and 51JQbhO0MmL_0.jpg.

This causes the images directory to balloon to 20 times the size it should be (lots of shared images).

Honestly, what I would prefer to do is to upload the images to the site separately (manually, via FTP etc.) and just import the links to the images, but I haven't figured that one out either.

(The data (files) is not being replicated, just the images are replicated.)

I found a solution to this. What you need to do is to install the Media Feeds module.

In your CSV file there is a column called e.g. image and reference the image using public://myimage.png.

Then in your mapping delete the original image mapping and create a new image mapping. When you do this you will have a new option for the image mapping.  Make sure you set the target configuration to "Source is exactly the filename".

No more duplicated images.


How do I get an array of all entitytypes of a specific entity? Hey there what I'm trying to do is to get all entity type ids from my custom config entity.
To load them all.

Example give:

I have an entity 'foo' and I create a new 'foo' named 'bar1' and another 'bar2' and so on how do I get those ids programmatically?

Better question

How do I get all entity_type_ids(or bundles dunno don't found a good entity hirarchie doku yet :( ) of an entity for example all types of the node entity?

Do you mean "How do I get an array of all entities of a specific entity type?"

$ids = \Drupal::entityQuery($entity_type_id)->execute();

Because an entity can only be of one type, to get the id of the entity type:

$entity_type_id = $entity->getEntityTypeId();

Answer to the edited question:

"How do I get an array of all bundle id's of a specific entity type?"

$bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);

Or all content types, which are bundles of the entity type node:

$content_types = \Drupal::entityManager()->getBundleInfo('node');

This function will be moved to it's own class before Drupal 9:

\Drupal\Core\Entity\EntityTypeBundleInfoInterface::getBundleInfo()

This is provided as a service:

$content_types = \Drupal::service('entity_type.bundle.info')->getBundleInfo('node');


Menu token module is causing errors When creating one of the menu items I accidentally left the "Use tokens in title and in path." option checked while setting the path to .

It is now causing the following error on every page:

Notice: Undefined index: path in menu_token_translated_menu_link_alter() (line 160 of /home/mysite/public_html/sites/all/modules/menu_token/menu_token.module).

I am now trying to delete this menu item and create a new one in its place but I am unable to delte it. It times out. I was able to disable but it is not preventing the error message from displaying. How would I go about deleting this menu item?

Disabling the Menu Token module, then deleting the corrupted link, and re-enabling the module did the trick.

Thanks.


Error when adding BCC to email handler with webforms and smtp I use SMTP to handle emailing and Webform to generate my forms on a drupal just upgraded to 8.7.10

I have recently discovered an issue where webforms that have an emal handler set to include a BCC email address throw the follwing error:

error: Call to undefined method Drupal\smtp\Plugin\Mail\SMTPMailSystem::_get_components()

The form submission does get saved but the confirmation process breaks so the user is not notified the submission saved and no emails of any kind are sent out.

Not including BCC fixes the problem. I use BCC in email handles to debug on a number of my sites and have never had this issue before. Any ideas? Is this a problem with webforms or smtp modules?

It looks like the issue lies with the SMTP module. The release notes for 8.x-1.0-beta6 include a bug fix for:

#2993124 by jmuzz, qichanghai, Chris Matthews: Call to Undefined Method error _get_components when there is a BCC


Mini pager on View in a block does not work I have a view that is displayed on a rightside block using quicktabs.

In Quicktabs it is the third option and set up as a view (as opposed to set up as a block).

It lists authors on a blog, and has a pagination feature. The mini pagination DOES show up, it just doesn't do anything. The pagination link appears but doesn't actually effect the view in the quicktab.

I've tried changing the Views ajax feature both on and off and neither have an effect.

If you want pagination to work as being a block display, you will have to set Use AJAX to Yes under Basic settings in your view edit page.

In the page display Pager work as it receives parameter as query string variable ?page=1.


After save empty cache of referenced node I have two content types. For clearer question I will work with the content types event and location.

From my location content type I can reference to and event.

Then on the event page I show the location that is connected to this event. I do this by creating a Views Block. This views block is showing content of the type location with a contextual filter to only show content with the Content ID from url.

This works fine. But there are events that don't have a location. On these events page I have a button saying add location. I do this with the following Twig Tweak:

{% if drupal_view_result('view-name', 'location-block') is empty %}
    Add location
{% else %}
    {{ drupal_view('view-name', 'location-block') }}
{% endif %}

This also works. But when I am on a event page and click the add location button I can add the location. When I go back to the same event page I was before I still see the add location button. Because the page is cached.

Is there a way to empty the cache of this event page after saving the location that is refering to the event? Or is there a other way to deal with this?

I tried if the problem was in the views cache but it wasn't turning it off for the block or removing only the views cache didn't work.

Thanks in advance

You may specify any cache meta data directly in your Twig template. I suppose 'node_list' cache tag can help in this case.

{{ {'#cache': {'tags': ['node_list']}} }}

Another approach could be configuring views 'No results behavior' to show that link.


Views as blocks - dropdown filters On Drupal 7 I have a view with filters exposed to the user, which are dropdown lists. I want to use this View as a Block within a page. The only way to get this to work is the tick the "Use AJAX" checkbox in the Advanced section. However this means that the dropdown lists change to autocomplete fields, and I want to keep them as dropdowns. Is there any way to do that?

(Alternatively, is there any way to add the options that appear in the tabs at the bottom of a piece of content to a view page?)

there is also a module Better exposed filters. Gives more options for the user. Maybe it is possible to do it with that module