How to create a user1, user2 and 3 others like this post? I'm creating a website and there is a problem that I have encountered. I need to create list of posts. And each posts have a like button and shows who's liked the post exactly as in Facebook. The likes are handled by the flag module. The list of posts is in a view. What I need to do is figuring out each nid every post has in the view and pull the latest likes and the number of likes each post have.

If this is already in a view -- you can do the flag/like counts by adding a relationship to the view (I'm assuming you're on Drupal 7).  Add the 'Flags: Node flag counter' relationship and select the flag you want the counts for.

Then you can add, for each piece of content in your block or page, the 'Flags: flag counter' field.  That'll appear only once you've added the relationship.  Make sure to select for it to use the relationship.

Let me know if this doesn't make sense and I can elaborate a little more.  :-)


Accessing translation and language URL from hook_preprocess_menu() I have setup language and translation in Drupal8 that affects my URL for example

myurl.com/ru
myurl.com/us
myurl.com/fr

What I need to do if find out which country is being accessed so I can add a variable to the twig theme layer

This is the hook that is working fine

/**
 * Implements hook_preprocess_HOOK() for menu.html.twig.
 */
function pnc_preprocess_menu(&$variables) {
    $code_to_access_language_url = 'this is a test';
    kint($variables);
    $variables['access_translation'] = $code_to_access_language_url;
    //print $code_to_access_language_url;exit;
}

I have found that under kint() there a lot of public methods for  translation but I am not sure how I access them or which one to access. I know I could regex the url, but there has to be a cleaner way to do it?

I found the answer myself.

if($variables['menu_name'] == 'navigation') {
  $langcode = \Drupal::languageManager()->getCurrentLanguage()->getName();
  // Add the logic here.
}


How to prevent display of specific paragraph types (bundles) on nodes I have a content type with a paragraph field which has many paragraph types available.  For one of these paragraph types, I do not want it displayed in the node because I am displaying it using a view in a different region.  The view works great but I cannot figure out how to prevent the specific paragraph type from displaying on the node. I've tried to removeItem from the render array using various hooks in .theme, but this removes it from the view as well.  I have also tried to remove the paragraph type from the paragraph field in the node template using a loop in twig.  I feel like there has to be an easier way.

Twig's without filter worked in my case.


Permissions on example payment method- Drupal commerce This is probably something simple, but I'm having a hard time configuring the permissions that would only allow the administrators to see the example payment method of the Drupal Commerce module. I have example payment method activated for testing purposes but every time I activate it, the example payment methods appears public. How can I configure the permission so that only the administrators can see the example payment method. I appreciate any help.

You have to go admin/commerce/config/payment-methods
And edit the example payment. In there you can set a condition that is on user. Data type of current user is admin and that will only allow admins to process the test payments.


Localhost configuration and problem with file permissions Whenever I work on my local machine I am almost always experiencing problems related to file permissions settings, and since I guess they may be related with my local machine configuration I would like to explain how did I configure it in order to get advice on how to configure it properly (Since my knowledge on server configuration is quite limted and I am far from being a sysadmin).

My local machine is using ubuntu as OS and I installed php5, php5-mysql, mysql-server, apache2 and phpmyadmin separately using ubuntu's packages. The only custom configuration I made is that I don't place the websites in etc/apache2/www folder as default but on a specific folder at my home partition ~/www . In order to make this settings work I have to do follow this steps:

I edit /etc/apache2/sites-enabled/000-default as to point to that folder by replacing /var/www with the path to ~/www
Restart apache (sudo /etc/init.d/apache2 restart)
Create a symlink inside ~/www which points to /usr/share/phpmyadmin (#  ln -s /usr/share/phpmyadmin /home/carlos/www/phpmyadmin )

This configuration has the following benefits which are quite important to me:

I can keep my code safe whenever I install a new ubuntu release (this is, every six months) yet at the same time I can format / partition without losing any data.
I don't need extra permissions (sudo) every time I want to edit any file (which is often, since it's my development environment), update modules and so on.

However, it also has some drawbacks like the ones I mentioned with file permissions, and I think they are related to the fact that the owner of the files and folders is not www-data user but my own user.

Is there any way to prevent problems with file permissions but also preventing having to place the files in etc/apache2/www folder?

The web server must have a properly configured file structure to operate. The files should be placed under /var/www or /usr/local, not under /home. The /etc directory is for system and configuration files, not web data files.

There should be no reason for you to format the root partition when maintaining a system, but if you insist on doing so, put /var /usr and /home on a separate drive, and mount them under the root during boot. That way you will not lose any data.

If you are so desperate to ease the editing, work as root and learn to be careful. But make sure the files are under the correct group and owner for the web server to operate.


How do I get the current node ID? In Drupal 7, if I wanted to get the node id of the currently displayed node (e.g. node/145) I could get it with the arg() function. In this case, arg(1) would return 145.

How can I achieve the same in Drupal 8?

The parameter will have been upcasted from nid to full node object by the time you get access to it, so:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See the change record for more information.


Specifying the length of an integer in hook_schema Why does Drupal not allow you to specify the integer length with type int in hook_schema?

Please see the Data Types documentation, I believe you can use tiny, small, medium, big, normal


How to theme a flag for different pages? I want to theme a flag for different pages like on user profile page the html of the flag will be different then on the view page . I can make  use of the flag.tpl.php and theme it but, I don't how to theme it for different pages.

Any suggestions?

Something like this will work for user pages. You can adapt for other pages. Put it in your theme's template.php file.

function MYTHEME_preprocess_flag(&$variables) {
  if ($variables['flag']->name == "MACHINE_NAME_OF_FLAG") {
    if (arg(0) == 'user') {
        $variables['theme_hook_suggestions'][] = 'flag__user_page';
    }
  }
}

and the template file name then becomes

flag--user-page.tpl.php


How change user form mode programmatically? i create 2 custom user register form mode :

When i go to mysite/user/register

Drupal show me the last form mode i create :

  S'inscrire

But when i go in the admin mode, for add a user, it show me the same form.
i try to display "Affichage Admin" form mode with more field.

So i try to alter the form mode programmatically.

Any idea how can i change form mode before it render ?

something like this:

/**
 * Implements hook_entity_type_alter().
 */
function YOUR_MODULE_entity_type_alter(array &$entity_types) {
  // We get all form modes, for all entities, and loop through them.
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    if ($entity_type !== 'user') {
      // We are only interested in adding a handler to the Node entity.
      continue;
    }

    $user_entity = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      if ($machine_name !== 'sinscrire') {
        // We are only interested in adding this form mode to the definition.
        continue;
      }
      // We get the default handler class. It will be enough for us.
      $default_handler_class = $user_entity->getHandlerClasses()['form']['default'];
      // We set the form class, keyed by the machine name of our custom form mode.
      $user_entity->setFormClass($machine_name, $default_handler_class);
    }
  }
}

Credit goes here: https://www.webomelette.com/render-custom-entity-form-modes-programatically-drupal-8


How can I split up a massive feature module into multiple smaller modules? I have one massive unmaintainable features module that I want to split up into smaller, manageable features. Can I disable the massive module without it removing or disabling content types and dependencies, as well as strongarm variables?

I came across this solution which suggests using CTools Bulk Exporter to get the features back into the database so they can be re-exported as smaller features.

  Think I've found an alternative solution to get your exported objects
  back into the database so you can safely disable/remove your features.

  1) Export everything you want in the database using CTools Bulk
  Exporter (admin/structure/bulk-export). Put the module it generates
  into your modules folder (eg. my_exports_module) 2) Disable the
  features containing the objects you just exported 3) Enable the module
  CTools Bulk Exporter created for you 4) Download Drush CTools Export
  Bonus & enable it 5) Run the following drush command: drush cbsa
  my_exports_module 6) Disable my_exports_module

  Tested this with view modes/fields/... created in Display Suite -
  everything went better than expected :)


Display the method of payment of an order on the invoice pdf comerce billy I installed Commerce Billy.

How can I display the payment method on my bill?

<?php

/**
 * @file
 * Template for invoiced orders.
 */

?>
<?php
//The code to get payment type

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}
?>

    <img src="<?php print $content['invoice_logo']['#value']; ?>"/>

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

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

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

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

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

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

  <?php print($payment_method); // Use this PHP Code where you want to print the payment type, you can style it any way, adding div, span, whatever you want ?>

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

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

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

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

Here are the contents of my file "commerce_order--commerce_order--pdf.tpl.php".
Where do I put the code ?

You can use code below to get the payment method of an order by passing order id to the function. The order id on Commerce billy template file can be easily found in this variable $content['commerce_customer_billing']['#object']->order_id and some other variables as well:

$order_id = $content['commerce_customer_billing']['#object']->order_id;

$payment_method = '';
$order = commerce_order_load($order_id);
$r = explode('|', $order->data['payment_method']);

if (count($r) > 1){
  $rule = rules_config_load($r[1]);
  $payment_method = $rule->label;
}

After using this function, you can print the payment method on your bill by printing $payment_method variable.


Change remove from cart button to an image button I want to change the remove-button, that removes line items from the cart to an image button representing a trash can like this:

The code I am using in a custom module looks like this:

<? php
function mymodule_custom_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) {
  foreach ($form['edit_delete'] as &$item) {
    $item['#type']='image_button';
    $item['#src']='sites/all/themes/mytheme/images/trash.svg';
    $item['#alt']='Remove';
  }
}

That code shows the icon instead of the text as expected, but unfortunately it introduces a major issue: now pressing the button doesn't remove the correponding line item, but wrongly successively removes the last added line-items. So when I added item1, item2, item3 to the cart in this order, then no matter which corresponding remove-button you press, item3 is removed. Next time, you press one of the remove-buttons of the remaining 2 line-items, then item-2 is removed.
What's wrong with the above code?

You need to unset the #value on your image_buttons:

  $item['#type']='image_button';
  $item['#src']='sites/all/themes/mytheme/images/trash.svg';
  $item['#alt']='Remove';
  unset($item['#value']); // this line here

The line item that is deleted is determined by the #triggering_element in your $form_data. This element is determined by a function _form_button_was_clicked($element, &$form_state) in form.inc in the core.

It seems that when you a #value has been set on your image_button, every image button is detected to have been clicked.

  // line 2227 in form.inc
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
    return TRUE;
  }

That means at the end of the ride, the last image button is always set as the #triggering_element, and the last line item is always removed.

Unsetting the #value fixes that. Setting it to an empty string doesn't, somehow.


How can I unset an option provided by the User Relationships module on the user edit page? I want to remove the 'Receive e-mail notification of relationship activity' option from the user edit page.

The hook is provided in user_relationship_mailer.module:

/**
 * Implements hook_form_alter().
 */
function user_relationship_mailer_form_alter(&$form, &$form_state, $form_id) {
  if (($form_id == 'user_register_form' || $form_id == 'user_profile_form') && $form['#user_category'] == 'account') {
    $account = $form_state['user'];
    $access = variable_get('user_relationship_mailer_send_mail', FALSE) && user_relationships_user_access('maintain @relationship relationships', NULL, $account);
    $form['user_relationships_ui_settings']['user_relationship_mailer_send_mail'] = array(
      '#type'           => 'checkbox',
      '#title'          => t('Receive e-mail notification of relationship activity'),
      '#default_value'  => isset($form['#user']->data['user_relationship_mailer_send_mail']) ? $form['#user']->data['user_relationship_mailer_send_mail'] : TRUE,
      '#description'    => t("If checked, we will e-mail you when there are changes to your relationship status with other users."),
      '#weight'         => -10,
      '#access' => $access,
    );
  }
}

So I tried to use unset() like this in my custom module:

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_mailer_form_alter(&$form, &$form_state, $form_id) {
  if (($form_id == 'user_register_form' || $form_id == 'user_profile_form') && $form['#user_category'] == 'account') {
    $account = $form_state['user'];
    $access = variable_get('user_relationship_mailer_send_mail', FALSE) && user_relationships_user_access('maintain @relationship relationships', NULL, $account);
    unset($form['user_relationships_ui_settings']['user_relationship_mailer_send_mail']);
  }
}

However, the option is still displayed even after clearing the cache twice.  My custom module's weight is set to 777 and the weight of the user relationship mailer module is 0.  Any idea what I'm doing wrong?

You also don't need to redeclare the $access variable, as you are just removing a field from the form array:

/**
 * Implements hook_form_alter().
 */
function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if (($form_id == 'user_register_form' || $form_id == 'user_profile_form') && $form['#user_category'] == 'account') {
    unset($form['user_relationships_ui_settings']['user_relationship_mailer_send_mail']);
  }
}

That should be all you need.


How get Drupal Alias from given node NID inside a module function? I am trying to get the Alias from a given system path node NID (node/nid), inside of a node_insert function in a custom module.

I already tryied:

drupal_get_path_alias('node/866'); // return node/866 in watchdog dblog

and

url('node/866'); // return node/866 in watchdog dblog

and

drupal_lookup_path('alias', 'node/866'); // return NOTHING in watchdog dblog

and

drupal_get_normal_path('node/866'); // return node/866 in watchdog dblog

It should return seo/preparedUrl, but I can´t find a way to do this.

I need this to change a path before the node is saved.

In URL alias (admin/config/search/path) the Alias(seo/preparedUrl) and System (node/866) are there!

THE ANSWER

First of all, Thanks to @arpitr with the help with devel/php path sugestion! Really fast  debug this way!

The answer in my case is that is two languages. The path was in language, but my user was in another so, when I use dpm it continues to print the node/nid, but when I changed my user language to be equals to content language it began to work the way I want!

(I can´t answer my own question or vote up nothing here because I am a new user, so I putted here!)

It looks like you are debugging through watch dog table, you should better use devel module it provides you several debugging options few are

dpm()
example in your case : dpm(drupal_get_normal_path('node/866'));
devel/php path
which allows you to test your php codes.
example in your case : simply log in as admin visit sitename/devel/php and execute  dpm(drupal_get_normal_path('node/866')); and see what it shows

About the problem

Make sure node/866 exists
If node exists make sure when you are able to access the node-866 by node/866 and alias which you have configured.
As as an option you can delete the existing alias and create the same alias again. And check again.


Omega 4: despite of environment set to production, css-file is full of sass-debug-info I've built an Omega 4 subtheme, generating css through sass with 'drush omega-guard'. Despite my config.rb looks like this, all sass-debug-info{} rests in my generated css files:

saved = environment
environment = :production
if (environment.nil?)
  environment = :development
else
  environment = saved
end

output_style = (environment == :production) ? :expanded : :nested
line_comments = (environment == :production) ? false : true
sass_options = (environment == :production) ? {} : {:debug_info => true}

I there a wrong declaration in my config.rb or is there another setting overriding my config.rb?

I cannot see anything wrong with your config.rb but if you are having problems you can use the following to force compass to strip out the debug info.

compass compile -e production --force

Source: https://www.drupal.org/node/1936986


How do I order a search query by best match? I am using the following code.

$query = \Drupal::entityQuery('node');
  $query->condition('status', 1);
  $query->condition('type', 'article');
  for ($i = 0; $i < count($split_keys); $i++){
  $group = $query->orConditionGroup()
  ->condition('title', '%'.$keys.'%' ,'LIKE')
  ->condition('body', '%'.$keys.'%' ,'LIKE')
  ->condition('title', '%'.$split_keys[$i].'%' ,'LIKE')
  ->condition('body', '%'.$split_keys[$i].'%' ,'LIKE');
  }
  $query->range(10,20);
  $query->addExpression('CASE WHEN title like %'.$key.'% THEN 0
       WHEN title like %'.$split_keys[$i].'% THEN 1
       WHEN body like %'.$keys.'% THEN 2
       WHEN body like %'.$split_keys[$i].'% THEN 3
       ELSE 4 END', 'order_col');
  $query->sort('order_col', 'ASC');
  $entity_search = $query->condition($group)->execute();

I am trying to sort by best match, but I get the following error.

  Call to undefined method Drupal\Core\Entity\Query\Sql\Query::addExpression()

How can I fix the code?

An entity query can't have arbitrary expressions added to it. To proceed with your current approach you'll need to execute a raw query against the database.

But to address your actual question, How to create search query in Drupal 8 order by best match, the answer is to use the Search API module:

  This module provides a framework for easily creating searches on any entity known to Drupal, using any kind of search engine. For site administrators, it is a great alternative to other search solutions, since it already incorporates facetting support and the ability to use the Views module for displaying search results, filters, etc. Also, with the Apache Solr integration, a high-performance search engine is available for this module.

In my experience the Solr integration is excellent, but if you don't have a Solr server handy, you can always fall back on the included database backend module. I would imagine that the results you get using search API will be better than any query you can put together yourself in any short amount of time.


Best practice two domains on one codebase and database I have one main domain name at site.com and I simply want to create blog.site.com using the same codebase and database. The only ways I see I can do that are by:

Using another install
Using a multi-site install
Using Domain Access

Among those 3 options, the most straightforward way to keep using one single codebase and database seems to be Domain Access but I wonder if it's not overkill for my use case?

This is with Drupal 7.

It really depends on what you need to do with the Blog vs. the regular site. For Flocknote, we decided to use www.flocknote.com/blog for the blog (so it would be easy to maintain as part of the rest of the website), but also have blog.flocknote.com redirect to the /blog URL (we set that up through a simple .htaccess rule, but you could also set up the redirect through your DNS provider).

If you really don't want the blog running within the same interface/site as the main site, but still want it running on Drupal, you can do that with one of the methods you mention. Just install another drupal site at blog.example.com using a database prefix (see Sharing a single database across multiple sites). Domain Access is a great solution if you plan on setting up more than a few subdomains on the same codebase, but it's overkill if you just want to run a blog. subdomain.

Or, if you want to set up another database, you could create a folder blog.example.com in the sites folder, point the blog subdomain/virtualhost to the same directory as the main site, and then use the separate database when installing Drupal.


Role to edit user profiels but not administer accounts As far as i can tell drupal allows me to make a user role able to edit other user profiles(edit the profile fields) only if the role they have includes "Administer users."

When this is set a role can see the edit tab on all profile pages and make edits to other user profiles. Good we want that. But this also allows the user to administer accounts as well(add/remove accounts). Bad, we want that restricted so that only account admins can add/remove accounts. We want a role for a "lower tier" user to be able to edit profile fields as needed, but not administer accounts.

I use the Fields Permissions module to control access to fields. Works great, allows that different user roles can or can not see and/or edit different fields for other users.
This lets us to have internal use only fields on our user profiles that only appropriate staff can access.
But this is not controlling if a user has the ability to edit user profiles or not.
Just what specific fields in user profiles can be seen or edited IF the user already has the rights to edit other user profiles first. That is still controlled with the "Administer users" setting, which seems to only give the rights for account administration as well as profile editing all in one.

Can we separate the rights to edit user profiles from administering user accounts,
allowing for a role that can edit user profiles but not administer accounts?

Thanks for any help on this one.

This looks like it should do the trick :

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

  This module allows site builders to set up fine-grained permissions for allowing "sub-admin" users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

The normal administer users permission is split out into create, edit and cancel users per role.


Exposed Filters in Drupal 8 I am not able to get exposed filters to work in Drupal 8.  Here is a screenshot to help me while I explain some of the issues

I want to filter by the title of a content type.  This title was renamed to "Name" as you can see me trying to put it in the value for the operator to compare.  This value seems to be the default since when I try this, "Name" is in the field and not grabbing any nodes.  Without anything inside the Value box, nothing is coming up for my queries when testing this filter.

So how do exposed filters work in Drupal 8?   Nothing I have tried has gotten any results.

Exposed filters do work in 8.0.2, although there are limits of to how well you can format or alter them.

But you want to do should work fine.  Looking at your uploaded image, though, suggests you don't quite have it configured right for what you want to do.  I'd recommend that you leave "Value" blank, and choose "Contains" as the operator. Under "Advanced", check "Use AJAX". Once you "Apply" to the display, you'll see a preview at the bottom of the view edit window.  If you start typing the name (i.e., title) of one of your nodes, you'll see that the list of nodes at the bottom of the window indeed updates as you type.


Ubercart - Stay on page when you add product to cart In Ubercart, each time i add a product to the cart, i'm redirected to the cart page. Then i have to click on the link "continue shopping". Is there an option to stay on the actual page after adding product to page?

Yes.

1. Log in as admin, and go to: admin/store/settings/cart
2. Click on Basic Settings
3. Then in the "Add to cart redirect" section, enter: <none>
4. Got to "Continue Shopping Element" and set "Make continue shopping go back to the last item that was added to the cart."


Render sub-paragraph in parent template I have a paragraph that has a field of type paragraph reference to sub-paragraphs.

Within my template, I need to access these sub-paragraphs and render the entity element. I have a loop that loops through a list of Drupal\paragraphs\Entity\Paragraph elements.

I need to render the paragraph markup.
Is there a function?

I tried item|render and item.view(), but neither of them worked.

You should be able to render the sub paragraph - without any loop, just like every other field - with

{{ content.field_name }}

If you really need the loop for some special markup you can try something like

{% for key, item in content.field_name if key|first != '#' %}
  <div class="some_additional_markup">
    {{ item }}
  </div>
{% endfor %}


How to add flat rate in Drupal Commerce? I have installed the following modules in an existing Drupal site:

Commerce and Commerce UI
Customer and Customer UI
Price
Line Item and Line Item UI
Order and Order UI
Checkout, Payment, Product
Product Reference
Cart and Product Pricing
Tax
Product UI
Tax UI
Payment UI
Shipping
Shipping Flat Rate

And my online shopping is working fine as expected. Now I'm trying to setup different shipping rates, so I'm following the instructions on Flat Rate module, however when I go to Store > Configuration > Shipping there is no option to Add a flat rate service

Wha am I missing?

Check "Shipping methods" tab (or go to .../admin/commerce/config/shipping/methods). Flat rate should be listed here.

If not double check that flat rate module is enabled?

-edit-

When viewing page Store > Configuration > Shipping there is few tabs like "Shipping services" and "Shipping methods" but below them is another set of tabs, which should include "Flat rate" and should be chosen before Add a flat rate service link becomes visible on that page.


How do I add a "Please select"/ "none" option to a required select input in a form? I cant find anything about that in the drupal 8 form api on how to add an option "Please select" to a select element. The form item is mandatory so you must select something. Of course, selecting "Please select" should invalidate.

$select['#options'] = $options;
$select['#required'] = true;

As they explain in the documentation URL provided in your question you should add the #empty_option or #empty_value property to the render array of the select button.

#empty_option: (optional) The label to show for the first default option. By default, the label is automatically set to "- Select -" for a required field and "- None -" for an optional field.
#empty_value: (optional) The value for the first default option, which is used to determine whether the user submitted a value or not.

If #required is TRUE, this defaults to '' (an empty string).
If #required is not TRUE and this value isn't set, then no extra option is added to the select control, leaving the control in a slightly illogical state, because there's no way for the user to select nothing, since all user agents automatically preselect the first available option. But people are used to this being the behavior of select controls.
If #required is not TRUE and this value is set (most commonly to an empty string), then an extra option (see #empty_option above) representing a "non-selection" is added with this as its value.


Detecting language and rewriting url Drupal can automagically detect the language to use when displaying content :

Based on URL
Based on User preference
Based on Browser language.

However, when I request a url like : http://mysite.com/toot/lala, Drupal detects the english language (browser settings), but it doesn't rewrite the url to : http://mysite.com/en/toot/lala

I'm afraid that this behavior will induce Duplicate Contents errors.
Does someone know how to correctly set this redirection ?

The Global Redirect module will help you with that issue.

It has a redirection system specific for language prefixes, preventing content duplication.


Normal View with multi language website I have a normal view on multi language site and add a field Called website the field is displayed on en language but does not show in the another language

How i can fix this problem

thanks all . my problem is come from the model is called views i18n cuase it is override the result to anther that i have translate it


Count the number of content flagged by logged in user I want to get the number of items (content) flagged by the logged in user.

<?php
  $flag = flag_get_flag('flag1');
  print $flag->get_count($nid);
?>

The above line would display the total number of times that content is flagged. How can i get number of items flagged by the logged in user. Lets say user A has flagged Content 1, Content2 and Content 3. Then the output needed is something as:

Number of Items flagged by [current:user]: 3

Thanks

This work for me in normal block (no in views):

<?php
global $user;
$uid = $user->uid; //Logged in user ID
$result = db_query("SELECT COUNT(*) FROM flagging WHERE uid=:uid and fid=2", array(':uid' => $uid))->fetchField(); //fid = ID your flag
print $result ." flagged items";
?>


Change date format on editing I'm using a date field on my custom type, if I use "select" widget for node editing, I can choose only between "YMD","MDY" and "DMY" formats.

Is there a way to add custom formats? I need an "only year" format.

By default, no.  The relevant code is in \Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget::formElement().

What you want is usually called a "partial date", which is a bit of an oxymoron.  In Drupal, datetime fields are stored as DrualDateTime objects, which derive from \DateTime so have both a full date and a proper time and timezone associated with them.

A partial date (year, year+month), has to make assumptions about the rest of the parts.  For example, the date-only field currently sets the time to noon UTC.  A year only field would have to do something similar.

You may be able to create your own widget for the datetime field to do this.  You could take DateTimeDatelistWidget as a starting point, and trim it down to be just the year.  Then, you would need a masssageFormValues() to set the rest of the parts and then call the parent method (because DateTimeWidgetBase::masssageFormValues() does stuff, too).  This may or may not work, it is just the idea that popped into my head.

There is an open issue about this, https://www.drupal.org/node/2703037, that may or may not be implemeneted.


How can I stop the full HTML editor from deleting my  paragraph? https://drupal.slack.com/archives/C1BB308HH/p1602318464360700 Link to slack question in #support
JSFiddle of the offending html: https://jsfiddle.net/tyeth/xr4ohast/
Demo Video showing the paragraph beneath second image being removed: https://www.youtube.com/watch?v=Hw9NACmMsps [Was private, now just unlisted, sorry]
Hi supportive people, you must get this one a lot. I'm aware of the filter options and have customised the Full-Html mode to not use the 3 offending filters, and cleared cache, but I'm still losing content.
I'm using the drupal 8(and 9) add a custom body block using layout designer, I then use the WYSIWYG editor in full-html mode with the filters (strip bad html/convert newline br+p/convert images -- see screenshot) disabled.
However it is DELETING html from the end of the editor. I wonder if it's technically an empty paragraph as that has been mentioned in other issues (it isn't but has a link inside so doesn't have it's own text content).

Also, which module is actually doing the rich editing these days?

Could be related to the auto paragraph funcitonality of CKEditor, which is used by default and can be disabled with this !deprecated setting:
"autoParagraph = false"

This can be easily disabled using the ckeditor_config module, see https://www.drupal.org/project/drupal/issues/3131055 for more information.
The whole paragraph wrapping in CKEditor is kind of buggy, you could also try these patches: https://www.drupal.org/project/drupal/issues/2876094 (but there the problem is an added p after an img)

I had some troubles when using linkit: https://www.drupal.org/project/linkit/issues/3162596 and made this core issue https://www.drupal.org/project/drupal/issues/3162605 (this is not related to your problem as your using the align and caption filters - but you see where the magic happens - on Drupal side).


Can't get javascript to load I am trying to load a javascript file in my .info file, but I can't tell if it is loading or not. What is the best way to find out if it is loaded and if it is the right path?

Some things you can try:

The easiest way, in my opinion, is to look at the source of your page. Right click the page of your website and click "View source" (or something similar). Try searching for the reference to the javascript file in there.

This could be somewhat more difficult if you're using Javascript aggregation, which means that your file might be concatenated with other Javascript files into one big file. In that case: open the files you see in your source and search for something that's in your Javascript file.

You could also try to display an alert by appending alert('It works!') to your file.

Edit:

As said by Clive in the comments: you might need to clear your cache for the Javascript file to be included. You can clear the cache at /admin/config/development/performance.


View/query to show latest node related to each term in a taxonomy vocabulary I have a node type (stories) which is related to a taxonomy vocabulary (countries).

Each story is related to one country only.

I want to create a view of the latest story from each country, ordered by published date.  I only want 1 story from each country (if there is one).

I looked into doing this with views and couldn't see a way to limit the results to only 1 result per country.

Does anyone have any suggestion how I can do this without writing a custom query?

Thanks,

I think that's the purpose of the module Views Grouping Row Limit.


What are the security trade-offs between Organic Groups and other methods? I'm in the early stages of implementing a community site that will be made up of many sub-communities/groups. Most content will be shared between all groups (e.g. community-wide announcements and news), but there will be several sections of the site private to each group. For the sake of discussion, let's say that every group has its own private wiki, blog, and address book.

Very generally, there appear to be two options:

One site with some content split up (Organic Groups)
Multiple sites with some content shared between them (Drupal core multisite install, Domain Access module).

The site will be exactly the same (theme, menus, layout, etc.) for every group except that each group's private sections (blog, wiki, and address book) contain content accessible only within their group.

Content in the private sections will make up an extremely small portion of the overall content, which feels like one site to me. However, as security of a group's private content is my primary concern, I'm leaning towards multiple sites.

What are the main security trade-offs between the available methods and modules?

Edit: I am not necessarily using separate domains to accomplish this, but it is an option I'm considering.

It sounds like you are going to need to use Domain Access and set your organic group permissions to fit your use case.

Here are key points to Multisite vs. Domain Access.

Multisite
 - One database/prefix per site, possible to share users, tables but requires tweaking.
 - Separate install for each but can share modules and themes

Domain access
 - Single Database
 - shared content, users


Custom entity form submit handler not being invoked I'm trying to attach a submit handler to an entity form (language_delete_form) provided by the ConfigurableLanguage config entity. On the form alter function for that form, the top-level submit handler value looks like $form['#submit'] = ['::submitForm'].

I want to add an additional submission handler, so it looks like $form['#submit'] = ['::submitForm', 'locale_delete_language_submit']. However, locale_delete_language_submit is not being called during the submission process (I would expect it to be invoked after LanguageDeleteForm::submitForm is invoked). What am I missing here?

Based on Berdir's comment here (https://www.drupal.org/project/drupal/issues/2252165#comment-9437863) I would have expected the function to be invoked.

Here's my code:

/**
 * Implements hook_form_FORM_ID_alter() for language_delete_form().
 */
function locale_form_language_delete_form_alter(&$form, FormStateInterface $form_state) {
  $x = 5;
  $form['#submit'][] = 'locale_delete_language_submit';
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function locale_delete_language_submit($form, FormStateInterface $form_state) {
  $defined_value = 'fifty';
}

As discussed in slack, you misunderstood my comment. You should add it to the form-level submit callbacks if and only if that form has no button-level submit callbacks.

If it has, then you need to add yours there as well.


How to create eshop for product hiring counting price per day Currently I'm working on specific project which is product hiring and price per day depends on hiring interval. It means 2 days hiring for certain product the per day price differs from 5 days hiring. Also in this case instead of product quantity I'm using days. My question is how can I organize above mentioned structure using commerce?

Look at the Commerce Price Table module which supports the following output for a table of prices/quantity:

  contrib project that allows to have a secondary price field that
  considers the quantity for displaying and using the prices. It also
  provides a field formatter to display the price/quantity values as a
  table.


Using variation values in a template file I am building a site that uses Drupal Commerce 2 and I am attempting to build out the product details template. Our product has a variation (field_accessories) which is an entity reference to another product and I am trying to access the title, the images (first one actually), and the link to the product's detail page.

I got the title showing with

{{ product['field_accessories'][0]['#commerce_product_variation'].getTitle() }}

and I can get the sku and price with:

{{ product['field_accessories'][0]['#commerce_product_variation'].getPrice() }}
{{ product['field_accessories'][0]['#commerce_product_variation'].getSku() }}

But I need the images and url link. Based on the available methods from using kint on the product['field_accessories'][0]['#commerce_product_variation'] I tried:

{{ product['field_accessories'][0]['#commerce_product_variation'].get('field_images') }}

and

{{ product['field_accessories'][0]['#commerce_product_variation'].getField('field_images') }}

and

{{ product['field_accessories'][0]['#commerce_product_variation'].getField('images') }}

but nothing is working and all come back with null.

When I do a product['field_accessories'][1]['#commerce_product_variation'].getFields() I see the following:

Any ideas on how to access the field_images and url to that product's page? Thanks and let me know!

Here is the answer that worked for me:

product.field_accessories[0]['#commerce_product_variation'].get('field_images')[0].entity.fileuri)

And I looped over the product.field_accessories to get just the first image for each product


How to get fields in StylePluginBase i´m building a new nap view style. I get the map shown correctly, but only without the data of the view :-(.

class OpenlayersViews extends StylePluginBase {
  /**
   * Whether the display allows the use of a pager or not.
   *
   * @var bool
   */
  protected $usesPager = FALSE;

  /**
   * Whether the display allows the use of a 'more' link or not.
   *
   * @var bool
   */
  protected $usesMore = FALSE;

  /**
   * Whether the display allows area plugins.
   *
   * @var bool
   */
  protected $usesAreas = FALSE;

  /**
   * Does the style plugin support grouping of rows.
   */
  protected $usesGrouping = FALSE;

  /**
   * Does the style plugin for itself support to add fields to it's output.
   */
  protected $usesFields = TRUE;

  /**
   * {@inheritdoc}
   */
  public function evenEmpty() {
    // Render map even if there is no data.
    return TRUE;
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['openlayers_map'] = array('default' => 'none selected');
    return $options;
  }

   /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $openlayers_map_options = [];
    foreach (openlayers_get_map() as $key => $map) {
      $openlayers_map_options[$key] = $this->t($map['label']);
    }

    $form['openlayers_map'] = [
      '#title' => $this->t('OpenLayers Map'),
      '#type' => 'select',
      '#options' => $openlayers_map_options,
      '#default_value' => $this->options['openlayers_map'],
      '#required' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    dsm("OpenlayersViews:render");
    $map = openlayers_get_map($this->options['openlayers_map']);
    $mapid = Html::getUniqueId('openlayers_map');
    $features = array();

    /*
     * Here i need a function to get the result of the view
     */

    $element = openlayers_render_map($mapid, $map, $features, FALSE);
    return $element;
  }
}

I do not know, if render is the right position for getting the data.
So maybe some of you can explain, what is the next step to do.

best regards

Normally you would iterate through the rows and call a row plugin to render the field values. As I understand the question you want to access the field values directly by row index and field id?

Then try StylePluginBase::getFieldValue:

$value = $this->getFieldValue($index, $field);

Normally a style plugin iterates the rows like this:

  public function render() {
    if (empty($this->view->rowPlugin)) {
      trigger_error('Missing row plugin', E_WARNING);
      return [];
    }
    $rows = [];

    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }
    ...

For this to work you have to set protected $usesRowPlugin = TRUE; and configure a row plugin which renders the map.

If you want to do all rendering in the style plugin you can use the same loop and get the field values directly:

  public function render() {
    $rows = [];
    foreach ($this->view->result as $index => $row) {
      $rows[] = render_map(
        $this->getFieldValue($index, 'field1'),
        $this->getFieldValue($index, 'field2')
      );
    }
    ...


Making a Content Type the subpage of a Views page for the sake of Breadcrumbs I have a Content Type named Cars and a Views page which lists all those cars. Is it possible to put the Cars content type under The Views page so my breadcrumbs would come out as Home > Cars > Sample Car. Cars is the Views page, Sample Car is the Content Type.

For this you will have to use Menu Breadcrumb and Path module

Define your view's path as cars and define path for your Cars type nodes as cars/sample-car

Menu Breadcrumb will do the magic for you to arrange hierarchy of your view and nodes in bread crumb


Change sort order for view when exposed filter text field submitted I have a view that by default is ordered by date. It has several exposed filters one of which is for filtering by text (we use it as a search field). I'd like the view sort to change to Relevance when a user submits a search but I also want to set it so it only does this once in case the user changes the sort order and then modified their search string. Is this possible? I'm using Better Exposed Filters, fwiw.
The view content source is "content datasource" from the drupal search api.

If you order your view by relevance first, then date, when there is no text entered all articles will be given the same relevance score, so this will achieve what you are after.


Image Upload in a Custom Module I'm writing a custom module, and I need it to upload an image. I'm having trouble finding good documentation on this, but I think I'm close.

What am I missing? $file returns false in the form submission.

function mymodule_custom_content_block_form($form_state){
    $form = array();
    $form['custom_content_block_text'] = array(
        '#type' => 'textarea',
        '#title' => t('Block text'),
        '#default_value' => variable_get('mymodule_custom_content_block_text'),
        '#required' => true,
    );
    $form['custom_content_block_image'] = array(
        '#type' => 'file',
        '#name' => 'custom_content_block_image',
        '#title' => t('Block image'),
        '#size' => 40,
        '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Update'),
    );
    return $form;
}

function mymodule_custom_content_block_form_submit($form, &$form_state){
    if(isset($form_state['values']['custom_content_block_image'])){
        $validators = array('file_validate_extensions' => array('jpg jpeg'));
        $file = file_save_upload('custom_content_block_image', $validators, 'public://');
        if($file == false){
            drupal_set_message(t("Error saving image."), $type = "error", $repeat = false);
        }
        else{
            $file->status = FILE_STATUS_PERMANENT;
            $file = file_save($file);
        }
    }
    variable_set('mymodule_custom_content_block_text', $form_state['values']['custom_content_block_text']);
    drupal_set_message(t('Custom Content Block has been updated.'));
}

If you don't mind my saying you're doing this the hard way. Drupal has a managed_file element type that handles most of this logic for you:

function mymodule_custom_content_block_form($form, &$form_state) {
  $form['custom_content_block_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'custom_content_block_image',
    '#title' => t('Block image'),
    '#size' => 40,
    '#description' => t("Image should be less than 400 pixels wide and in JPG format."),
    '#upload_location' => 'public://'
  );

  return $form;
}

function mymodule_custom_content_block_form_submit($form, &$form_state) {
  if (isset($form_state['values']['custom_content_block_image'])) {
    $file = file_load($form_state['values']['custom_content_block_image']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}


how to deploy from dev to staging and production? Hello so here is my question,
I have three environments for my drupal 7 installation Dev, Staging, Production, right now Dev has all the new code and well everything is setup there. The move of the code from Dev to Sta or Prod is quite simple as it is just code and can be done with a simple push. But what about the configuration on the DB? how do you move DB configuration from Dev to Sta and Prod? more specifically how do you sync the configuration from Dev to Sta or Prod? so the views, nodes and whatever modules you had enabled on Dev will show on Sta or Prod?

Tried features and well it moved the code (which i already know how) but the db configuration was not transferred/enabled in the other environment

Any deployment strategy can be broken down primarly into three main streams

Content(Node,taxonomies etc.)
Code
Configuration(Content types, Vocabularies etc.)

Content Deployment

I am assuming you are not targeting content deployment as part of your deployment. Its a complex peace based on your content strategy.

Configuration Deployment

Configuration Deployment, since content and configuration are kind of tightly coupled till Drupal 7, there is no way out of the box you can just keep the configurations in sync. But there are couple of modules which let you pull your configuration into code, features is definitely one and I believe most widely used module for deployment.
Sometime you can not get all the configurations just by features module, there is another helper module strongarm module which will let you exporting variable configurations by contributed module.

Just wanted to bring the keypoints for feature module.

Features module let you bring the configuration in code.
Either you update your feature or revert your feature based on if you want to get the configurations as in feature code and revert any manual override configuration we do feature revert, if you want to get the manual updated configuration in feature code we do feature update/recreate.
Feature module compares the configuration in code and configuration in database, based on it features allow to revert/update.

Code Deployment

For code any versioning tool will do the job.


Modify/hook into admin page of rate module I'm creating a new widget type for the rate module with some custom settings. I plan to use multiple instances of the same widget each with different custom settings. Is it possible to hook into rate_widget_form to alter the admin page of the rate module ?

Example :

admin/structure/rate/add?template=widgetname
admin/structure/rate/%/edit

Sample Image :

I found the solution for my problem. I used hook_form_FORM_ID_alter

function hook_form_rate_widget_form_alter(&$form, &$form_state, $form_id){
enter code here...
}


Discussion forum for each group I need to set up a forum kind of discussion board for each group that is created. Can anyone help me with this.

You could use Panels and create a forum looking View (table) thats a copy of the same view that shows your Group content and then add it somewhere on the page. I wouldnt know how to add the 'forum' on a seperate page though.

You could add a select list in the group node form and have 'forum' or 'post' options.


How to re-render a particular field in template_preprocess_node or template_preprocess_field? This is really really easy in Drupal 7: just use field_view_field or field_view_value. Choose the latter if you want to re-render a particular field value, or the former if you want to re-render the whole field (label and all values).

However, I couldn't figure out how to do this in Drupal 6. I resorted to implementing hook_nodeapi and changing the node content before it was rendered. This approach cannot be implemented from the theme, though, I'm looking for a theme solution.

In template_preprocess_node($vars), you can do:

$node=$vars['node'];

and then all the fields of the node are available to you, and a quick

drupal_set_message('<pre>' . print_r($node,true) . '</pre>');

will show them to you.  So if you had a text field called field_description you can access it via:

$node->field_description[0]['value'];

and you can then modify to your heart's content, eg:

$node->field_description[0]['value']='What I really wanted to say was....';

and then at the end:

$vars['node']=$node;

sets it on its way.


How to provide link to styled image in a services feed On our Drupal 7 site, we use the the services module to provide a feed for our internal news to pick up. With services, you create a view for all the data to provide. It is current giving the location of the original image for our images field (File: Path) that comes out http://oursite.com/sites/default/files/post.jpg. We want to provide a link to the styled image (already resized) that should look like https://oursite.com/sites/default/files/styles/downpage_art/public/field/image/solar_panels700x425.jpg?itok=P4VrgCIH. I don't see this as an option in the view we have for our feed.

I think the Image URL Formatter module will help.

Image URL formatter module offers 3 options that are not contained by views:

support Image styles
support multivalues, there is a "Multiple field settings" when image field is multivalue.


taxonomy with image field is not translating I have a taxonomy term with an image field in it.

The problem is when I try to translate the taxonomy term and choose an image, the term is not translated and the language is set back to Language Neutral on save action.

Here is the message who came up when I hit the save button

Created new term testtttttt.
You are not authorized to access this page.

It's only happened when I fill the Image field, otherwise the taxonomy is translated correctly.

It's seem to be a new bug in drupal
https://www.drupal.org/node/2227181

Thanks

I tried wolverine's answer but it didn't worked for me, it caused error "#build_id not defined" so I changed it a little, I don't know if it's right solution but it worked for me.

Add only this code in your module:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'taxonomy_form_term') && (!isset($form_state['triggering_element']) || $form_state['triggering_element']['#id'] != 'edit-delete')) {
        if (!isset($form_state['storage']['rebuilding'])) {
            $form_state['storage']['rebuilding'] = TRUE;

        } else {
            $form_state['no_cache'] = TRUE;
        }
    }
}

Hope it's helpful for someone.


ob_start(), ob_get_contents()  do not work in preprocess functions? I tried to catch some HTML output in preprocess function with ob_start() and ob_get_contents(), but the output seems to slip through them. Is output_buffering maybe disabled in Drupal?

This is the pseudo code from mytheme_preprocess_page():

ob_start(); ?>

    This is block

<?php $vars['my_block'] = ob_get_contents();

When I do this, I get the
 output directly and not dumped to $vars['my_block'], as one would expect. My guess is that output buffering is, for some reasons, disabled. I am wondering if that is the case and why.

I think nothing is left on buffer in Drupal. After evaluating each template the rendered output is preserved as value and passed to outer level template. In this scheme Drupal might be getting buffered content and clearing it across each template.

That is why you should look for variables in that scope.


hook_module_implements_alter() to put hook implementations into separate files - bad practice? In a number of modules I wrote, I use hook_module_implements_alter() to split up the *.module file, and to move hook implementations into separate files.

The main reason is that I passionately hate long files. (and yes, this does make me unhappy about a lot of the files in Drupal 7 and contrib)

Examples:

nestedbox_core_module_implements_alter()
xautoload_module_implements_alter()

I know there are a few things to consider:

It might not work for all hooks. E.g. boot or install, or hooks that are not called via module_implements().
It is important to include the respective file from within the hook_module_implements_alter() implementation, due to the way that module_implements() works.

Now I heard from a long-time and well-known Drupal developer that this practice is problematic. https://drupal.org/node/2230319 (topic starter, and comments #5 and #11).

Before I start moving functions around, I would like to hear from others whether and why this is bad, both technically and aesthetically.

EDIT:
I guess this could be split in two questions:

Is it good or bad to split up your *.module file, so that hook implementations live elsewhere?
Is hook_module_implements_alter() reliable enough, or should I rather use include_once __DIR__ . '/MYMODULE.filename.inc' directly in the *.module file? What could possibly go wrong by using hook_module_implements_alter() for this?

I just found the piece of information that was missing.
EDIT: And another one.

Problem with module_invoke()

module_invoke_all() always calls module_implements(), which checks the module include file by checking both hook_hook_info() and hook_module_implements_alter().

However, module_invoke() only checks hook_hook_info() and not hook_module_implements_alter().

module_invoke() is called e.g. in _block_render_blocks() for hook_block_view().
This means that hook_module_implements_alter() is not a good solution to split a hook_block_view() implementation into a separate file.

This has been a problem in Crumbs, see https://www.drupal.org/node/2328535.

For other hooks it generally works ok, but you never know if a specific module wants to use module_invoke() instead of module_invoke_all().

module_implements() cache polluted in bootstrap.

Another problem is caused by a core issue reported here:
module_implements_cache() can be polluted by hook_boot() implementations calling module_invoke_all() directly or indirectly

This applies only to non-boot modules, where it can happen that the implementation of hook_module_implements_alter() is never discovered.

An unexpected chain of events causes module_implements($hook) being called from hook_boot().
The $hook can be any random hook, it does not need to be related to the module we are working on.
This causes module_implements('module_implements_alter') to be called.
Drupal looks for all implementations of hook_module_implements_alter().
At this time, MODULENAME.module is not included yet.
Therefore, for the rest of the request, Drupal assumes that the implementation MODULENAME_module_implements_alter() does not exist.
Later in the request, implementations of other hooks are being discovered, but the implementations by MODULENAME are not being found, because MODULENAME_module_implements_alter() is not being executed.

Alternatives

require_once

Alternatives have already been mentioned. Instead of these tricks, one can include the file directly. There may be a tiny performance impact but this is probably overshadowed by a lot of other things in Drupal.

But, instead of using module_load_include(), I would suggest a more direct solution:

require_once __DIR__ . '/crumbs.block.inc';

Or to be PHP 5.2 compatible:

require_once dirname(__FILE__) . '/crumbs.block.inc';

Why not module_load_include()?

There is generally no need to call module_load_include(), it could even be detrimental, if the *.module file is included from you-dont-know-where (e.g. from settings.php), and you don't know if module_load_include() is available.

This function is mostly there to help you determine the location of other modules. But if you are including within the same module, it is generally safer and easier and faster to work with relative file paths and explicit require_once.

Call to helper function

As mentioned by Jimajamma, you can also implement the hook in the main *.module file, and then include another file and call a helper function from there. This is done e.g. in Display suite.

This solution is ok, although I think it still clutters the main file, and gives you even more places to look.

And here likewise you can use require_once instead of module_load_include(), if it is within the same module.


WYSIWYG tinymce editor unwanted tags showing in drupal 7 I have css define set and themes/garland  in the input for the directory but when I go to test all tags are showing.

Do I need to deselect an option in buttons to stop this or is it something else?

Sounds like a text format settings issue, review the formats at

Admin > Config > Content authoring > Text Formats

e.g Filtered HTML > Limit allowed HTML tags

and add the allowed tags if necessary.


How to set required POST parameters for routes With GET method we can do something like this

example.user
  path: 'example/{user}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'
    user: ^[a-zA-Z0-9_]+

so it sets user param as required and also limits its format.

But I'd like to do something similar with POST method. Tried this, but not working:

example.user
  path: 'example'
  methods:  [POST]
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'
    user: ^[a-zA-Z0-9_]+

EDIT:

Sure I can set some logic inside controller like this, but it doesn't feel right:

public function store(Request $request) {
   $params = json_decode($request->getContent(), TRUE);
   //I'm trying to avoid using these conditions inside controller methods
   if(empty($params['user'])){
      //return error response
   }else{
     if (!preg_match('/^[a-zA-Z0-9_]+/', $params['user'])) {
       //return error response
     }
   }
  //return success response
}

So what's drupal way to do it?

I did something like this before ( take a look at helper link ),it  not required to tell router about type

just post your data and in your controller  get them with

$value = \Drupal::request()->request->get('your_posted_variable');

Also you can get all $_POST variables with

  \Drupal::request()->request->all(); // equal to $_POST


How to name multi-sites for different environments (dev and staging)? I have a Drupal project that is a multi-site setup. I currently have my sites named like so:

sites/site1.example.dev
sites/site2.example.dev
sites/site3.example.dev

This is fine for working locally in development, as I can point my browser to site1.example.dev, site2.example.dev, or site3.example.dev and it works. However, when I push this up to staging, I want to be able to access these sites at the following addresses:

site1.example.com
site2.example.com
site3.example.com

Is it possible to simply name these as "[specific_name].example" and configure it so that I don't need to rename/update depending on the environment?

Thanks.

I think you may be looking into aliases.

On your sites folder there should be a example.sites.php. It basically allows aliasing sites to different names.

You could create an if and based on some environment condition (maybe the output of hostname? or a file somewhere that contains prod vs dev), enable or disable the aliases.

More documentation:

https://api.drupal.org/api/drupal/sites!example.sites.php/8.2.x
https://api.drupal.org/api/drupal/sites!example.sites.php/7.x


How to use .schema.yml definition for two entities avoiding duplicated code What is the yml syntax in drupal .schema.yml files for specifying the same config for two entities? Something like this is what I need:
node.type.*.third_party.my_module:
media.type.*.third_party.my_module:
  type: mapping
  label: 'My Module'
  mapping:
    lots more lines here ...
    which I do not want to duplicate ...

I want the same settings for both node.type.* and media.type.* and there should be a way to avoid repeating all the definition and just having those two rows at the top.

Solution
Here is a very good way to do this, with thanks to @sonfd for the link.
node.type.*.third_party.my_module: &third_party_settings_alias
  type: mapping
  label: 'My Module'
  mapping:
    lots more lines here ...
    which I do not want to duplicate ...

# Use saved alias to repeat the same settings for media.type
media.type.*.third_party.my_module:
  *third_party_settings_alias

That's all there is to it. All the settings for node.type are repeated for media.type


Why can't anonymous users vote more than once from different browsers/machines? I created a poll in a Drupal 8 site and I enabled anonymous voting too, but when opening the pool in different browsers/machines, the poll results appear and anonymous users cannot vote.
Please tell me where the issue is.

Seems like that was the issue because of same IP address. But in case of  local network with hundreds of machines, how will that be taken care of, is still a question.
Right resource: Does poll not allow multiple anonymous votes?


Drush install on Redhat 7 Errors PHP Installing drush is never the same on every linux system apparently. I'm on redhat 7 and and I just setup php 5.6 and installed composer, but I can't do a composer install on the fresh git repo of drush.

I'm getting the following error:

Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Your requirements could not be resolved to an installable set of packages.

      Problem 1
        - Installation request for d11wtq/boris v1.0.10 -> satisfiable by d11wtq/boris[v1.0.10].
        - d11wtq/boris v1.0.10 requires ext-posix * -> the requested PHP extension posix is missing from your system.
      Problem 2
        - Installation request for phpunit/phpunit 4.6.6 -> satisfiable by phpunit/phpunit[4.6.6].
        - phpunit/phpunit 4.6.6 requires ext-dom * -> the requested PHP extension dom is missing from your system.

It's complaining about phpunit not being installed. So I went ahead and installed it:

  PHPUnit 5.6.2 by Sebastian Bergmann and contributors.

And I still get the same error when doing a composer install.

Can someone please explain why this always happens? You try to install something and it complains something isn't installed. You install that thing, but it still complains. Or better yet, you install something and it complains that something isn't installed and you install that thing and it complains some other thing isn't installed. Wasn't these package managers suppose to solve these dependency issues?

The errors are pretty self-explanatory:

The requested PHP extension posix is missing from your system
The requested PHP extension dom is missing from your system

You need to install those extensions because packages that drush depends on in turn depend on them.


How should i code a column layout? I'm new to Drupal and I thought a lot about planing a column layout at my frontpage. In each column there is a teaser list of nodes. I have one row with 3 columns, the next with 2 columns... I can't upload the mockup, but I hope you imagine what I'm working on. The important thing is grouping the node lists to different columns.

So what should i use to code this? Blocks? Views? Something with panels? At the moment I'm a little bit confused about all these options...

Greetings

Given the brevity of your description, it is hard to say exactly. If you want to avoid custom coding and use contrib code (always a good thing to try first, in my option), I would consider the following.

Views Page
manager
List item

Panels.

There is a good tutorial on the above (free at the moment) from the good people at Lullabot. The presentation is actually done by Node One, and is one of the best I've seen.

http://drupalize.me/series/learning-page-manager


Users that can add other users in drupal 7 Scenario is as follows: admin adds users (coordinators). Coordinators should be able to add another type of users (editors) which can create content. What is the best solution to this scenario? I don't want any of the users assign roles to other users. Coordinator should be able to add only one, defined type of user.

There's a module for that: Administer Users by Role.

  This module allows site builders to set up fine-grained permissions for allowing users to edit and delete other users — more specific than Drupal Core's all-or-nothing 'administer users' permission. It also provides and enforces a 'create users' permission.

  To use this module:

  Create a role for the users who you'd like to be able to create/edit/delete other users
  Give that new role the 'administer users' permission and give it the desired Administer Users by Role permissions

I'm using it exactly for the same purpose you described.


Updating the CKeditor library in Drupal after Version 7.14? I will now quote from CKeditor project page at Drupal.org:

To use CKEditor in Drupal, you may need to download CKEditor (the library which this module relies on). This would not be necessary starting from version 7.x-1.14 (not released yet - 24 April, 2014), where the installation has been simplified and CKEditor from official CDN is available by default.

As you could see in the picture, my sites/all/modules/ckeditor/ckeditor folder is empty, i.e the folder where you put the library... So my question is, given that the library's folder is empty by default, is it even possible to update the JS library but not the module...? Is it even possible after version 7.x-1.14? Or should I wait to the coming Drupal module release? Thanks.

Yes.

Libraries should not be store in module directories for the reason that it makes it harder to update things.

Best practice is to install the Libraries API module and put the library in sites/all/libraries (or an equivalent libraries directory if you're using an install profile or something).

CKEditor and a lot of other modules integrate with the libraries API module.

The CDN option that is referred to in your quoted text is different though. In that case you don't need to have the CKEditor plugin anywhere in your website files.
Instead the module will use a copy of the library from the CDN.

It's possible there could be performance implications from not using a local version but I haven't actually tested that.


Using webform 4.x values in other fields/descriptions on multi-page webforms Is there a way to output values of other field values in a multi-page webform? Say I have a 3 page webform. First page is name, email, then address. How can I reference the name value in the last page of my webform? I tried [webform:val-name] and it doesnt work in the description field.

Or is there a way I can call it via javascript? Are these values stored somewhere?

Once you complete an specific field in one page, it can be used ONLY in the next page.
The variables are stored into ->

$form_state['input']['submitted']['your_field_machine_name']

One trick I did, I saved that submitted variable into a hidden input in the next page.


Will all Drupal 7 Ubercart 3 orders be deleted if I disable & uninstall all Ubercart related modules? I'm working on migrating a Ubercart site to Commerce and wanted to know if all Ubercart orders and tables will be deleted if I disable & uninstall all related modules. Since I don't need the old data, I don't mind it having it completely deleted.

If you uninstall them, then yes.

EDIT:

No, they will not. Good call, duckx (I shouldn't have assumed that the D7 version implemented hook_uninstall_schema()).


What is the difference between hook_field_attach_validate() and hook_field_validate()? I'm a bit confused as for the difference between these two hooks,  and which one I should use for custom  validation of attached fields in my code.

Is there a better way to define a custom validation for an attached field (I am attaching the field programatically if that helps)?

EDIT: Looking more into it, I don't really get all that much information in hook_field_attach_validate(). All I'm pretty much getting is the entity_type, entity object and an errors array.

Whereas with hook_field_validate(), I get the field I'm actually validating against, which, I'm assuming is where I need to put the bulk of my custom field validation logic. The only issue I'm having now is that I'm unable to find a function that will invoke this method for me. Should I manually invoke this function or is there an API function I can use in this instance?

hook_field_validate()
 Should be used to validate the form for your modules fields.

hook_field_attach_validate() works on field_attach_validate() which is more for back end validation.

  This function does not perform field widget validation on form
  submissions. It is intended to be called during API save operations.
  Use field_attach_form_validate() to validate form submissions.

Are the fields ones which your modules is creating, or are they fields from a third party module?

The #element_validate property may be what you need to validate another modules fields.


Views: filter by the highest (max) field value of all items In this case, ‘Volume’ is a text field of type integer. Using the Views module, I want to display only those articles which have the highest value in the volume field.

I am able to do it using contextual filter but I have to provide a default value like 6. Please see the attached screenshot.

Is there any way in views, to detect the highest value of the field and use that as a filter?

I fear you will need a subquery for that. You can do that in a custom module.

/**
 * Implements hook_views_query_alter().
 */
function MODULE_NAME_views_query_alter(&$view, &$query) {
  $max = db_query('select max(YOUR_TABLE_COLUMN) from YOUR_TABLE')->fetchField();
  $query->add_where(0, db_and()->condition('TABLE.YOUR_FIELD_NAME', $max));
}

The tricky part here is to create your select query and find the correct field name/alias. Have a look at the query output of your view to find the correct parts.

Original answer (before clarification)

Instead of a contextual filter you can use a sort on the 'Volume' field. Sort descending. That way the articles with the highest 'volume' are at the top.

If you want to show only articles with a number higher than X you could add a regular filter for that.


How to migrate from DotnetNuke to Drupal? Currently we have DotNetNuke (= DNN) websites. We are planning to move the DNN websites into the Drupal platform.

My questions: how do I migrate the DNN content and users tables into the Drupal Mysql tables?

I have tried with Drupal Migrating Handbooks, but no luck.

There is a very good module to assist migration from other CMSs to Drupal called the Migrate module.

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

Link : Documentation.


Do we require a token module for token_replace() to work? I am creating a custom token using token_replace() and then adding hook_tokens_info() and hook_tokens in .tokens.inc file.
Will this function work without token module
?
I mean do we need token module for this function

You don't need the Token module to use the functions you mentioned in your question. They are defined in Drupal core.

References:

token_replace()
hook_token_info()
hook_tokens


how to show a panel node only to authenticated users? i am using panel nodes to display profile pages such as my profile page on facebook . i have created a menu link for it . When i logout my profile link still shows. I want that only the logged in user should see the my profile link.

I think that Content Access module should help You because it gives You ability to grant access to content type (panel) or - after select "Enable per content node access control settings " option - to single node.


How to override VBO redirect after performed action? My problem is that I can't override the URL where VBO redirects me to after I performed a default action. When I write my own actions I simply put $_GET['destination'] = 'my/target'; inside my custom form submit and that works. I tried to alter VBO's form submit to attach my own submit but that doesn't work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_bulk_operations_form') {
    array_push($form['#submit'], 'MYMODULE_vbo_redirect');
  };
}

function MYMODULE_vbo_redirect() {
  $_GET['destination'] = 'my/target';
}

When I testhack the VBO module and inside views_bulk_operations_form_submit($form, &$form_state) replace the final redirect with my custom one, it works. How can I get inside there and get my custom redirect executed without hacking?

I tried to alter the wrong form. VBO somehow merges its form stuff with the views form itself. So I had to look there to attach my custom submit. Then I had to pay attention to attach it in the same moment the views_bulk_operations_form_submit is attached. Then I set the cancel button to also bring me back where I want. And finally set $form_state['redirect'] in my attached submit.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}

Only problem left is that this redirect always gets triggered when performing any VBO action from this view. But I can live with that for now.


Programmatically do something when a node is updated I want to do something when a node gets updated. To keep it simple, lets say display a drupal message.
hello_world.routing.yml
hello_world:
    path: /node/{node}
    defaults:
        _controller: Drupal\hello_world\Controller\HelloWorldController::hello_world_entity_update
    requirements:
        _permission: 'access content'

Not sure if the path should be /node/{node}/edit instead.
HelloWorldController.php
<?php
/**
 * @file
 * Contains \Drupal\hello_world\Controller\HelloController.
 */

namespace Drupal\hello_world\Controller;

use Drupal\Core\Controller\ControllerBase;

class HelloWorldController extends ControllerBase {

  public function hello_world_entity_update(Drupal\Core\Entity\EntityInterface $entity) {

    drupal_set_message(t('Something @var just happened.', array('@var' => 'cool')));

  }
}

Since hook_node_update() was depreciated, I assume we now have to use hook_entity_update().
I am not getting the message upon updating a node, what I'm I missing or doing wrong?

Update

Just so I don't confuse anyone.
I was brainwashed into thinking I needed a routing file and a
controller. All the D8 examples out there use them.
Since I was not creating any pages,
turns out I did not need a routing.yml file nor a Controller.php file
nor the /src folder. All I had to do is approach this like Drupal 7,
all that I needed was the .info.yml file and a .module file
to put the hook.

Hooks are still implemented as global, procedural functions; you need to declare them in the .module file just like Drupal 7, not in a controller class:

function MYMODULE_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // ...
}

The system will move to OO in Drupal 9.

It's also worth noting that hook_ENTITY_TYPE_update() also exists, so you can still use hook_node_update():

function MYMODULE_node_update(Drupal\node\NodeInterface $node) {
  // ...
}


Can trusted host settings use an IP address? I'm working with a test site installed on a server on my network. Since it's only a sandbox, it has no domain name. Drupal being installed in a sub-directory (there are several sandboxes), I access it through an address like this: http://10.156.222.145/d8

However, when I put this in the trusted host patterns, like so:

$settings['trusted_host_patterns'] = array(
    '^10\.156\.222\.145\/d8$',
    '^localhost$'
  );

I get the error message: "The provided host name is not valid for this server."

Question: is it even possible to configure these settings with an IP address, and if so how?

Yes using an IP is fine, you just need to make sure you're using a valid host name (I.e. one without the path appended):

^10\.156\.222\.145$


Storage of the images in Drupal-Commons 6.25: serious troubles acompanied with CHMOD & CHOWN-issues Where do the image files reside? I have problems with the files, and the permissions. On my site, which runs Drupal-Commons, I cannot upload any image, either to a user or a group.

I was not able to fix it. First of all, regarding the user, my server works with the SETGID-bit enabled, and with the user vhost:vhost.
The bad is that every time I touch the chmod, I lose the setgit-bit; I tried changing it to 2777, and then all gets lost. I lose the style too.

What can I do? Can I upload the images manually, and store them into /home/vhost/WWW/schulcenter.org/sites/default/files?

setuid and setgid are for execution and not access control.

I can't comment on your exact problem, but when I move a site, I do

sudo find /path/to/site/default/files -type d -exec chmod 755 {} \;
sudo find /path/to/site/default/files -type f -exec chmod 644 {} \;
sudo find /path/to/private -type d -exec chmod 755 {} \;
sudo find /path/to/private -type f -exec chmod 644 {} \;
sudo chown -R apache.apache /path/to/docroot/site/default/files
sudo chown -R apache.apache /path/to/private

By default, files are in site/default/files but this location can vary for a few reasons

Admin setting for public files
Admin setting for private files
Whether the files use public or private
Whether you use the default location, or a site alias

and probably some others I can't think of.  I suspect that your write errors will show up in your Apache error_log and you should also see what the status report (admin/reports/status) says.

Note that the private paths/settings are for Drupal 7 only, but the rest applies.


How to create a PHP file that returns a list of nodes as XML? How do I create a PHP file that returns a list of nodes as XML when called if I have a menu structure like this:

<GalleryXML>
--gallery 1
---Item 1
---Item 2
---Item 3

And I want a url like localhost/getgallery.php

this url will then return my gallery as xml, something like this

<galleryXML>
    <gallery name="gallery1">
        <item name="item1">
            <image>localhost/site/default/image1</image>
            <imagethumb>localhost/site/default/image1</imagethumb>
            <url>http://google.com</url>
            <description>lorum ipsom</description>
        </item>
    </gallery>
</galleryXML>

Where Image, Imagethumb, url and description are fields on the item node

Thanks in Advance!

This is what i did:

I created a view.
Changed the style to XML data document (Need to download the Views Datasource module)
Added the fields I needed and Nodequeue
Added a filter to filter by node type so it looks like this:

then I added a new page with a path:

my end result looks like this:

 <node>
    <node>
        <Description>blablalbla</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>derp</Link>
        <gallery>Gallery1 For flash</gallery>
    </node>
    <node>
        <Description>sdfsdfdf</Description>
        <Image>
        sites/default/files/articles/siteadmin/test.png
        </Image>
        <ImageBig>sites/default/files/test.png</ImageBig>
        <Link>sdfdf</Link>
        <gallery>Gallery2 For flash</gallery>
    </node>
</node>


How to execute a script that takes a long time? I am executing a script by calling a URL using the wget command. I want to execute this script 3 times a day for 2 hours each time. To do so, I check the difference between the start time and the current time.

My problem is that sometimes the script runs for 2 hours, sometime 1 hour, and sometimes just 3 minutes. I don't know why. I have increased memory_limit and max_execution_time. Still, I haven't been able to find the reason.

What my script is doing exactly:

It fetches a data from other site using cUrl. The data are articles, journals and some other user's data.
After getting the data in XML format, it adds each content.

You can break up your work somehow. You shouldn't try to process thousands of things at a time and assume nothing will break or you'll run out of time.

I have recently wrote an in-house Drupal 7 project that allows me to query a webservice for XML data very quickly and process 100,000s of XML entries to an SQL DB pretty fast. A full fetch of all remote SOAP based data is ~100,000 SQL rows after import. This takes ~5 mins to complete. From CURL to DB insert.

The Drupal 7 site performs the following:

Allows me to fetch a .NET SOAP response for X departments from my university. X any number of department queries from 1 department to 90 departments per school quarter.

I used the Background Process module to fetch the CURL requests to local XML files in a Drupal private filesystem.
90 CURL requests with ~2Mb XML responses complete in ~1 minute. (I could request 1 huge xml file of all departments; I break it up for many threads below).
The XML files are added to a Drupal queue. Queue's can lease queue items as jobs for processing. A developer can set a lease time per job for any length of time.

I then use hook_cron_queue to define a worker function that parses the XML and inserts the data into a database. This happens to be a non-Drupal database that I connect to via a custom db entry in settings.php.

I use the Ultimate Cron and Ultimate Cron Queue Scaler modules to actually perform the processing. I set 9 threads in Ultimate Cron Queue to process queue items, and I have set my lease time to literally 2 hours (7600 seconds). Drupal cron runs/checks for work every minute, the lease time assures no thread tramples over work already in progress.

with no optimizations a script I'd written using PHP DomDocument with Xpath queries inserting SQL queries to a DB took minutes per XML file. After adding some SQL batch inserts with db_insert each file takes seconds, but I know from progressively optimizing my scripts a job can have a set lease time. Which is what you want here.

In short. Find a way to break-up your workload and dont be afraid to use watchdog log messages in your module code. A Queue is a nice way to store pieces of the whole task to complete in tiny parts. As you run your worker functions you'll be able to find a lease time that works best for your data size and processing times.

I realized your post is about Drupal 6; it doesn't really matter. The core pieces you want are the D6 queue project and hook_cron(). The Ultimate Cron, Ultimate Cron Queue Scaler, and the Background Process modules have D6 versions.

The project described is a private in-house project, and I cannot easily provide code examples. I've tried to outline how to glue this all together.


can't programatically update line item on drupal commerce order I want 'sell' a donation for custom donation amounts, and I know that to do this, I will need to use line items. I wrote the following code which I thought would do the trick, but when I go to /cart, I see that the price has remained the same.

global $user;
  if(user_is_logged_in()) {
    //$order_id = commerce_cart_order_id($user->uid);
    //$order = commerce_order_load($order_id);
    $order = commerce_cart_order_load($user->uid);
  }
  else {
    $order = commerce_cart_order_load();  //no uid since user is not logged in. attempts to load an anonymous order from the session.
  }
  //var_dump($form_state['values']['donation-custom-amount']);
  $lineItem = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  if($form_state['values']['donation-custom-amount'] !== "") {  //if the user entered a custom amount
    $lineItem->commerce_unit_price['und'][0]['amount'] = $form_state['values']['donation-custom-amount'];
    $lineItem->commerce_total_price['und'][0]['amount'] = $form_state['values']['donation-custom-amount'];
  }
  else {
    $lineItem->commerce_unit_price['und'][0]['amount'] = $form_state['values']['donation-amount'];
  }
  commerce_line_item_save($lineItem);

I checked that $form_state['values'] was giving me the form data, and there are no errors, just no price change.

Recently I've updated some other line item fields on commerce_add_to_cart_submit() via this code:

$line_item = commerce_line_item_load($lit_id);
$line_item->field_product_options[LANGUAGE_NONE][0]['value'] = $size;
commerce_line_item_save($line_item);
entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));

I hope this will help someone.


How to display parent term name of a term located in a paragraph? I have a vocabulary for employees, which has a paragraph field. In this paragraph entity, I have two fields. One for date and one for the job title. The hierarchy goes like: company > department > job title. I've created a view where I list all employees and what I want to accomplish is not to show what their job title is. I want to display in which department they work.

Any help is appreciated.

1st you have to make relation with the field who reference to taxonomies after that youhave  to make another relation with your paragraph field to get the job title


D7 Commerce - Save rules applied to line items in cart? I want my users to be able to redeem points for discounts off of their orders. Every dollar is worth 20 points. I've managed to work the entire equation in Rules to line items, however none of the rules I put into place save. Here is what I have so far:

As soon as I leave my cart, the value changes from the discounted value I've set, back to 0.00. For some reason, the updated unit price will not save (even though I've set it to?) Am I missing something? Apologies for crazy rule, but it's the only way I could get it done.

Update: I've learned that Cart Refresh is the reason rules applied to line items in cart don't save. How can I make these rules stick?!

I don't think there is. You will have to:

Add a Discount /admin/commerce/discounts, which will generate a discount rule. /admin/config/workflow/rules?event=0&tag=Commerce%20Discount
Edit the discount Rule and do your magic here.
Create a Coupon /admin/commerce/coupons and link it to your Discount in the "Discount Reference" field.


How can I print the vocabulary name instead of the referenced term in a node template? Let's say I have a content type article with a field "taxonomy".

The vocabulary is "fruits".

The terms are "apple", "orange", "bananas"

The article belongs to "orange".

I can easily print in my twig template the term of the article :

{{ content.field_taxo_fruit }}

Result is "orange".

But I don't find an easy way to print the vocabulary : "fruits".

On an other project, I used views field and I used "rewrite result". But here, I use twig template like node--article--teaser.html.twig

The vocabulary machine name is the bundle ID of the term, which you can get through the node object:

{{ node.field_taxo.entity.bundle }}

To load the label of the vocabulary:

{{ node.field_taxo.entity.vid.entity.label }}

This works only when the field has content. For an empty field you would have to dig into the field definition you get from the same field object and check whether the field is restricted to a single target bundle.


Viewing Referenced Field Images in node template I'm stuck with a probably simple problem, maybe someone can help?

I have a node (representing a route) which has a reference to other nodes (points of interestes)
Like this node.field_poi

Every field_poi has it's own images attached

from the node template I'm trying to get the images, but no way!

There are my attempts, where am I wrong?

{{content.field_poi.0.entity.field_image.0.entity.uri.value}}
{{kint(node.field_poi.0.entity.field_image.0.entity.uri.value)}}

If I try this, it breaks completely the page:
{{kint(node.field_poi.0.entity)}}

Thanks to the slack channel #drupaltwig, I found a solution!
I leave it here, in case somebody else needs it

{% for curr_poi in node.field_poi %}

{% if curr_poi.entity.field_image.entity.uri.value is not empty %}

<img class="product-image" src="{{curr_poi.entity.field_image.entity.uri.value | image_style('app_list')}}" />

{{curr_poi.entity.title.value}}

{% endif %}

{% endfor %}

Main hints:

use node instead of content
iterator is curr_poi do not use a index
I used twig_tweak drupal module in order to user the filter | image_style('app_list')

Thanks to @kekkis @markconroy


Field remember settings Let's say we have a content with these fields:

Title
Category
Price
Mobile
Skype
City
E-mail

A checkbox for "Remember my settings" that will remember these fields:

Mobile
Skype
City
E-mail

When user is registered in profile edit will have an option to change (I guess this will be able to achieve with Profile2):

Mobile
Skype
City
E-mail

After changing these details, the next new content form will have a checkbox for "Use my settings" to use the settings from the profile form details. Is it possible to do this with a module or hook in Drupal 7?

I'm not asking for someone to explain me the details (even it's very welcomed), but I'm asking if it's possible, what module or hook should I use? I hope this doesn't sounds too broad.

I think you are looking for Remember values

  This module enables Drupal to remember entered values from selected
  fields upon new node submission, stores them in the database and then
  pre-fills appropriate fields on the next node-add form. This is useful
  when a user needs to enter many nodes at a time and some of the
  fields' values are repeating.


Drupal 7 has lost all "safe" values and summaries I suddenly noticed that safe_value and safe_summary are empty now. Regular value is filled with data, but safe values are not. They were working just fine some time ago. I am currently trying hard to find what caused this havoc.

This applies to all nodes and comments. Haven't checked other content types yet.

Thanks!

I found out that the problem was caused by Facebook album fetcher module and its text format filter.


Rules loop through list and create nodes with custom title I'm using rules to create new nodes on 'After saving content of type' event.

To do so I loop through a list of type entity reference

Loop
Parameter: List: [node:field-childs]
List item: Current list item (list_item)

Inside the loop I  Create a new entity,

Create a new entity
Parameter: Entity type: Node, Content type: Attendance, Title:
[node:field_childs], Author: [node:author]
Provides variables: CreateAttendancePage (basic_attendance_created)

Then I save the entity

Save entity
Parameter: Entity: [node], Force saving immediately: true

This will title all the new nodes with all the field_childs values available instead of taking them one by one.

I end up with titles like:

First node: Timmy, Jack, Jimmy, Sam, Hannah

Second node: Timmy, Jack, Jimmy, Sam, Hannah
etc.

Instead of:

First node: Timmy

Second node: Jack

I've figured it out by myself.

Inside the loop when you create a node the pattern used for the title needs to be from the Replacement patterns for Current list item section and in my case, it was the [list-item:title] (the title of the current referenced entity in the loop).