How do I show a message about the currently executed operation? I have created a batch, and it's working, but I want to control the messaging a little better. I would like to give the user some feedback about the currently executing operation, other than just letting them know that it has completed.

Here is what I am attempting to do, but it is still executing sleep(5) before updating the message.

function batch_callback(&$context) {

  // set up message for batch operation
  if (empty($context['sandbox'])) {

    $context['message']  = t('Pre-execution message...');
    $context['finished'] = FALSE;

    // put something in sandbox (doesn't matter what)
    $context['sandbox']['step'] = 1;

    return;
  }

  sleep(5);

  $context['finished'] = TRUE;
}

So, how do I set a pre-execution batch message?

The message will be shown just when the batch callback returns. If your intent is pausing the batch operations to let users see the pre-execution message, I would rather use the following code.

function batch_callback(&$context) {
  if (empty($context['sandbox'])) {
    $context['message']  = t('Pre-execution message...');
    $context['finished'] = FALSE;
    $context['sandbox']['step'] = 1;

    return;
  }
  elseif ($context['sandbox']['step'] == 1) {
    sleep(5);
  }
  // Do your operations.
}

You could also set the progress message using $batch_definition['progress_message'] (where $batch_definition is the value passed to batch_set(), but that just gets @current, @remaining, @total, @percentage, @estimate and @elapsed as placeholders. You could not use it to show, for example, the title of the node being processed, since it doesn't allow to use a custom placeholder. It is used more for messages like Completed @current of @total.


Filtering list of nodes with attached views by taxonomy of node I have a single article (page) which has an attached view thats displays a load of nodes (in a content called 'courses').

These nodes have a term reference field called 'language' which assigns them to a specific language the course is taught in.

Each of these nodes have an attached view which lists a load of related nodes (in this case 'products'), and these are also assigned with the same taxonomy called 'language'.

What i am attempting to do is to list these nodes, with the attached view filtered by the same taxonomy 'language'.

I've attempted to set up the view using contextual filters with the notion of getting the parent nodes id (When filter is not available use taxonomy term id from URL) but this only gets me the id of the top level node. What i'm looking to get is to pass the language tid from each course to its attached view.

I've used hook_views_query_alter to add on the join table for the languages table which i'd like to then fill with the tid from the passed taxonomy term to do the filtering.

Anyone done such a thing? seems pretty straightforward as it feels like i'm doing something in the wrong order (ie its rendering the view before attaching to the node).

I would pursue the hook_views_query_alter() way, and using arg(1) and node_load() to load the node you are viewing and get the 'language' value from the node field. Add that value as a filter for your view programmatically.

Is this enough for you to continue on your own?


How to add an SQL expression to the entity query? (D8) Assume we have an entity query like the following:

$query = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->getQuery();
$tids = $query->condition('vid', 'tags')->execute();

and we need to add some SQL expression and condition based on it, like the following:

Replace(name, ' ', '-') = 'some-tag'

How to do that?

The Drupal\Core\Entity\Query\Sql\Query class does not have methods for doing so (unlike Drupal\Core\Database\Query\Select).

Using query tags and metadata the underlying Select query can be altered easily.

$query = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term')->getQuery();

// Add tag and any metadata to the entity query.
$query->addTag('my_category')
  ->addMetaData('my_category', $dynamic_category_name);

$tids = $query->condition('vid', 'tags')->execute();

And then in my_module.module file:

/**
 * Implements hook_query_TAG_alter() for my_category tag.
 */
function my_module_query_my_category_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $expression = "Replace(taxonomy_term_field_data.name, ' ', '-')";
  $args = [
    ':dynamic_category_name' => $query->getMetaData('my_category'),
  ];

  $query->addExpression($expression);
  $query->where($expression . ' = :dynamic_category_name', $args);
}


What is percent sign in the arguments? The percent sign is something I once saw in Drupal 6 and Drupal 7, but not  Drupal 8. It has been a few years ago; I don't recall where exactly inside a view, but most probably inside the contextual filter criteria.
What is percent sign in the arguments?

The percent sign in view arguments is to tell Drupal to expect a contextual filter within the view path. It is specific to Drupal 6 and 7, linux doesn't matter.

Drupal 8 uses curly braces to accomplish this instead.

From https://www.drupal.org/node/1578576, the example provided is that user/%/comments would provide a contextual filter to show the comments for the specific user.

This resource gives screenshots and examples about how to create a contextual view filter:
https://www.drupal.org/node/1578564


How can I add CSS or JavaScript files? I want to add two files, CSS and JavaScript, to be used in a Drupal site,  without linking them to the used theme. I can add these with Bash.
touch /var/www/html/example.com/{css.css,js.js}
chmod 644 /var/www/html/example.com/{css.css,js.js}

I need to include both files.
Sometimes I create small sites without modifying the theme at all, but I still need some minor CSS/JavaScript changes that don't justify creating a sub-theme. I wouldn't mind creating two "quick" and "global" files directly on the Drupal directory just for that.
Can this be done in Drupal 8.5.6?

Add a module, give it a libraries file (MODULE.libraries.yml):

global:
  js:
    /js.js: {}
  css:
    theme:
      /css.css: {}

In the .module file, implement hook_page_attachments:

function MODULE_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'MODULE/global';
}

When you enable the module (or clear cache if it's an existing module), the CSS and JS will be included on every page.


TinyMCE doesn't affect on nodes I've installed TinyMCE editor but when I change font style or anything else, I don't see any change in the published node. what should I do?

Check to ensure the content has full HTML input filter, it may be that even though the source includes the customised html inserted by TinyMCE upon save it is all being stripped out.


One time db scrub with .install file I need to scrub a production db to replace paths in the body field. Being a production database, it needs to happen in a time-sensitive, well-documented way with the solution frozen in code. I'd assume that a .install file would be the best way to do this.

What would a one time install script look like to search the database for "http://mysite.com" and replace with "https://www.mysite.com" in the default body field?

I typically do things like this outside of modules, and instead use a drush script.

The script itself, would go something like

Go into maintenance mode
Do an EntityFieldQuery to get my nids.
Loop through each nid, and
Load the node, and make an entity metadata wrapper
Do the search and replace on the fields
Save the node
Exit maintenance mode

Before and after running the script, I usually do a drush sql-dump.  You can even combine all of this into a single script

#!/bin/bash

drush variable-set -y --always-set maintenance_mode 1
drush sql-dump --result-file=~/db/before.sql
drush scr path/to/my/script.php
drush sql-dump --result-file=~/db/after.sql
drush variable-delete -y --exact maintenance_mode

By doing a drush script, you can really ensure that the task runs when you want it to, and you aren't bound by execution time limits.  I also find it easier to debug.

That said, you should just be able to use Pathologic to rewrite the URLs.  Install/enable it, and add it to your text formats, and configure to do the path fixups.


Calculate field value based on another field value with Rules I am using Drupal 7 and Commerce.

I have Product display where is custom field called Stock (field_stock). This field holds stock value (integer) for Product.

In Product display I have Product Variations. Variations has custom field called Stock Value (field_stock_value).

When adding new Product display and setting field Stock to value 10. And then adding first Variation and setting field Stock Value to 6. And to second Variation field Stock Value to 4.

I need to have rules which decreases Stock field from Product display. So it is simple: take value from Stock Value field and reduce that amount from Stock field.

But I have not succeeded to make working rules for that. Any help needed. Thanks!

Try Computed Field

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of CCK fields. So start cooking up your PHP based values!

Check Conditional Fields too

  Define dependencies between fields based on their states and values.


How to hook_views_query_alter arbitrary field and use it in view GUI For the life of me I can't figure this out.

I have vast and complicated drupal 7 site and among other things I'm using profile2 module. Not sure why, but a few years back I've added field directly to 'profile' table. It is used to store some number and adding it looked like quick fix back then.

Now I need to get some info using views and all is fine except this one field which I absolutely have to take into account, but I am not able to.

What I did so far is:

function modulename_views_api(){
    return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'modulename'),
  );
}

in my custom module,

function modulename_views_query_alter(&$view, &$query){
    if ($view->name == 'viewname') {
        $query->add_field(NULL, 'some_field', array());
    }
}

in modulename.views.inc

What I'm trying to do is either add this field to display directly, or add it to the list of fields, or replacement patterns, or anything I could use.

modulename_views_data() isn't useful for me, because I would have to recreate whole table structure created (and frequently changed) in GUI.

I tried _views_pre_view, _views_pre_render, relationships, query rewrites, all to no avail. I've run out of ideas...

You could add a normal number field to the user profile in the drupal ui, then translate the rogue column into this normal drupal field by populating the field from the table column with an SQL query (or several queries via a looped php script) on your database.

This would mean that the field would become available in the normal drupal way within views, and would also avoid you having these sorts of issues on another occasion.

I am sure it does not need to be said, but obviously you would backup first and perform this operation in a local development to test.

Note: It should even be possible to export the numeric value against uid and use feeds to bring the value into a profile2 field using the uid as unique, if that felt more comfortable than the naked sql population.


Copy contents from an field entity reference I have 2 content type

1-Parent Product
Title
Fabric Type
Product Type
Product Description

2-Child Product
ParentProduct (Node Reference to Parent Product Content Type)
Title
Fabric Type
Product Type
Product Description
Product Code
Product Size
Product Color

Here is the use case.
1-I Create all my Parent Product

2-I Create a child
The first field I need to filled is ParentProduct (Node Reference)
By choosing the ParentProduct, I would like  this parent act as the default value for Title, Fabric Type, Product Type and Product description of this child.

Is there any module that could help me for that?

Thanks a lot

Using Entityreference prepopulate and Entityreference prepopulate token

Once installed, you will need to create a link for the Child on the Parent page's template that includes tokens for the fields you want prepopulated. The answer here shows how to string multiple values together.

If it needs use a Node Reference rather than an Entity Reference, then Node Reference URL Widget and Prepopluate will do approximately the same thing.


How to remove the comma between Link multi-value field I am using the Link module's link field. When I create a multi-valued field, it automatically adds a comma between them. I would like to remove this comma. For some other field types, such as term reference, I believe there is a way to set this in the UI, but I don't see this for the Link field.

My suggestion would be to modify the way the links are displaying using the Display Suite module's field templates. Field templates gives you a high level of control over all the ways Drupal outputs the fields.

I found this tutorial that is pretty in depth, but in short you want to add the Display Suite module, enable it and the "Display Suite Extras" module that comes with it.

Next go to the display suite settings and enable "Field Templates." This is under Structure > Display Suite > Extras.

Once those are enabled, find the display settings for your content type (Structure > Content Types > YOUR CONTENT TYPE > Manage Display.

On that page, in the vertical tabs at the bottom you'll see an option to set a layout. Select "One column" or "Reset". Selecting a basic layout here will enable the additional features Display Suite offers.

After your layout is set, you'll see many more options on each field for how it is displayed. You can set the field template to "Expert" and you'll get control of the wrappers, prefix and suffix content (i.e. comma or no comma), and a lot of other stuff.

I hope that points you in the correct direction. Play around with DS a bit and I think you'll really like the control it gives you.


Render a button in a block I want to display a button on the homepage. The best solution i've thought about was to render it in a block. The code is the following :

  $button['my_tickets'] =array(
    '#type'       => 'link',
    '#title'      => t('My tickets'),
    '#href' => '',
    '#class' => 'btn btn-default',
    '#id' => '',
    '#options' => array(
      'html' => true,
    )
  );

And here's the theme :

  function My_module_theme() {
    return array(
      'my_module_my_button' => array(
        'variables' => array('vars' => NULL),
        'template' => PATH_TO_TEMPLATE,
      ),
    );
  }

Problem : The link isn't rendered with the classes inside the "a" tag. How can I do that ?

I think the classes should be added in the attributes array:

 $button['my_tickets'] =array(
    '#type'       => 'link',
    '#title'      => t('My tickets'),
    '#href' => '',
    '#attributes' => array('class' => array('btn', 'btn-default')),
    '#id' => '',
    '#options' => array(
      'html' => true,
    )
  );


Url query - using a key with multiple values I am trying to build a url with a query using the url() function.

    $options = array(
        'query' => array(
                'parameter1' => 'value1',
                'parameter2' => 'value1,value2',
        ),
        'absolute' => TRUE,
        'external' => TRUE,
    );
    url ('https://somesite.com/', $options);

The URL becomes: https://somesite.com/?parameter1=value1&parameter2=value1%2Cvalue2

So commas become encoded as %2C.

How can I build a query that has parameters with multiple values separated by comma?

EDIT: I have to deal with an old API that does not recognize %2C as comma characters, so actual commas have to be present in the end url.

How can I build a query that has parameters with multiple values separated by comma?

You already have, the commas are just encoded so they can be transported safely as part of the URL.

If you mean how can you stop the url() function from encoding special characters: you can't, without editing it. More specifically, you would need to replace its use of drupal_http_build_query with something that only selectively encodes special characters, much like drupal_http_build_query does itself for the / character.

The other options you have are

Do a string replace on the return value from url (or parse it and build it up again to your own spec)
Roll your own url function to your own spec
Contact the maintainers of the API and ask them to fix their decoding bug. Obviously YMMV on that.


How do I debug connection problems while testing Deploy module while using local host? I'm attempting to properly set up between the Deploy Module between these two by follow these instructions. I've used Drush QuickDrupal to set up two new Drupal 7 instances.

$ drush qd d7-deploy-stage
$ drush qd d7-deploy-live

Initially, I ran them as on the same host machine via PHP's internal development server

$ php -S localhost:8000 # d7-deploy-stage
$ php -S localhost:9000 # d7-deploy-live

The end point is listed as http://localhost:9000/services/rest and the authentication (and only user) is admin with password of admin.

However upon a cron run on the d7-deploy-stage instance I

  DeployAuthenticationException: Authentication error:-111 Connection refused in DeployAuthenticatorSession->deploy()

Question(s): How would I begin to debug this? Since the error reads "connection refused", I'm also curious if I start the servers with a fully qualified domain name (or my machine's IP) or if the port numbers an issue in the addressing

What I've tried so far:

The Patch:
The '#31' has failed with the following output patch -p1 < deploy-404_CSRF_error-2017767-31.patch

  patching file plugins/DeployAuthenticatorSession.inc Hunk #1 FAILED at
  76. 1 out of 1 hunk FAILED -- saving rejects to file plugins/DeployAuthenticatorSession.inc.rej

Update

On both instances, based this answer below, I downloaded the 'add start up .ht.route' patch, applied and restarted

wget https://www.drupal.org/files/issues/add_a_startup-1543858-58.patch
patch < add_a_startup-1543858-58.patch to each instance.
php -S public-ip-number:8000 .ht.router.php # stage
php -S public-ip-number:9000 .ht.router.php # live

The error on drush cron has changed

  WD deploy: DeployAuthenticationException: Authentication error: 404 Not found : Could not find resource user. in DeployAuthenticatorSession deploy() (line 76 modules/deploy/plugins/DeployAuthenticatorSession.inc).

There are few issues with your examples.

You're missing routing-script for the built-in PHP web server. It's recommended to use since you're using PHP built-in web server and by default it may have some problems handling certain clean URLs (for example URI containing dots are treated as direct files). So you should apply this patch from #1543858 and re-run you server as below (same file you can use for both Drupal 7 & 8):

php -S localhost:8000 .ht.router.php

You should use -l in order to specify URI of the Drupal site to use, so your code knows what's your proper hostname (since the fail is related to the connectivity issue).

drush -v -l http://localhost:8000/ cron

If you still have Connection refused, you should check where the code is trying to connect and check the connection (e.g. wrong configuration or firewall in place). To debug the connectivity issue, on OS X you can use dtruss, on Linux this can be debugged by strace, e.g.

strace -e trace=network -fp $(pgrep -fn php)


How to organise children menu links as tabs in D7? I'm using Drupal 7 and now I have a regular dropdown menu like this:

Link 1

sub-link 1
sub-link 2

Link 2

But I would like to organize my sub-links as tabs where sub-link 1 and sub-link 2 would  be a content tabs that contain a block content. I tried to use OM Maximenu Modul, it helps to organise parent links as tabs but not sub-links. Could anybody help me in this question?

Instead of OM Maximenu module I used Views Menu module as it easier and I used it only with purpose to attach views block to only one menu link.


How to delete a form element via ajax? This is my custom form with working add more and dummy delete button.

function mymodule_mycustom_form($form, $form_state){
   $form['checkboxes_fieldset'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated textfield'),
    '#tree' => TRUE,
  );
  $form['checkboxes_fieldset']['number'] = array(
      '#type' => 'textfield',
      '#title' => 'number',
    );
  // dummy delete button
  $form['checkboxes_fieldset']['delete'] = array(
      '#type' => 'submit',
      '#value' => 'delete',
  );
  $form['add'] = array(
    '#value' => t('add more?'),
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'mymodule_add_callback',
      'wrapper' => 'checkboxes-div',
      'method' => 'append',
    ),
  );

  return $form;
}

This is ajax callback for add more button

function mymodule_add_callback($form, $form_state) {
  return $form['checkboxes_fieldset'];
}

Now i want a working delete. But dont know how?

Adding a value using that code won't actually work since you've only defined one textfield, and thus, only one value will be stored. All the new fields returned will have the same id/name as the first one so only one form value will be sent back to the server when the form is submitted.

You need to add an extra layer to the form structure to make each field instance unique, say by including an instance number in each id/name.
Something like $form['checkboxes_fieldset'][$i]['number'] where $i is increased by one for each field instance. That goes for all the elements inside the fieldset. You generate these fields in a loop, but before that you check how many instances of the field are already present in the form state so you know how many iterations are needed in the loop. For each iteration, you also check if the form was submitted and if the current field instance matches the name of the button used to submit the form. If so, you skip adding that field instance to the form (don't increment the instance counter this iteration to keep the total count synced).

The submit handlers for adding/removing fields simply set the 'rebuild' flag in the form state and return the fieldset to be updated (all instances get re-rendered each time).
Adding/deleting field instances then become an indirect action of rebuilding the form with the correct number of field instances.

The examples module on drupal.org has an "add more" AJAX example which is fairly similar to what you want, except that it always removes the last field instance.


admin/commerce/products/add page says "You have not created any product types yet" when I have Somehow, the Drupal Commerce page at admin/commerce/products/add is failing to recognise that I have product types and is giving this misleading error:

  You have not created any product types yet. Go to the product type creation page to add a new product type.

From reading this discussion and a look at the code here it looks like the Commerce module on this page bizarrely gets the list of product types from looking at the menus. There's a heap of "what worked for me was moving X to Y in the menus" but they all seem to be slightly different and match older menu naming conventions. This issue appears related but isn't. I have editted the Commerce menu and would like to keep my editted menu how it is.

How can I make sure that Commerce recognised my product types on this page? What has to be where for this page to recognise product types (or even better, is there a way to make it happen the normal way via entities instead of via menus?)

I've also tried bypassing my broken admin/commerce/products/add page completely with a redirect, but the redirect is ignored.

I've also tried moving my Products > Create Item auto-generated menu links back under Store in the Management menu, and creating new menu links to those pages under Store in the Management menu, but neither works.

Those admin pages are generally based on the menu, so I think it makes sense that the commerce module is using the menu to build it.

It doesn't have to be like that, though, you can change it up pretty easily:

function MYMODULE_menu_alter(&$items) {
  $items['admin/commerce/products/add']['page callback'] = 'MYMODULE_commerce_product_ui_add_page';
}

function MYMODULE_commerce_product_ui_add_page() {
  $types = commerce_product_types();

  if (count($types) == 1) {
    drupal_goto(_MYMODULE_commerce_product_admin_add_path(key($types)));
  }

  return theme('MYMODULE_product_add_list', array('types' => $types));
}

function _MYMODULE_commerce_product_admin_add_path($type) {
  // Method taken from commerce_product_ui_menu()
  return 'admin/commerce/products/add/' . strtr($type, array('_' => '-'));
}

function MYMODULE_theme() {
  return array(
    'MYMODULE_product_add_list' => array(
      'variables' => array('types' => array()),
    ),
  );
}

function theme_MYMODULE_product_add_list($variables) {
  // Build up an HTML list of links based on $variables['types'], similar to theme_product_add_list()
}


entityform submit handler with preview I have a simple Entity Form and have added a custom submit handler:

$form['actions']['submit']['#submit'] = array('custom_submit','entityform_edit_form_submit');

That works very well. The problem is when I enable form preview before submission. My custom_submit function runs before preview is generated and not after it was confirmed.

How do I get it to run after form has been confirmed in preview?

$form['#submit']  = array(
    'custom_submit',
    'entityform_edit_form_submit'
);

does not work at all.

So this is what I found entityform module does. If preview is enabled it set $form['review']. All of my forms will have that preview set so what I did is simply:

//check if form is in preview mode and if it is then it adds my custom handler.
if(isset($form['review'])) {
    $form['actions']['submit']['#submit'][] ='custom_submit'
}


Whats best practices for handling Drupal 8 core file paths for vendor package.json I use drupal-vm when setting up my dev environment and have heard that setting up Drupal core files in the document root is a security issue and should be set in a different way.

So I have set my composer.json to:

 "merge-plugin": {
        "include": [
            "docroot/core/composer.json"
        ],
        "recurse": false,
        "replace": false,
        "merge-extra": false
    },
    "installer-paths": {
        "docroot/core": ["type:drupal-core"],
        "docroot/modules/contrib/{$name}": ["type:drupal-module"],
        "docroot/profiles/contrib/{$name}": ["type:drupal-profile"],
        "docroot/themes/contrib/{$name}": ["type:drupal-theme"],
        "docroot/drush/contrib/{$name}": ["type:drupal-drush"],
        "docroot/modules/custom/{$name}": ["type:drupal-custom-module"],
        "docroot/themes/custom/{$name}": ["type:drupal-custom-theme"]
    }

I get issues with the autoload not being able to find the vendor/autoload:

Warning: require(/var/www/site/docroot/vendor/autoload.php): failed to open stream: No such file or directory in /var/www/site/docroot/autoload.php on line 14

Whats is the best practice for placement of Drupal 8 core files?

I think this is a slight misinterpretation of the security risk.

The core/ directory needs to be in your DOCROOT; it has assets that the webserver needs to serve up (JS, CSS, and images).

The vendor/ directory should (mostly) be outside of your DOCROOT; some packages have files that shouldn't really be accessed by the webserver directly and have been the focus of recent SAs.

The exception to this are dependencies that need to be served up or be in the proper place, hence why people use the installer-paths to place modules, themes, and JS libraries in the right place.

While not universal, I would say that drupal-composer/drupal-project is a growing best practice, at least for starting points for websites.  This will place vendor/ outside of DOCROOT, take care of the autoloader and scaffold files, and set up a sane set of installer-paths.  Even if I am not using this directly, I look to its composer.json for inspiration.


Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1 no such table: I'm getting a strange error with my Drupal site. The error is as follows:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1 no such table: router: SELECT name, route, fit FROM {router} WHERE pattern_outline IN ( :patterns__0 ) AND number_parts >= :count_parts; Array ( [:count_parts] => 0 [:patterns__0] => / ) in Drupal\Core\Routing\RouteProvider->getRoutesByPath() (line 344 of core/lib/Drupal/Core/Routing/RouteProvider.php).

I don't know much about what's causing the error. I took a look at the file the error references, but I can't figure out what to change.

Here are the steps I took that led up to the error:

I started with a Drupal 7 website.
I deleted all of my files from the website directory.
Note: The "sites" directory would not delete no matter how many times I tried.
I uploaded my Drupal 8 release candidate 1 hoping that that new "sites" directory would overwrite the old one.
I reloaded my website page and was presented with error above.

Any ideas?

Unfortunately you've gone down the wrong path by deleting your existing site. Hopefully you have a backup you can restore from...

Drupal 8 isn't an update, it's a brand new system; you need to migrate your D7 site to it.

The docs are here, they should contain everything you need


How to perform some Rules Actions WHILE some condition is TRUE? Using Rules, how can you perform a set of Rules Actions WHILE (some condition = TRUE)?

About that condition: I'm not talking here about a Rules Condition ... Instead I mean some sort of boolean expression that evaluates to either TRUE or FALSE.

Also, even though Rules has the concept of "Lists and Loops" (for which you can typically iterate over each item of such list via a Rules Loop), that's not what my question is about either.

I'm not aware how to implement such WHILE-construction by only using Rules. However, if you also enable the Conditional Rules module, you can implement such WHILE-construction.

Example

Consider this rule (in Rules export format):

{ "rules_execute_a_while_loop" : {
    "LABEL" : "Execute a while loop",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_nr" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Value specified for \u0022Free format nr\u0022 is: [node:field-free-format-nr]" } },
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "1" },
          "PROVIDE" : { "variable_added" : { "loop_counter" : "Loop counter" } }
        }
      },
      {
        "WHILE" : { "NOT data_is" : {
            "data" : [ "loop-counter" ],
            "op" : "\u003E",
            "value" : [ "node:field-free-format-nr" ]
          }
        },
        "DO" : [
          { "drupal_message" : { "message" : "Do your thing for \u0022loop_counter\u0022 value = [loop-counter:value]" } },
          { "data_calc" : {
              "USING" : { "input_1" : [ "loop-counter" ], "op" : "+", "input_2" : "1" },
              "PROVIDE" : { "result" : { "incremented_counter" : "Incremented counter" } }
            }
          },
          { "data_set" : { "data" : [ "loop-counter" ], "value" : [ "incremented-counter" ] } }
        ]
      }
    ]
  }
}

Some more details about this rule:

Rules Events: After creating a new node, or after updating an existing node.
Rules Conditions:

Content is of type "Article".
Entity has field, for field with machine name field_free_format_nr (which is of type integer).

The above Rules Events and/or Rules Conditions can be more or less anything (I just used some of the popular ones). The actual magic is in the Rules Actions:

Show a message on the site, just for demo / testing purposes, to show the value enter for the field_free_format_nr field.
Add a variable, with machine name loop_counter, and initial value 1.
While: NOT Data comparison, whereas the test is to check if NOT (loop-counter is greater than [node:field-free-format-nr]), in which case all of the below Rules Actions are performed:

Show a message on the site,  just for demo / testing purposes, to show a message like

  Do your thing for "loop_counter" value = [loop-counter:value]

Calculate a value, to increment loop_counter with 1, and (temporary) store the result in incremented_counter
Set a data value, to copy the value of incremented_counter in loop_counter

BTW, it could well be that the last 2 Rules Actions can be consolidates in a single one, though using 2 Rules Actions should be easier to understand what's happening.

Demo

With the above rule enabled, these are the messages shown if I create or update an article, and specify a value of 3 for the field_free_format_nr field:

Value specified for "Free format nr" is: 3
Do your thing for "loop_counter" value = 1
Do your thing for "loop_counter" value = 2
Do your thing for "loop_counter" value = 3


ctools modal form shows ugly access denied I have made a modal form using ctools. The form works okay when the user has access rights, but with no access rights an empty modal form is showing and I get a browser error saying

"An AJAX HTTP error occurred. HTTP Result Code 403" (and a lot of debugging information)

Is this a flaw in ctools modal or am I missing something?

In case of access denied I would like to fall back to a standard access denied message.

I will try to answer this myself. There is no mentioning of this issue in the CTools project itself but the issue is mentioned at the CTools Auto-modal project https://drupal.org/node/1450232

There is also a solution:

implement hook_page_delivery_callback_alter
check if callback is made by one of your ajax links
if so, check is user has access by using menu_get_item and inspecting the resulting router item
if access is ok, do nothing
if access denied or page not found, render a message

The solution at CTools Auto-modal renders the message in the CTools modal box. But I preferred to kill the CTools modal and just do nothing:

$commands[] = ctools_modal_command_dismiss();
print ajax_render($commands);
exit();

This way the dreaded drupal ajax error will never appear.


Error when attempting to create sync directory I'm installing Drupal 8 with using Composer. During the requirements verification phase I receive this error.

Requirements problem
Errors found
Configuration directory: sync
An automated attempt to create the directory ../config/sync failed, possibly due to a permissions problem. To proceed with the installation, either create the directory and modify its permissions manually or ensure that the installer has the permissions to create it automatically. For more information, see INSTALL.txt or the online handbook.

As I understand it, the full path to the sync directory should be project_root/web/sites/default/files/config/sync, but if I run chown myuser:www-data to the project_root directory, Drupal will literally place the folder as in the error message, project_root/config/sync in my case.
I've never installed Drupal 8 via Composer, but this appears wrong and I can't find any relevant information.

Nothing wrong with that.

It is recommend to have the config folder outside of the public web folder; Drupal just doesn't have that. To keep the installation simple for non-experienced users, it puts that folder in the files folder, which has to be writable anyway.

Just create that folder and give Drupal write permission to it; you'll be fine.


listing users filtered by whether they have posted content or not I've been fiddling with the filters in views but none of the filters seem to work on if they posted content or not.

Is custom code necessary for this?

Have you tried using Relationships instead? User:Nodes authored might be what you are looking for.


Apache Solr and Arabic diacrictics I am using Drupal and I would like to index Arabic text that use Arabic diacritics extensively 'similar to accents in French or Umlauts in German".

The text is indexed but the search doesn't ignore the diacritics when searching. Does anybody know if the Arabic standard tokenizer handle Arabic diacritics?

I read somewhere that some people use AraMorph tokenizer. I am not sure if this can work with Solr 4.4.0.

I use Apache Solr integration module along with Search Api for Solr.

How can I make my search insensitive so that it ignores those diacritics?

Thanks,
Mohamed

Adding the ICUTokenizerFactory to the text fieldtype solves the issue and the search ignores the diacritics.


How do I use a newer version of jQuery with Ubercart shipping quote (Ajax)? If I use any version of jQuery with drupal/ubercart other than jquery 1.2.6, the ajax comes back from (UPS,Fedex,etc), but never updates the objects on the screen.

How do I use a more current version of jQuery with ubercart?

As it turns out, Ubercart will NOT work with jQuery after 1.2.6 unless you make a small change to an Ubercart module

ubercart/shipping/uc_quote/uc_quote.pages.inc

Go to around line 70 which should be the end of the uc_quote_request_quotes function

comment out or replace the broken drupal_json($return_quotes);

replace it with the standard PHP json encoder
print( json_encode($return_quotes) );


string espected but array given in custom pop_date field #default_value Possible Duplicate:
  Date popup form field doesn’t show the default value correctly

I'm trying to set a default value for my custom date_popup field. To be precise I'm trying tho set the field to the first day of the current month. But if I can populate the field without errors I can figure out the rest.

At first I was trying to input a string value:

#default_value = '1/1/2012'

This results in no errors but also the field will remain empty.

I've looked trough some issues including this one and noticed that I had to use a date() as value.
But this also results in an empty field using the the following code:

'#default_value' => date('d/m/Y'),

Which I think should give todays date?

Finally I used the following code:

'#default_value' => array('day' => 1, 'month' => date('m'), 'year' => date('Y')),

which populates the field but gives me:

  Warning: strlen() expects parameter 1 to be string, array given in
  date_default_date() (line 114 of
  /home/quickstart/websites/nieuwesite/sites/all/modules/date/date_api/date_api_elements.inc).

Of course I'm trying to build this field in hook_form(). for reference here is my whole field:

$form['click_stats_date_start'] = array(
'#type' => 'date_popup',
'#title' => t('Start date'),
'#label_display' => '',
'#date_format' => 'd/m/Y',
'#date_year_range' => '-1:+0',
'#date_label_position' => 'hidden',
'#default_value' => array('day' => 1, 'month' => date('m'), 'year' => date('Y')),
'#size' => 20,
'#required' => TRUE,
);

So my question is how do I populate the date_popup field on the first load without errors?

You are getting the "expects parameter 1 to be string" error because the only value the date popup form element accepts as default value is a string with the format described in date_popup_element_info().

  Set the #type to date_popup and fill the element #default_value with a date adjusted to the proper local timezone in datetime format (YYYY-MM-DD HH:MM:SS).

The code you should use is the following one.

$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d'),
  '#size' => 20,
  '#required' => TRUE,
);

If you need to visualize a specific value as default value, then the code should be the following one. (Replace $saved_timestamp with the value you need to show.)

$form['click_stats_date_start'] = array(
  '#type' => 'date_popup',
  '#title' => t('Start date'),
  '#label_display' => '',
  '#date_format' => 'd/m/Y',
  '#date_year_range' => '-1:+0',
  '#date_label_position' => 'hidden',
  '#default_value' => date('Y-m-d', $saved_timestamp),
  '#size' => 20,
  '#required' => TRUE,
);


How remove/hide an action field link? On a node field form (admin/structure/types/manage/article/fields), I have a dropdown with action links for all fields.

Edit
Storage Settings
Delete

I would like know if it's possible to unset the "Delete" link for a field please.
I have try with hook_link_alter() but I don't know how find and remove the link for a specific field (by example field_image).

Thanks.

Assuming those operations check access correctly (not doing so would be a bug), you can use hook_ENTITY_TYPE_access, e.g. in your case hook_field_config_access, there you can deny delete access for a field with a given name.


Drupal 6: only displaying select vocabularies? I use two vocabularies, one for tags and one which determines where a view will be displayed. Can anyone tell me how I could output the terms of my former category while hiding the ones in my latter category?

Thanks!

Assuming that the row style of your view is "Fields", add a "Taxonomy: All terms" field to your view. On that field's settings form, you will see a "Limit terms by vocabulary" checkbox. Select it and choose the vocabulary you want to show.


How to hide profile2 field label and captcha label in registration form I've tried using 2 different functions, where both successfully sets the value to 'invisible' with a dsm($form) check. However, the label is still being displayed.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
          case 'user_register_form':
              $form['profile_users']['field_username']['#title_display'] = 'invisible';
              $form['captcha']['#title_display'] = "invisible";
   break;
  }
}

and:

function MYMODULE_form_profile2_edit_PROFILETYPE_form_alter(&$form, &$form_state){

     $form['profile_PROFILETYPE']['field_username']['#title_display'] = 'invisible';

}

I do not encounter this problem for the username, password and email fields.

Edit: I've also tried:

$form['profile_users']['field_username']['und']['#title'] = '';
$form['profile_users']['field_username']['und']['#title_display'] = "invisible";

you can use this code instead:

$form['captcha']['#title'] = '';


How to convert year to date with Migrate I try to import a CSV file with Drupal 8 Migrate. One column contains a year value which I want to convert to a Drupal date field.

I try to do that with the following process statement using format_date plugin from Migrate Plus but something goes wrong:

  process:
    field_fecha:
      plugin: format_date
      from_format: 'Y'
      to_format: 'Y-m-d\TH:i:s'
      settings:
        validate_format: false
      source: year

I'm not sure if Y is allowed as from_format value. But I also don't know what standard value uses Drupal 8 date field and what to put as to_format value.

Just found out that to_format value is the problem. Setting it to 'Y-m-d' works fine and imports the year value as date putting month and day to values of today. So actually to get specific day and month added to year value, this code works fine:

process:
    field_fecha:
      plugin: format_date
      from_format: 'Y'
      to_format: 'Y-01-01'
      source: year

Probably that's because I defined the date field as "date only". For "date and time" fields 'Y-m-d\TH:i:s' should work fine.


Feeds remove item with certainly conditions Good day

I have a problem with the side of developer

with certainly conditions i need remove a item from source. for example i have in source

nid and phone1 and phone2

but if phone2 is the same that phone1 remove, all this is in updates nodes

function custom_feeds_before_update($source, $item, $entity_id){

  $entity = node_load($entity_id);
   if (isset($item['phone 2'])) {
      if($entity->field_phone_1['und'][0]['value'] == $item['phone 2']){
         unset($item['phone 2']);
      }
  }
}
function custom_feeds_presave($source, $item, $entity_id){

  $entity = node_load($entity_id);
   if (isset($item['phone 2'])) {
      if($entity->field_phone_1['und'][0]['value'] == $item['phone 2']){
         unset($item['phone 2']);
      }
  }
}

something i make wrong? none working never unset if i make dpm in item no appear the item but if i see the node appear update, is other hook

thanks for any help

To alter the source items for the D7 version of Feeds, implement the hook hook_feeds_after_parse().

/**
 * Implements hook_feeds_after_parse().
 *
 * Removes duplicate phone numbers for importer 'myimporter'.
 */
function mymodule_feeds_after_parse($source, $result) {
  if ($source->importer->id == 'myimporter') {
    foreach ($result->items as &$item) {
      if (isset($item['phone 1']) && isset($item['phone 2']) && $item['phone 1'] == $item['phone 2']) {
        // If phone 1 and phone 2 are the same, do not import phone 2.
        unset($item['phone 2']);
      }
    }
  }
}


Use of textimage module how can we convert the contents of the article into image format using textimage module in drupal 7.

Suppose, we are viewing a article in some textformat (ie default format of drupal) and
if we want to see the contents of article in image format.

Check Textimage 7.x-3.x

It provides a field formatter for long text. Be aware that very large text may create memory issues.

From README.TXT:

via Content Type field display formatters

Access 'Content type' administration features via Administration->   Structure->Content Types
Select the content type for which you want to manage a Textimage field   (e.g. Article, Basic page, etc.)
If you need to create a new field, in the 'Manage Fields' tab, add a new   field of type 'Text' (or 'Long text', or 'Long text and summary') or   'Image'
In the 'Manage Display' tab, select a 'Textimage' format for the field   created above (or any existing one)
Click on the gear icon
Select from the dropdown displayed the image style you want to use to   represent the content as a Textimage


How to alter output of markup on a specific views field Is there a way to change the output programatically on a specific field in d8 views?
I have a field called 'IMCID' which I want to output as a link, but the link is going to change based on the value of another field for that row.
For example, if IMCID of row #1 is 15, and Format of row #1 is 'Copy', then I want the output URL to be something like example.com/copy/15, however if IMCID of row #1 is 15, and Format is 'Hard Copy', then the output URL would be example.com/hardcopy/15
If possible, I would like to avoid making multiple template files for individual fields, as this functionality will be carried over onto other fields later on, and would rather not have to manage a ton of template files.
I have tried using hook_pre_render() and hook_post_render(), but the markup doesn't appear to be in this hook so I am not sure how to update the link URL.

Views is mainly a UI tool, also for theming. Check this box in the field:

REWRITE RESULTS
[x] Override the output of this field with custom text

This opens a text box which accepts Twig code and field tokens of other fields which are placed above. Exclude those fields from display if you want to us them only in Twig. You can check the available tokens in REPLACEMENTS PATTERN below the text box. Look in REPLACEMENT PATTERNS for raw field values, don't use formatted output in Twig logic.


Option sets for fields? In my content type I have a products field (entity reference) which references other content types (product content types).
What I want to do is each product field has to have a specific option set, and on the node add form the user can choose a product with a specific said option. Example:

Product: Food package A
Options to choose from: Set A, Set B, Set C, etc.

Product: Food package B
Options to choose from: Set A, Set B, Set C, etc.

My Goal:
Choose product: Food package A
Choose option: Set A

I tried editable fields but what happens is the user edits the original product content. BTW I'm not using any commerce module.

Any help would be greatly appreciated!

I didn't fully understand your question. But what is get is you have multiple fields that each one is specific product say, tablet,cellphone,food and every product field has its own specific sets of options.

I recommend you to use field collection module and set the number of values to unlimited. By this module, define the filed collections and specify what sets every product field is free to choose.


Ajax error when installing When installing Drupal 7.31 in the first page, I can't install with the following error message.

  An  AJAX HTTP error occurred,HTTP Result code 2: debugging information
  follow,  Path:htp://localhost/install.php?
  profile_standard&locale-en&op_do statustext: Unknown ResponseText:

  error page show : Fatal error:call to  undefined function
  node_types_rebuild() in C:/APM_setup/htdoc/includes/common.inc  on
  line 7512

  line 7511---entity_info_cache_clear();
          7512---node_types_rebuild();
         7513---//node_menu()  defines menu items based on node types so it needs to come
         7514---//after node types are rebuilt.
         7515---menu_rebuild();

Every time i delete and again try to install this always it's same.

I had problem like this. You need to increase memory_limit.

For XAMPP: you can change it globaly in php.ini (in xampp located in '\xampp\php\php.ini')

  memory_limit = 8M // search for this "memory_limit" and adjust it by your needs (min 64M)

For WAMP: right click on the WAMP icon, then navigating to the PHP folder/menu-thingy and selecting php.ini, and find memory_limit (like on XAMPP)

After you made a change restart Apache and try to install Drupal from the beginning.


Lock Workbench content until moderation state change I'm managing content workflow using the Workbench module. Content is moved through various states until it's made live by the publisher.

I've managed to lock content whilst it's being edited, using the Content locking module, which seems to do the job well. However, I now have another requirement to lock the content to the user until the user is finished editing it, which is to be indicated by changing the state to the next level, such as 'Ready for review'.

Can anybody suggest a method of doing this?

There is a really cool module called Rules Forms that could help here.
https://drupal.org/project/rules_forms

You have to set it up so that it works with your particular content type. See admin/config/workflow/rules/forms
Create a Rule and set two Events "XX node form is being built", and "XX node form is being validated", where XX is your content type
Set an Action called "Set an error on the form" and then choose "Title" for lack of something else, and then enter a message about this node being locked.
Set up the conditions as needed - probably need to check the user id and the state of that node - this is the part where I can't help without seeing your particular site.

If you don't set any conditions, nobody will be able to create or edit nodes of this type until you do.


How to remove source from RSS feed? I have a site where Drupal generates rss through a view and then an external source uses that rss. Now the client says that I should remove the source from RSS. How can I remove the source from rss? See the source in image.
The source shows the url.

You can make a custom template taking views-view-rss.tpl.php as starting point.
See the template under modules and views/theme/views-view-rss.tpl.php


Changing a menu link used in the sitemap module but not in main nav We are using the Sitemap module for creating a sitemap generated from three menus (Footer, Main nav and a 3rd arbitrary one).

In the main nav we have a placeholder LI element which we use to insert a view.

In the sitemap template we need to replace this placeholder with some content without affecting the main nav.

In the sitemap overridden template where {{ item.content }} normally appears I tried replacing with the following:

{{ item.content|replace('>LRGPH_BRANCHES_BY_SERVICE<', ('>' ~ allBranches ~ '<')) }}

Note: allBranches is a concatenation of the output of 4 views (Essentially pure HTML)

but Twig/Drupal seems to have issue with this as I get an error, as per below:

  Warning: strtr() expects parameter 1 to be string, array given in twig_replace_filter() (line 521 of /var/www/vendor/twig/twig/src/Extension/CoreExtension.php).
      twig_replace_filter(Array, '>LRGPH_BRANCHES_BY_SERVICE<', '>

I next tried using the contributed modules hook, namely function TEMPLATE_preprocess_sitemap(&$variables) but although I can see the HTML output of the sitemap I cannot change it using this as far as I can tell.

Is there any way to achieve this change at all without altering the Main navigation?

{{ something.content }} is a render array, you can't do a string replace on an array. But you can store the computed string output of the render array, and do a string replace on the rendered output:

{# compute the output of the render array and store it #}
{% set rendered_html_string = item.content|render %}

{# do the replacement #}
{% set modified_string = rendered_html_string|replace('seachtext', 'replacetext') %}

{# print the modified string #}
{{ modified_html_string }}


User relationship requests in a view block with accept and decline links I have a node in which i want to show a user all the relationship requests the current user has received and a status link below that so that the user can accept or decline the request then and there itself without needing to go to the boring Drupal default user relationship page. I am obviously using the user relationship module for this purpose. Anyways, i set out to create a view but after tinkering enough i was unable to do so. What i was able to do was to get a list of all relation requests (also made by the logged in user) I want only the received request.  How can i do this? If it helps, here's my view

Add requestee relation.
Add context filter by user id (set it on current user with requestee relation). Add filter criteria by relationship status.

Here you can see screenshot of view.


How can I display author name, picture and signature when viewing a full node in D6? I'd like to display the name, picture and signature of a node's author at the bottom of each node. The node.tpl.php file that I'm using (supplied by the zen theme) includes variables for the author's name and picture, but not the signature. How can I make that accessible in the template file?

Figured it out. To add a $user_signature variable to your node.tpl.php file, add this function to your template.php file:

function YOURTHEME_preprocess_node(&$vars, $hook) {

  $account = user_load($vars['uid']);
  $vars['user_signature'] = check_markup($account->signature, $account->signature_format);
}


Is it possible to trigger a webform submit via url? I have set up a webform for simple user polling with an yes/no option, with a submit button.

  [ ] Yes
  [ ] No

  Submit

and the parameter is pass via URL as default, e.g.:

 http://example.com/event_form?option=y

Currently, the webform link is sent via email. So users click the link, open a browser, select an option or use the default, press submit, and see the confirmation message.

Is it possible to automate the submit click? Such that the submit button is automatically clicked after clicking on the link in email?

Inject some javascript into the body using PHP can make auto submit to work by a param in URL:

 http://example.com/event_form?autosubmit=yes&option=y

For example, the webform node ID is 101:

<?php if ($_REQUEST['autosubmit']) { ?>

    <script>
    (function ($) {
        $(document).ready(function(){
            $('form#webform-client-form-101').submit();
        });
    })(jQuery);
    </script>

<? } ?>


import content types from sql dump I recently had a db crash on the site I am currently working on.  I was running sqlite, and the crash locked the db.  No matter what I tried, I couldn't get drupal to access the database again (killed the process, exported into a new db, reinstalled drupal).  So I decided to just migrate it to MySQL.  I converted the sql dump from the old database to MySQL syntax without too many problems.  I can import my nodes just fine, I cannot however get my content types, panels and views to import.

I have tried dbtng migrate, it recognizes both databases, however it keeps giving me schema errors that I can't get around.  ie. destination database does not contain table variable_store -> import variable store from sql dump -> destination database contains table varaible_store dbtng migrate cannot overwrite table.  That is an issue in and of itself, but I digress.

The original site is completely dead, there is no way I can backup from the Drupal UI.

TLDR
cannot import content types, panels or views from sql dump.

Assuming your SQLite dump is complete, your best bet is probably to try and properly convert it to MySQL format and then restore to an empty database.

There's a good thread over at stackoverflow with information on SQLite to MySQL conversion: https://stackoverflow.com/questions/18671/quick-easy-way-to-migrate-sqlite3-to-mysql

I would paste a solution from there here, but as it's a sibling site, probably ok to just pop over and try some of those solutions.

Good luck


twig kint permissions buggy When debugging with kint in a twig tpl the output is seen also by site visitors although they are not logged in.

Permissions "Access kint information" are set just for admin.

Is this a bug?

Most likely the issue is probably related to caching, you can argue that it's a bug in devel/kint module and that is should have an implementation to handle this.

I would argue that the use of kint in a template file is made for running the site in development mode and if you disable caches (which is a really idea on an actual production site) it should work just fine.


How to use managed_file to upload many files I'm looking for a way to upload many files by means of the managed_file form API element. I would like it be like while uploading for node where is 'add new item' button.
How to do it?

You may want to use plupload form element instead. Install Plupload integration module and then use something like:

$form['my_element'] = array(
  '#type' => 'plupload',
  '#title' => t('Upload files'),
  '#description' => t('This multi-upload widget uses Plupload library.'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg jpeg gif png txt doc xls pdf ppt pps odt  ods odp'),
    'my_custom_file_validator' => array('some validation criteria'),
  ),
  '#plupload_settings' => array(
    'runtimes' => 'html5',
    'chunk_size' => '1mb',
  ),
);


How to sort view using already sorted array in hook_views_query_alter I have the following code to alter a view and filter IN only specific nodes

function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if($view->id() == 'myview'){
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == "node_field_data.nid") {
          $condition = array(
            'field' => "node_field_data.nid",
            'value' => [2,4,6,1,3,5],
            'operator' => 'in',
          );
          break;
        }
      }
    }
    //this does not work
    //$query->addOrderBy('node_field_data','nid', 'ASC', '', [2,4,6,1,3,5]);
  }
}

and I want to sort them with this specific order [2,4,6,1,3,5]

I tried not putting any sorting field but the view sorts the nodes by created date.  How can I tell the view to sort them in this manner ?

I think I need to use ORDER BY FIELD('node_field_data'.'nid','2','4','6','1','3','5') in sql but I don't know how its done in drupal

I have seen this answer but don't know how it applies to my case

any help would be appreciated

OK I figured it out

$query->addOrderBy(NULL, 'FIELD(node_field_data.nid,2,4,6,1,3,5)', 'ASC', 'order_field');


Error when trying to upload a Configuration Synchronization file I want to create a local copy of a production website. I read that I could use Configuration Synchronization to copy some of the settings of the production website over to my local website. When I try to upload the exported .tar file from the production website to my local website, I get this error:

Could not extract the contents of the tar file. The error message is Invalid checksum for file "Y3drj:+uT}vG|59ooc&{C:BS1@/f/" : 65255 calculated, 0 expected

I'm using lando to host the website locally. I also had to delete some of the characters in the error message above because stack exchange wouldn't let me post them.

what you need to do is make few changes on settings.php file

$config_directories = array(

CONFIG_SYNC_DIRECTORY => 'sites/default/files',

);

On production sites, and if your account has permission to do so, it's a good idea to move the configuration sync directory outside of the webroot entirely. As your sync directory should be under version control, this means having your version control repository's root be one level higher than your webroot.  please check out more details at  https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory


Pager for basic pages in Drupal I am working on site, on site for certain set of basic pages i want to provide a numeric navigation with previous/next buttons. Is there a module to achieve it easily or else we need to hard code it.

Please suggest me some solutions to get this functionality.

Smart Paging have the option to navigation with previous/next links with numeric navigation see the below image and add a css style to prev/next class to achieve the button effect. See the demo

also worth checking this module Pagerer for providing a collection of pager themes to enhance Drupal and Views standard pagers. See Demo


How to override Bootstrap theme files in sub-theme I'm creating a sub-theme based off Bootstrap. I've followed the instructions here and is working ok.

Now I want to override the tpl files in theme/block, theme/system, etc.

In my sub-theme I've created the folder structure mimicking the one on Bootstrap (at least for the ones I want to override), yet it seems my files are not being used.

How can I override the aforementioned files (preferably) using the same structure?

Thanks for your help

You should put those files in yourtheme/templates/ (no sub-folder) and a quick cache clear after that.

See bootstrap_subtheme/templates/README.txt:

  This folder is where you should place all your overriding template files. By
  default, the Bootstrap base theme provides all the necessary template files in
  various folders inside of sites//themes/bootstrap/theme. For example, the
  page.tpl.php template file is located at
  sites//themes/bootstrap/theme/system/page.tpl.php. To override any of these
  files, copy them from the Bootstrap base theme and place them in here.


YAMLFORM Element Settings I'm using yamlform in my Drupal 8 site and I want to add a new setting (i.e General Settings, Form Display etc) to each of my fields based on if I have a handler attached to my form.

I have used the

function prepare()

method for this in my custom elements, but I would like to add it to all existing elements as well, there are several hooks available but I'm not sure which one would be most appropriate.

I realise that yamlform gives you a custom settings box, but I need something a bit more obvious for my non-tech end users.

Thanks.

So In the end I had to use hook_form_alter, here's a quick trimmed down example of how I achieved my particular problem:

function hook_form_alter(&$form, FormStateInterface $form_state, $form_id) {

if ($form_state->getFormObject() instanceof YamlFormUiElementEditForm and hashandler) {

$form['newsection'] = [
  '#type' => 'fieldset',
  '#title' => t('New Section'),
];
$form['newsection']['newfield'] = [
  '#type' => 'textfield',
  '#title' => t('New field'),
];


How to make Taxonomy replacement tokens available to the HTML email action in Rules? I have created a rule for a client that triggers an HTML email to them every time an authenticated site visitor downloads one of their PDF brochures.

I have no problem including things such as the username, email address, filename and other info, but the client wants to have the "vertical" of the PDF displaying as additional information on the outgoing email.

The PDF's are uploaded as a unique content type and are categorised by using taxonomy terms through a select field.

Unfortunately, when editing the HTML email action element on the rule, there are a whole bunch of replacement tokens, except any related to taxonomy. I tried to "wing it" and create a taxonomy token, but of course this did not work and it seems logical that there would naturally be a disconnect here as how would the rule know to relate the correct term to the file being downloaded.

Any advice with regards to possible workarounds?

Make sure to add a Rules condition Entity has field (related to your field you indicated via the "through a select field..." in your question).

That's also what is mentioned in the Rules UI, e.g. when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

Your question seems to be related to using such field in a Rules Action (instead of a Rules Condition). However, have a look at the sample rule in included in my answer to "How to specify a Rules condition related to select list values?". That rule doesn't have a "Rules Action" that uses that field (as you seem to try to do). Though using the Rules UI to (eg) edit the message I'd want to display in my sample rule, within the list of tokes available for Replacement patterns for created content, one of them is actually [node:field-optionlist]. And the 'created content' in my case is because of the Rules Event node_insert that's used in my sample rule.

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.

PS: To have such field available to use it in any other Rules Condition also, I always add such Entity has field condition BEFORE any other Rules Conditions, if any.


Limit Teaser to display only the first value of a Field I have a Content Type with an Image Field. This field will typically be populated with 0 to 4 values. By default the teaser for this Content Type outputs all 0 to 4 images. How can I adjust the Teaser to only display the first image?

Create a custom module, replace MODULENAME with the name of the module and field_image with the name of your field:

/**
 * Implements hook_entity_view().
 */
function MODULENAME_entity_view($entity, $type, $view_mode, $langcode) {
  if ($view_mode == 'teaser') {
    $entity->content['field_image']['#items'] = array_slice($entity->content['field_image']['#items'], 0, 1);
  }
}

See the hook_entity_view() documentation for more details.


Unable to install the XYZ module since it requires the A module When running (right after site install) the drush cim -y command, the following error appears:

Drupal\Core\Config\ConfigImporterException: There were errors validating the config synchronization. in Drupal\Core\Config\ConfigImporter->validate() (line 728 of /var/www/ifc_test/web/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:
Unable to install the XYZ module since it requires the YAML
Editor module.
Configuration XYZ.conf depends on the YAML Editor module that will not be installed after import.
Configuration yaml_editor.config depends on the YAML Editor module that will
not be installed after import.

(XYZ is the name of the custom module.)

I have the yaml_editor contrib module physically under modules
There is a dependency declared in the configuration files above
I also added yaml_editor to the core.extension.yml file to make sure it should be installed

Why config importer not enabling the yaml_editor module? I mean, that's what dependency declaration is for. Also, I've got a couple of other modules which are not enabled after site-install, they will be enabled during the drush cim process.
Of course drush en yaml_editor -y solves the problem, however, it's part of a building process, and I don't want to just insert an extra line into deployment script, just because this strange thing is happening.
Any ideas why config management doesn't enable (installs) this dependency, and why it says: "that will not be installed after import"?

Adding the yaml_editor to core.extension.yml solved the issue.
It perhaps were removed due to a complex git merge, and that's why my install process started to fail all that sudden.


Node title inside layout (Layout Discovery + Field Layout) Just tried the new core modules Layout Discovery and Field Layout and I want to render the title of a node between two fields.
Without these modules, node's title can be rendered between other fields very simple by using inside node.twig.html something like:

{{ content.field_image }}
{{ label }}
{{ content.body }}

But when I try to use {{ label }} inside the registered layout template, nothing gets rendered. Can somebody help me?

Thank you in advance.

I wasn't able to get variables inside layouts due to this bug https://www.drupal.org/project/drupal/issues/2861840
Drupal 8.5 fixed the problem.
Now, inside mytheme.theme if I put this:

function MYTHEME_preprocess_layout(&$variables) {
  $request     = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
   $variables['node_title'] = $title;
}

I'm able to use {{ node_title }} inside layouts.


How to give a content editor access to the theme settings? I'm using the Marinelli theme and want to give my main content editor access to the theme settings.  Ideally just the ability to upload/change/add/subtract/enable the backgrounds of the rotating banner.

I don't see any way for them to do this without full access to the Theme settings. I was able to just give "administer themes" settings to this user and give them a shortcut to that theme.  But that's still a lot of liability.

Has anyone been able to do this: limit theme configuration to just certain tasks?

You could use a hook_form_alter in your custom module.

The following assumes you already have a role called editor existing in your website.

Create a mymodule folder (e.g. in http://www.example.com/sites/all/modules/custom/mymodule)
Create two files in that folder. mymodule.module and mymodule.info
Past the following code in mymodule.module

 <?php

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

  if ($form_id == 'system_theme_settings' && in_array('editor', array_values($user->roles))) {
    // unset the elements you don't want your content editor to have access to
    // unset($form['css3']);
    // Here we want to hide some form elements.
    // To hide/show an element we must use $element['#access'] key in the render array.
    // Using unset($element) might cause issues in form_validate and form_submit processes.
    // So instead of unset($form['css3'], $form['layout']) we set their access to FALSE
    $form['css3']['#access'] = false;
    $form['layout']['#access'] = false;
  }
}

Past the following in mymodule.info

name = Mymodule
core = 7.x
Enable your module at http://www.example.com/admin/modules
Clear your cache

Please note that these are the minimum requirements for creating a custom module and you should definitely read up on best practices for creating custom module at https://www.drupal.org/node/1074360


Custom form register i have any fields form register user drupal 7. I want to when user choice select box : User 1 or User then any fields hide or show. Please help me
Thank to all.

Look at Conditional Fields:

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API. You can, for example, define
  a custom “Article teaser" field that is shown only if a "Has teaser"
  checkbox is checked.

EDIT

To learn how to use the Field UI and create these form items for Users please see:

https://www.drupal.org/documentation/modules/field-ui
https://www.drupal.org/documentation/modules/options


When adding Custom Blocks the weight is changed for the rest of the blocks We are using custom blocks very extensively. We are also using block visibility groups and Domain Access. At this point when we make a new block it changes the weight of many of the other blocks at what seems to be random intervals.

Has anyone else had this issue?

If you have blocks that have the same weight, that may trigger a bug where your blocks get shifted. At least, this is something I have experienced with views filters in D7, and I found a bug report here regarding a similar weight issue in D8 with taxonomy terms: https://www.drupal.org/node/941266

Ensure you are able to see the numerical weights of the blocks, and make sure they all have distinct weights.


Organic groups and "Create content" I want to replicate the Drupal "Create Poll,Event" links etc of the Drupal groups.
How can I accomplish that with Organic groups?
Thanks

In case you use panels, Organic Groups module comes with a content create panel pane that allows to select the content types to include in such a links list.


Can I Search an entity reference with search api db? I am using the search api database backend together with a views (with exposed fulltext search field). I want to show a 'related field' that is related to a content type that is being indexed. When the entity reference field only holds 1 value, all is fine.

But when it holds unlimited values (in the field settings) it no longer works in the view :-(

Does search api db have a limitation on indexing multivalued fields?

UPDATE

My content types are as follows:

Content type a

Field_a = text
Field_b = entity ref to content type b (allowed values unlimited!)

Content type b

Field 1 = text
Field 2 = text

I have indexed all fields above and added the related fields 1 and 2 to my search index as related fields.

Then when i create a view that shows the indexed nodes for content type a, and want to show field 2's information of the node that is referenced it only works when field b is set to allowed values: 1

SearchAPI does have this limitation: Note: This is a multi-valued relationship, which is currently not supported. Only the first related entity will be shown.

Here is the issue about this. https://www.drupal.org/node/1378656


How do I get the vocabulary of a term inside an "article" type content type? I have a content type tagged with various vocabularies. Each vocabulary has terms which I want to style with particular colours based on the vocabulary. For example, say I have a "Fruits" vocab which has term 'apple' and 'banana' and a "veggies" vocab with 'onion' and 'carrot'. I want to colour the apple and banana tags RED and the onion and carrot tags BLUE *in same node. Say I've a content type "article" which is tagged with apple from the fruits vocab and carrot from the veggies vocab. 'apple' should have a RED background and 'carrot' and BLUE background. Another content node has apple and banana for tags and they should both be RED.

I've found the following code, but it only works when the page I am viewing is the "apple" page - that is, I'm reading the page for the vocab term apple, NOT a content type tagged with apple. It DOESN'T work for tags in other content types and I'm failing miserably to find the right code.

function MYTHEME_preprocess_field__entity_reference(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
  // load the term entity and get the data from there
  $term = \Drupal::routeMatch()->getParameter('taxonomy_term');
  $variables['vocab'] = $term->bundle();
  }
}

My theme has custom twig files for field--entity-reference.html.twig

and I'm trying to use the preprocess function above. Nothing I can find anywhere addresses this; what gives?

Adding the answer now. My final code in the field--entity-reference.html.twig file:

{% for item in items %}
  {% set mylabel %}
    {{ item.content }}
  {% endset %}
  {% set myclass %}
    {{ item.content['#options'].entity.vid.0.value['target_id'] }}
  {% endset %}
  {% set myclass = myclass|replace({'_':'-'}) %}

      {{ mylabel|striptags }}

{% endfor %}

HERE is the code needed in a node to access the parent vocabulary of the taxonomy terms in the node. (That is, individual tags on a content type node).

item.content['#options'].entity.vid.0.value['target_id']

NOTE: This is on Drupal 8.5.3 and none of my "tags" have more than one parent.


adding media content to a Drupal Commons Group page header? I've been playing with Drupal for a bit, and have gotten used to the idea of Content and fields.  I am now trying to use Drupal Commons 7 to up my game some and improve how my site looks.  Im a bit stumped however on how I can edit the look of my Group page.  Id like to add a big image at the top, before the group content.  I think this is done using panelizer but Im not sure.

First is this right?  Second, if so, where can I look for getting started tutorial type stuff that explains panelizer and how it works with the underlying field system?  Do I have to add a field to content somewhere?  If so, what and where?

Thanks

I solved it by enabling the Media component and then adding its widget in the CKEditor configuration.


Cannot delete entity I'm unable to delete a custom entity. I'm getting the following error

$storage_handler = \Drupal::entityTypeManager()->getStorage("notification_storage");
$notification_entities = $storage_handler->loadMultiple($notifications['notification']);
$storage_handler->delete($notification_entities);

  Symfony\Component\Routing\Exception\RouteNotFoundException : Route "entity.notification_storage.canonical" does not exist. dans Drupal\Core\Routing\RouteProvider->getRouteByName() (ligne 202 de /var/www/html/docroot/core/lib/Drupal/Core/Routing/RouteProvider.php).

/**
 * Define NotificationStorage entity.
 *
 * @package Drupal\notification\Entity
 *
 * @ContentEntityType(
 *   id = "notification_storage",
 *   label = @Translation("Notification Storage"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\notification\Controller\NotificationStorageListBuilder",
 *     "views_data" = "Drupal\notification\NotificationViewsData"
 *   },
 *   base_table = "notification_storage",
 *   entity_keys = {
 *    "id" = "id",
 *    "uuid" = "uuid",
 *    "langcode" = "langcode"
 *   },
 *   fieldable = TRUE,
 *   links = {
 *     "canonical" = "/admin/notification_storage/list"
 *   },
 *   field_ui_base_route = "notification_storage.settings"
 * )
 */

You've defined a canonical link in the entity annotations, but this doesn't build a route automatically. If you don't want to do specify the route in a yaml file you need a route provider:

 *   handlers = {
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",

If the custom entity should be part of the admin interface use AdminHtmlRouteProvider.


How to override webform in template.php I've followed different tutorials but I cannot seem to override a field on my webform via a function in template.php.

  Theme is called: 'myTheme' Id of the form is:
  'webform_client_form_76' Id of the input:
  'edit-submitted-henkilotiedot-etunimi' Name of the input:
  'submitted[henkilotiedot][etunimi]'

The function I think should work:

function myTheme_webform_form_76 (&$vars) {
    $vars['form']['submitted']['edit-submitted-henkilotiedot-etunimi']['#value'] = t('Name');
}

What is the correct format to override webform elements?

function [themename]_form_webform_client_form_76_alter(&$form, &$form_state, $form_id) {
// code of altering
}


How can I write a query to get a list of users who have registered in the last 24 hours? I'm trying to use PHP to generate a query that fetches the number of users who have registered in the last 24 hours.

Based on the code for the "who's online" block:

$authenticated_count = db_query("SELECT COUNT(DISTINCT s.uid) FROM {sessions} s WHERE s.timestamp >= :timestamp AND s.uid > 0", array(':timestamp' => $interval))->fetchField();

I modified it as follows (based on this old D6 Stackoverflow answer:

$users_registered = db_query("SELECT COUNT(DISTINCT u.uid) FROM {users} u WHERE u.created >= :timestamp AND u.uid > 0", array(':timestamp' => ($_SERVER['REQUEST_TIME'] - 86400)));

However, this results in an error:

  Notice: Object of class DatabaseStatementBase could not be converted
  to int in format_plural() (line 1801 of
  /var/www/om/includes/common.inc).

I'm not great with SQL, so a brief explanation of where I'm going wrong would be much appreciated.

It seems to me that you aren't doing anything wrong; it's just that the object you will get back from db_query() in your case is not something you can use as is.

Invoke ->fetchField() method after db_query() so that Drupal's DB API returns you one single value.

Use this:

$users_registered = db_query("SELECT COUNT(DISTINCT u.uid) FROM {users} u WHERE u.created >= :timestamp AND u.uid > 0", array(':timestamp' => (REQUEST_TIME - 86400)));

Also, use REQUEST_TIME constant to get current timestamp.

Hope this helps.


How to create a view of unread comments on own nodes for the user's profile page? I'd like to create a view for the user's profile page that displays all unread comments on the nodes he/she created. When I say 'unread', I mean that the page where the comment is situated (namely, the node's page) hasn't been visited by the user yet. In other words: when the user hasn't read a new comment, it will be displayed in the view; once the user has read it, it will disappear in the view.

I've already set up a view that simply displays all comments on the user's nodes, but I can't find an extra 'Filter criteria' or 'Relationship' that filters out the unread ones.

Can you help me?

Edit: I created a flag called 'Read' ('Reactie gelezen' in Dutch) with the Flag module and a rule 'Comment read' that automatically flags comments with 'Read' when they're viewed. I've also granted every user the permission to flag comments with the 'Read' flag (although they won't see the flag links above their comment of course).

My rule works perfectly and the flagging works manually too. The view however, doesn't work properly. These are my settings:

Both uid's were provided the default value 'User ID from URL'.

What did I do wrong?

The Flag module only keeps rows in the database for content where a flag is set. I.e. when something is not flagged, there will be no corresponding row in the database.

The problem is, that views will generate a query which looks something like this (for a user with uid=12 and a flag with fid=1):

SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
LEFT JOIN flagging AS f ON c.cid = f.entity_id AND f.fid = '1'
WHERE n.uid = '12' AND f.uid = '12'

However in order to select all comments for a given user excluding those which are not flagged, you need an SQL subquery:

SELECT cid FROM comment AS c
INNER JOIN node AS n ON c.nid = n.nid
WHERE n.uid = '12' AND c.cid NOT IN (
    SELECT f.entity_id FROM flagging AS f
    WHERE f.fid = '1' AND f.uid = '12'
)

AFAIK Views has no built-in support for subqueries. I therefore recommend you to reverse the logic and implement the following:

Add a comment-flag is_new
Whenever a new comment is posted, execute a rule which sets this flag on behalf of the content author.
Whenever a node is viewed by its author, execute a rule which removes all is_new-flags on the associated comments (this is essentially the same rule you already have, except that you need to reverse the flagging-logic).
Configure the view just as you did before but remove the flagged=false filter, instead configure the flag-relationship such that only flagged content is included.


How do I translate/change the text of the order receipt email in Commerce 2? The Commerce 2 documentation describes how to send a an order confirmation receipt:

Go to the Commerce admin page.
Choose order types.
Click edit for the relevant order type and check the box to email a receipt.

However, how do I translate the text of this receipt?  There appears to be no UI for this.

You can find the Subject on the UI translate page (/admin/config/regional/translate).  Search for Order #.

The rest can be found in a twig template:

/modules/contrib/commerce/modules/order/templates/commerce-order-receipt.html.twig

Copy this template to your theme and then edit as desired.  You can also use the template as a guide for what to search for on the translation UI screen to translate everything.


Getting the node link in views-view-fields.html.twig I've created a block display view to list recent posts on a page. Which variable can I use inside the views-view-fields.html.twig template file in order to retrieve the link to the post?

        {{ fields.field_image.content }}

    read more +

{{ fields.title.content }}

    {{ fields.body.content }}

Add a "Path" field and include it in the view. It should be something like: {field.path.content} You can always format it :D


Not able to access pear.drush.org So what happend to pear.drush.org I havent been able to access that page and drushs puppet module relies on it. Is the site down?

The Pear installation method for Drush was deprecated many years ago; I am not sure how long it has been unavailable, but it will not be coming back. The recommended and supported ways to download Drush are:

Use composer
Clone the git repository, then run composer install
Download the .phar

The Drush Puppet module on drupal.org claims to support git and composer installation mechanisms; perhaps you'd have the best luck if you switched to using that one.


Calculate time between start and end time I'm building a website where I need to know the time (in hours) between the start and end time from a date field. So I want to know how long it took. It's usually from one day to another, sometimes just on one day (don't know if that matters).

I made a field Date (Unix timestamp) with month, day, hour and minute. Users need to choose both start and end time.
I also made a Computed field. The first part is the Computed code and the second part is de display code:

<?php
$field_tijden = array_pop(field_get_items($entity_type, $entity, 'field_date'));

$start = $field_tijden['value'];
$end = $field_tijden['value2'];
$timezone = $field_tijden['timezone'];

$date_start = new DateTime($start, $timezone);
$date_end = new DateTime($end, $timezone);

$interval = $date_start->diff($date_end);

$entity_field[0]['value'] = $interval->format('%h');
?>

<?php
$display_output = $entity_field_item['value'] . " hours";
?>

I checked "Store value in the database", checked "Float", data length "3,2" and the other settings I kept on default. This is what I copied from another website and all I tweaked was changing it to $field_tijden which is the name of the field.
I know almost nothing about PHP, so I have no idea what to change to get this to work. Right now when I save a node the field is not being displayed.

Is there anyone who can help me getting this to work?
Thanks in advance!

Edit: These are the settings I put in a Rule, but it's not working yet. Does anyone see what I'm doing wrong?

Events:
 - After saving node

After updating existing node

Conditions: nothing

Actions:

Convert data type. Value: Integer. Selector: node:field-tijden:value (this is the start time). Label: conversion-result-start.
Convert data type. Value: Integer. Selector: node:field-tijden:value2 (this is the end time). Label: conversion-result-end.
Calculate a value. Selector: conversion-result-end. Operator value: (-). Selector 2: conversion-result-start. Label: result-calculation.
Calculate a value. Selector: conversion-result-calculation. Operator value: (*). Selector 2: 60. Label: result-in-minutes.
Calculate a value. Selector: conversion-result-in-minutes. Operator value: (*). Selector 2: 60. Label: result-in-hours.
Convert data type. Value: Integer. Selector: result-in-hours. Label: conversion-result-in-hours-converted.
Set a data value. Selector: node:field-tijden:duration (I'm not sure where the :duration is coming from)

There is a way to accomplish this without writing any code. You can use the Rules module to calculate the difference between dates and to update a field in any entity or node.

There isn't a Rules action that will calculate the difference between dates, but there is still a way to do it in Rules. It involves four simple steps:

Use the "Convert data type" action to convert both date objects to Integer types. This will create variables that use a Unix int timestamp (number of seconds since 1/1/1970)
Calculate the difference between the two integers and store in a variable
Divide the result by x number of seconds, depending on what you want to calculate. To calculate days, divide by 86400 (60 * 60 * 24)
Use "Convert data type" to round the subtraction to an integer (and store in a new variable)

Then you can simply use the Rules action "Set a data value" to store this value in a node (or entity) field

You can trigger this Rule whenever the user saves or edits content of specific type.


How can I restrict users to some parents node with node hierarchy? I have the Node Hierarchy module on my Drupal installation, and I am using the following hierarchy:

Main Navigation (menu)

Art & Sciences

Art
Sciences

Economy

News

World wide
Other

What I want is that:

Stephanie can add/edit/delete content any content from "Art & Sciences" section
Stephanie can NOT add/edit/delete any content from other sections
John can add/edit/delete content any content from "Economy  " section
John can NOT add/edit/delete any content from other sections

I tried to install Workbench access; it creates me sections, but users can choose any node for parent, whatever the hierarchy.

Node Hierarchy obviously add nodes to the "Main navigation" menu as menu links. Despite of editors, everyone can add a node in every menu, but I want to restrict each user to their section. I can assign only the section I want to a node, but in the hierarchy it's not correct.

Is there any module (even if I have to use more than one) I can use to achieve what I want?

I suggest you attach a taxonomy vocabulary to your content type and use the Taxonomy Access module.

So, create your vocabulary:

Arts & Science
Economy
News

Create roles based on taxonomy:

arts_role
economy_role
news_role

Assign permissions to roles:

Edit terms in Arts & Science to arts_role
Delete terms from Arts & Science to arts_role
Edit terms in Economy to economy_role
Delete terms from Economy to economy_role
Edit terms in News to news_role
Delete terms from News to news_role

Assign your users to your roles:

Stephanie gets arts_role
John gets economy_role


Content from the same content type as the current user I have users with a "field_org" entity reference (multiple values allowed) to the "Org" content type. I also have a "field_org" (single value) in my "Article" content type.

When looking at a user profile (let's call this user "UserA"), how do I build a view that gets you "articles from your orgs" (i.e. created by other users that also belong to any of UserA's orgs)? And, bonus question: how do I exclude articles created by UserA? (since I have a separate "your articles" view showing in the same page).

I know this is probably a combination of relationships and contextual filters, but I can't figure out exactly how to configure them. Probably something like this:

Contextual filter on node author to prevent "UserA's articles" from showing (set to "exclude" in the options)
Contextual filter on node author, but probably set to one of the relationships below.
Relationship between article nodes and orgs?
Relationship between orgs and users?

Both contextual filters would load the same user ID using "Provide default value".

Create a content view
Add the Content: Author relationship
Add the Content: Author uid contenxtual filter

Provide default value: User ID from URL

So far we have a view displaying content created by a certain user, we still have to narrow down the results to a single content type.

Add the Content: Type filter = Org

Note that a page view (with a path) will show no results if you just hit the path. To have results you must pass a uid to the url, like mypath/%uid. On the other hand you can create a block or a content pane and place/embedded it to the user's profile, view's will return all results (if any) for you!


Views, Filter based on part of url I have a content type: "artist_news" which has an entity reference to "field_artists". So that when you create a news story you attach it to an artist.

the url for this might look like this: /artists/picasso/news/my-news-item

I am trying to create a view block, to appear on the page "/artists/picasso/news/" that shows all news "artist_news" items that reference any given artist (e.g. picasso)

I cannot figure out how to exactly structure it. I suspect I need to use contextual filters but the exact settings of contextual filters is escaping me.

Thank you in advance for your help.

That is just your pretty URL.  Your actual url is something like this node/52.

So in your contextual filters, choose provide default argument and then select the content id from the URL.  Views will pull in the 52 number for your referenced entity and that will filter your block accordingly.

UPDATE
Since you are manually creating your URLs, and idea here would be to grab the first and second element from your path.  I do not recommend this.  I would recommend you adding another field to reference the artist on the news basic page so you can use that value in your contextual filter.  Anyway here is what you could do.

In the contextual filter, when providing a default value, use the PHP filter and add something like this to return the value of the NID of the artist.

$path = drupal_get_path_alias($_GET[‘q’]);
$path = explode(‘/’, $path);
// This path should be something like artists/picasso
// The idea here would be to get the artists node path
// and then retrieve the node id from that.
$node_artist_path = drupal_get_normal_path($path[0].'/'.$path[1]);
// ^ should return something like node/33
$nid = arg(1,$node_artist_path);
return $nid;

This will return the value of nid from the artists main path.  AGAIN I do not recommend this as its very dependent on path aliases.

Also I did not test any of this code, I may have some functions wrong and if I do let me know and I will update it, this is all from memory.


How should I add multiple markers using geofield module? Whenever I set the module with unlimited values there are more the one maps with location. However they show the location which I want, but in two or more different maps.

My problem is I want to integrate multiple location with a single map. My project is kind of setting the route for people.

How do I do that? Should I create a hook for the Geofield module?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.
PS: I'm assuming this question is about D7 ...