How can I automatically make term relations between all the terms with same term name? I have multiple Taxonomy Terms which have the same "Term Name" (with different TID).
And I need to make term relations between all the terms with the same term name.

For example:

    term-A (tid=1)
    term-A (tid=2)
    term-A (tid=3)
    term-B (tid=4)
    term-B (tid=5)
    term-B (tid=6)

Then I would like to make term relations between term A and also between term B

Is there any way I can do this automatically?
As I have thousands of this kind of terms it's not realistic to do it manually.

I don't think you really want to just display the related terms. Thats a complicated band-aid to a problem you probably would be better off actually solving.
This type of problematic data is often encountered as part of a migration so it is definitely do-able in a migration like process.
Steps:

Decide which tid is going to be authoritative.
Find all duplicates of that term.
Re-assign all references to that duplicate term to the
authoritative term.

Install the Taxonomy dupecheck module so you don't get in this kind of trouble again. Some details from its project page:

Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.
The module provides a configuration screen allowing administrators to choose which should be unique: taxonomy terms, vocabularies or both. It defaults to case-insensitive comparisons, with an option to change to case-sensitive. Both stored and input terms/vocabularies are trimmed before comparison to handle cases such as 'foo ' and 'foo'. Based on the settings, the user will see an error message when adding a duplicate value.
Caveat: due to the inability of hook_taxonomy_term_presave() to stop the saving process, this only works in the taxonomy term and vocabulary forms. If you want to prevent duplicates through other entry points, this module will not prevent that. If someone knows a way around that I will happily add that in, as that was the original plan.


Set select list default value I have select list with options:

$options = array(0 => '0', 500 => '500', 1000 => '1000');

I'm trying to set it's default value to 500:

$form['price']['min']['#options'] = $options;
$form['price']['min']['#default_value'] = 500;

But this don't work.

I've never seen this problem. That default value should work. I would say try making the key a string and set #default_value as a string. The #options array may be being passed through array_merge  somewhere, thus rekeying integer keys. If keys are strings then that shouldn't happen.
Currently, your array looks like this:

$options = array(
  0 => '0',
  500 => '500',
  1000 => '1000',
);

But passing that array through array_merge can reorganize those integer keys to be in sequential order:

$options = array(
  0 => '0',
  1 => '500',
  2 => '1000',
);

If that happens then the 500 key simply doesn't exist. This is because array_merge does not like to preserve integer keys, but you can use strings to prevent it.
So, I think your array should look more like this:

$options = array(
  '0' => '0',
  '500' => '500',
  '1000' => '1000',
);

Then you can set your #default_value:

$form['price']['min']['#default_value'] = '500';

Otherwise, is there anywhere else where the default_value may be being overridden?


Webform multipage - different page.tpl for different page Is it possible to use specific page.tpl for webform pages?

For example: page--form1.tpl for page 1 and page--form2.tpl for page 2.

I wanted to do this via URL but it's same on all pages.

Any ideas?

I don't think you can do this on page level. Can't you use form templates? In that case you could add your own theme functions. Here's an example:

/**
 * Implements hook_theme().
 */
function YOUR_TEMPLATE_OR_MODULE_theme() {
  // Add our own webform theme function, copied from
  // webform_form in webform.module.
  $theme = array(
    'webform_form_page' => array(
      'render element' => 'form',
      'template' => 'templates/webform-form',
      'pattern' => 'webform_form_[0-9]+_[0-9]+',
    ),
  );
  return $theme;
}

/**
 * Implements hook_webform_form_webform_client_form_alter().
 */
function YOUR_TEMPLATE_OR_MODULE_webform_form_webform_client_form_alter(&$form, &$form_state) {
  // Check if we are on another page then 1 in a webform.
  if (isset($form_state['storage']['page_num'])) {
    // Add our own theme including the page number.
    $form['#theme'][] = 'webform_form_' . $form['#node']->nid . '_' . $form_state['storage']['page_num'];
  }
}

You should now be able to create your own tpl file per form page. It would look something like this: webform-form-626-2.tpl where 626 is the node id and 2 is the page number. For the first page you should just use webform-form-626.tpl.php so it also functions as a fallback template.

I haven't tested this so you might need to tweak it a bit but I hope this puts you on the right way.


Creating Pay and Configure Products on Drupal Commerce I am using Commerce Product Option (https://drupal.org/project/commerce_option) module to create a customisable product.

I want a way in which the user can checkout and make payment for the product and then be allowed to customise it. What would be the ideal set of Rules for this scenario?

This module set only supports customizing the product prior to checkout. Achieving customization after checkout will require custom module development.


Entity Metadata Wrapper Save VS Node Save when invoked from hook_node_insert Can somebody shine a light into the difference of the two, in terms of their interaction with database when hook_node_insert() is invoked? The documentation explains that

  Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and node_save() goes out of scope.

In fact, when I tried doing node_save($node), it will give me an error.

However, if I was doing it this way,

$nodeWrapper = entity_metadata_wrapper('node', node_load($node->nid));
$nodeWrapper->title->set(t("Saved by Entity Save"));
$nodeWrapper->save();

It works just fine. Has the new node being committed into the database after the $nodeWrapper->save() was executed?

Essentially, there really isn't much difference between node_save() and the save() method of the entity metadata wrapper. Neither should however be used to save the node passed in as the argument to hook_node_insert().

The argument is passed by reference (since it's an object and all objects are passed by reference in later PHP versions), and any changes you make to it will be included when the node is saved by Drupal just after it's done calling the hook implementation.

Trying to manually save the same node again could trigger endless recursion into your hook_node_insert() implementation.

Just alter the node object as you see fit (setting the title in this case, though that is not a translatable string, so replace t() with check_plain()) and do nothing more.

If you need to do more complex alterations, the entity metadata wrapper could come in handy, but you must remember that any alterations you want to have saved must be performed on the node instance passed as a reference to hook_node_insert(). This means you can't node_load($node->nid) here first, since that would actually just create a new node object with data that's already in the database. If you do manage to save that node copy without ending up in a recursion loop, it would either mean that the node save already in progress - the reason hook_node_insert() was originally called - overwrites any changes you made, or fails because the new node to be saved already exists.

Instead, pass the $node argument to entity_metadata_wrapper() directly and the wrapper will be able to alter the correct node object for you, but remember to not call save() on the wrapper!


Template variable pre-process concept I am new to Drupal and I am trying to create a theme for it (Drupal 8). I have a few questions:

What does it mean to pre-process a variable?
Do all variables have to be pre-processed?
How do you figure out how to pre-process a variable? I understand some come from the Drupal config. Where else can variables come from?

I have read a few articles and searched the Internet but it seems Drupal  8 documentation is still being worked on. It's not very explanatory. Are there any articles you can suggest to learn how to theme Drupal 8 from the ground up?

Thank you

Preprocessing is just an optional step between defining a render array that will then use a twig template and the actual twig template.

It's a place where you can execute PHP code to prepare variables that you can later use in your template.

You don't have to use preprocess for you own templates but some things can only be done there or are a lot easier, as you can't execute arbitrary code in a twig template.

See template_preprocess_image() for an example. Note the different names of preprocess functions. There's always the one prefixed with template. That's reserved for the module that defines template in hook_theme() and is called first. And then it's called for each module and active theme, just like a hook, e.g. as yourmodule_preprocess_image.

That brings me to another advantage of the preprocess phase. There can only be one template that's actually used and while there are ways, modules in general shouldn't provide template unless they define it. But, every module can implement the preprocess function and influence the output of a template to a certain degree. For example to add a certain class or data attribute to a node so that some JS can then use it.


How to switch logo and menu links based on subdomain? my D7 site will be accessible from 4 different subdomains:
- a.site.com
- b.site.com
- c.site.com
- www.site.com (or just site.com)

I already enabled a domain cookie for .site.com and the login works across all subdomains.

Now I want to be able to show a different logo logo based on the subdomain and I also want to be able to switch the main menu links.

I tried the context module but didn't find a way to detect the subdomain.

I don't want to use the domain access module. I was thinking about modifying the theme to switch the logos. Can I do the same for the menu links?

Does anyone have a  better idea?

I am unaware of any contrib modules that do this (well, other than Domain Access), but it would be pretty trivial to write a little custom code to accomplish it.

Essentially, you would add something to your theme preprocess to detect the domain and tack on body classes.  How to do this depends on whether you are using Drupal 6 or Drupal 7.  Either method, though, would use $_SERVER["HTTP_HOST"] to detect the theme.

Then, in your CSS you would preface your logo rules with body.whatever to choose the correct one.

The menu thing is a little trickier.  You would use essentially the same logic, but set a variable containing the proper menu and print this out in your theme.  To be honest, though, I really would use Domain Access for this if you are using Panels.  The domain shows up as a panel selection rule, so you can do all of this from the UI.


Adding dynamic and multiple fields for user profile using profile2 module in Drupal 7 I am creating profile like linkedin.
Where user can have multiple education fileds and he can add/modify dynamically.
Is there any plugin which suits my requirements.

The nearest I found is profile2 which is promising but does not provide me multiple entry functionality.

Can Drupal help me out how to fix this problem?

Thanks in Advance.
Yatendra

Edit : I want profile types like linkedin education wizard. i.e. if user had entered education detail one time then there should be two option first one for editing education detail and second one for adding more education detail.

Old question, but I have to say that Ankit's comment was on the right track. Install and enable Field Collection, because you will use this to group each instance of your education details fields.

Depending on whether or not you use Profile 2, create a Field Collection-type field at /admin/config/people/accounts/fields or /admin/structure/profiles/manage/<profile_type>/fields. The number of values for the field collection field should be greater than one or unlimited. Finally, create your education details fields at /admin/structure/field-collections/<field_collection>/fields.


How to enable users to add content only from some pages (and only once) in  Drupal 7 i currently need to implement this use case in drupal.

We have two different type of users: registered users and moderators.

I need to do the following:

registered users can add only one
particular content type: videoCV (no
help needed on this subject)
registered users can add this content
only from a pre-definite page called
"Create you Video CV" (the page is
accessible in the main menu) and only
once
moderators can add contents wherever
they want.

so i need on these points:

how to limit to registered users the
possibility to add content only on
one page?I mean have the link add
new content only on that page? (and
also change that link so that it
reads add your videoCV
how to limit users so that they can
add just one content?

any help is appreciated, i think i can solve point number 1 withouth particular coding, but i think i need to create a custom module for point number 2, that is no problem!

Content Profile module usually bounds the users to create exactly one node of some content type that has been marked as Content Profile.

May this help you in this regard.


How to remove a taxonomy vocabulary via database query To manually remove a taxonomy vocabulary in the database, what tables/columns etcetera do I need to delete or modify?

I have a "ghost" taxonomy - it shows up in the list, but doesn't exist anywhere else. I cannot edit it through the website admin - it says page doesn't exist. I can't delete it by using drush entup

But I must remove this somehow, as it's disrupting the website with errors...

  LogicException: Missing bundle entity, entity type taxonomy_vocabulary, entity id Regions

As a hook_update_n solution didn't work, and installing a module to do 'drush entup' didn't work... where can I remove this from the database? I had the team in charge of the database itself do a search and pull this result:

I'm assuming that first result is for the block structure, and unrelated to my taxonomy. But maybe someone sees an issue with the results below it, or if we can safely delete those to get rid of this 'ghost' taxonomy?

From the world of weird solutions that work...

I tried using a module and 'drush entup' ... didn't work
I tried creating a module to use 'hook_update_N' to delete it ... didn't work
I tried using hook_update_N to Create it, so I could then delete it
... didn't work.

On a whim, I went to the admin page, listing taxonomies. I dragged the 'ghost' taxonomy to rearrange the list. Then I saved. Suddenly, all the options to edit it had returned. I was finally able to delete the taxonomy using the usual dropdown field.


Avoid hard crash if user searches when Solr stopped I use search_api_solr with a server-based Solr installation. Works fine. For reasons I won't explain, the Solr service is stopped sometimes. If a user does a search while Solr is stopped, they crash with "The website encountered an unexpected error."

The error log  says "Drupal\search_api_solr\SearchApiSolrException: An error occurred while trying to search with Solr: Solr endpoint http://localhost:8983/ unreachable or returned unexpected response code "0"." No surprise, since the service is stopped.

How can I trap this error and display a "Search isn't working" page instead of crashing? Seems like there should be a way to intercept it, but I haven't figured it out.

Based on the comment by @4k4 and post at https://drupal.stackexchange.com/a/235942/70681 and further reading, I used my existing custom module (rsc) to solve the problem as follows:

In modules/custom/rsc/rsc.services.yml

services:
  rsc.event.SolrException:
    class: Drupal\rsc\EventSubscriber\rscSolrException
    tags:
      - { name: event_subscriber }

In modules/custom/rsc/src/EventSubscriber/rscSolrException.php

<?php
namespace Drupal\rsc\EventSubscriber;

use Drupal\search_api_solr\SearchApiSolrException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RedirectResponse;

class rscSolrException implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::EXCEPTION][] = ['onException', 60];
    return $events;
  }

  public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof SearchApiSolrException) {
      $event->setResponse(new RedirectResponse('/search-not-working'));
    }
  }
}

When a Solr exception occurs, users are redirected to the search-not-working page instead of to "The website encountered an unexpected error." Much nicer.


Is it possible to change the fields' names of the JSON generated by Services module? I have a mobile app, which calls a legacy system's HTTP REST interface. Now I replaced the legacy system with Drupal and Services module. I forgot setting field machine name to match mobile app client, however, there is no chance to modify the mobile app. So, as I asked in the title: is there a way to change the fields' names of the JSON generated by Services module?

You can use hook_services_request_postprocess_alter(): http://cgit.drupalcode.org/services/tree/docs/services.alter.api.php?h=7.x-3.x

For example, say you wanted to replace the node title property with nodeTitle when a node is being retrieved, you can do so like this:

/**
 * Implements hook_services_request_postprocess_alter().
 */
function my_module_services_request_postprocess_alter($controller, $args, &$result) {
  if ($controller['callback'] == '_node_resource_retrieve') {
    $result->nodeTitle = $result->title;
    unset($result->title);
  }
}


views with multiple contextual filters - should return data only when both or any one filter is present Views of content is having two contextual filter. For some reason node object is available to views so it is passing through url's 7th argument.

1.Content: Has taxonomy term ID
Configuration: Php Code

$nid = arg(7);
$node = node_load($nid);
if($node && isset($node->field_tags)) {
      $related = field_get_items('node', $node, 'field_tags');//dpm($related);
      foreach($related as $tag) {
          $view_par[] = $tag['tid'];
          //dpm($tag);
      }
return implode(',', $view_par);
}
else{
return 0;
}

2.Content: Nid (Ref: entity-reference-and-nested-arguments-in-views)

$nid = arg(7);
$node = node_load($nid);
$Related_ids = array ();
    $Related = field_get_items ('node', $node, 'field_some_er')    // Get the entity reference scope
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related[$ i]['target_id'];
      }
    }
    return implode ('+', $related_ids) // It returns the values of the field entity reference

Relationships:

Content: Taxonomy terms on node (Require this relationship :TRUE)
Content entity referenced from field_er_in_content (Require this relationship :TRUE)

With above configuration/modifying how to retrieve views's data only when

1. Any one of the filter should be present i.e either field_tags(term reference field) or field_some_er (entityreference field)
2. Both filter could be present.

but should not retrieve when both value is absent. Is there something can be done using common variable like found flag that can be shared to both php code and break the view operation.

Perhaps this is what you're looking for:
https://www.drupal.org/node/1871388

Otherwise, it looks like you might want to set up what your contextual filters do when the arguments  are not available:

https://www.drupal.org/node/1578574


How do I target different types of anonymous user after a gateway page? So there are a whole bunch of useful tools in Drupal for changing how a website looks depending on a number of factors, including which page you're on, what roles you have, whether you're logged in or not:

Page Manager (part of Chaos Tools in Drupal 7), and the contexts provided within (found a freaking awesome tutorial on this stuff here)
Context
Domain Access and various others like it
Organic Groups

But I can't seem to figure out how to make the following use case work:

Anonymous user visits site

a. If user has never been to the site before (on this browser/computer), ask whether they are A or B

b. If user has been to the site before, figure out whether they are A or B (should be easy enough with cookies/session variables)
Change how site looks depending on whether user is A or B

It's really easy once they log in, but how do I tell anonymous users apart?

I tried installing ctools cookie context and ctools session context in the hope that I could use these to provide the necessary hooks for visibility settings in page manager... but visibility settings don't seem to use contexts!

Surely somebody has tried to do this before me?  Maybe I am googling the wrong words but I've been at this for several days without a clear idea yet.

Typical, no sooner than writing up my question do I find an answer.  Though I'd love to hear if there are better ideas.

I discovered that you can use php to check the contexts in visibility settings.  I didn't want to do this because I don't want to give the site admin access to php.  However, I can make a couple of ctools access rulesets and make those available to the site admin to control visibility.

I haven't tried it yet but I think this will work, as long as the ctools context plugins work as I think they should.

[edit: it worked]


How to deal with module conflicts ("anti-dependencies")? I have a module that specifically doesn't work with another module. I want to know if there is a way to check if that module is enabled and abort installation for example or gray out the installation box so that my module can only be installed if that other module is disabled.

It's like inverse dependencies!

Is there any way of doing this properly in Drupal?

The module just needs to implement hook_requirements(); a requirement could be that a module is not installed, and if the module returnes an error from hook_requirements(), then it will not be installed.

The module should implement code similar to the following one:

function mymodule_requirements($phase) {
  $requirements = array();
  // Ensure translations don't break at install time
  $t = get_t();

  if ($phase == 'install') {
    if (module_exists('other_module')) {
      $requirements['mymodule'] = array(
        'title' => $t('My module'),
        'value' => $t('My module is not compatible with Other module.'),
        'severity' => REQUIREMENT_ERROR,
      );
    }
  }

  return $requirements;
}


How to store multiple values in a profile field (specific to each users)? I have a profile filed called Amount corresponding to each users, and I want to store multiple values in the profile field Amount. Bu using the custom module, the value of Amount is to be inserted on each registration (or it can be inserted any time by a cron program).

For example User Williams has Value 100 in his Amount field. This is not a single value, it may be

Time    Amount
-------+------
Hour 1 :  10
Hour 2 :  30
Hour 3 :  20
Hour 4 :  35
Hour 5 :   5
============
Total  : 100

I want to display the total amount and individual amount by exact time.

How to do it?

You might be best installing content profile as this will allow you to use cck, when creating the profile field amount you can set it to unlimited which would allow you to store multiple values in an array for a single field.

The total would be another dynamic field which is calculated by adding the values from the amount array each time they are changed via a hook

To add the field to a content profile, follow the below steps:

Edit the profile content type
Go to manage fields
Add a new "text field
Fill in field details
On this page you will see a "number of values" option, choose "unlimited"

You can update content profile fields as below, just put it in a custom module or something:

//load current user
global $user;
//find the users content profile
$uid = $user->uid;
$node = content_profile_load(profile,$uid);
$pid = $node->nid;
$node = node_load($pid);
//update the field AMOUNT
$node->field_AMOUNT[0]['value'] = $var1;
$node->field_AMOUNT[1]['value'] = $var2;
//do the same for the TOTAL with calculations
$node->field_TOTAL[0]['value'] = $var1 + $var2;
//save the content profile node
node_save($node);


How to fix Zen theme only showing correct breadcrumbs with theme developer module enabled? I've been going around in circles with trying to get breadcrumbs working as the client wants them on a Drupal 7 site with a custom Zen theme working. I've built the site out and it requires the titles being added to the breadcrumb trail.

The issue is, the crumbs only display correctly with the theme developer module enabled. I know you can set the Zen theme's settings to append content titles to the breadcrumb trail, but this doesn't seem to work (either through specifying through the UI, or by changing the settings in the MYTHEME.info file). They do however correctly display with the theme developer module enabled. For a host of reasons I can't have a live site with this module enabled.

So,

1) How do I get the breadcrumbs working properly and why doesn't it work through the UI or in code?
2) How can I resolve this apparent conflict?

So, apparently there is a conflict between the Path Breadcrumb module and zen's built in breadcrumbs. When the Path Breadcrumb module is enabled, the zen breadcrumb doesn't append the title to the path. I'm assuming that Path Breadcrumb hooks into and overrides the drupal_get_breadcrumb(), although I haven't been able to demonstrate this myself. When I disable Path Breadcrumb, the zen breadcrumbs behave normally. This leaves me with two viable options: 1) hack the current status of the theme breadcrumbs, 2) or code Path Breadcrumbs for the rest of my pages. Neither options seems particularly palatable.


Programmatically Updating Taxonomy Term I'm looking for a better way to update a set of taxonomy terms. It's currently causing cron to hang which slows down the site substantially.

    //Look through all of the stocks
    foreach ($terms_data as $symbol => $data) {
        //Check to see if term exists in the default vocabulary
        $matching_terms = taxonomy_get_term_by_name($symbol, __DEFAULT_VOCAB_MACHINE_NAME);

        //Loop through existing term(s)
        foreach ($matching_terms as $term) {
            //Load the new vocab term
            $new_term_data = taxonomy_term_load($term->tid);
            foreach ($data as $k => $v) {
                //Add in the new data
                $field_name = substr("field_".$k, 0, 31);
                $new_term_data->{"$field_name"}['und'][0]['value'] = $v;
            }
            taxonomy_term_save($new_term_data);
        }
    } //endforeach

The only way I could figure out how to get it to work was to:

Find the term that matches the $symbol variable
Loop through the matching term (1 term)
Create a new term
Update the exact fields
Save overtop of the old term

I know there has to be a better way to do this. Any ideas? Thanks in advance!

For those of you interested: the bottleneck is in the taxonomy_term_save() function.

Following the trail, it led me to the field_sql_storage module (in core) which deletes an existing row and then inserts it. It should really use the built in DB Driver functionality and UPSERT instead of deleting and then inserting.

Working issues (for D8 only):

https://www.drupal.org/node/1800286#comment-9356897
https://www.drupal.org/node/2239071

As of writing this, no patches have been applied yet. Updating large sets of taxonomy terms will lock up your DB.


Need to sort views block by current node first So what I'm doing is setting up a block with images that link to it's corresponding testimonial page.  Each testimonials has it's own node, and I want to sort the block so that the first image in the block is the one that links to the current testimonial page that the user is on. For example:

I have testimonials from:

Student A
Student B
Student C
Student D

If I'm on the page for Student C then the order of the block should be:

Student C
Student A
Student B
Student D

Anyone have a good way to do this?

A quick solution might be using the module Views PHP.

As far as I understand your problem, you want to sort a list but have the current student at the top.

I used a Content Type name 'Students' with a integer field 'Rank', representing the field to sort the students.

Create your view and a block and set up your view as follows:

Format: as you like, no grouping
Show: Fields, no special settings
Fields:

Content: Nid (exclude from display)
Content: Title
Content: Rank

Filter Critera

Content: Published (yes)
Content: Type (= Student)

Sort Criteria:

Content: Rank (asc)
Global: PHP (asc) -> this is from the Views PHP module

Configure the Views PHP filter similar to this:
Sort Code (no php tags!):

$nidFirst = arg(1);
return $row1->nid != $nidFirst;

That's it. Embed the resulting block on your students page and navigate to one of those pages.

Sort criteria 1 gets the result into the default order, e.g. best rank is on top.
Sort criteria 2 fetches the current students node id (nid) from the url (assuminf it realy is the first argument), compares it to each row and returns true, if the rows nid is not equal to the current students nid.
As the sort direction is ascending, all rows with a comparison result of true will be moved below the row with the result false, so the current student ends up at the top of the list.


What difference between declaration of an ajax callback function with $this and without it? There is a form working with AJAX Framework. And there is a form element having the callback function named "myFunction", which is a public method of the form class.
The callback can be declared as

'callback' => [$this, 'myFunction']

And it also can be declared as

'callback' =>  '::myFunction'

Could you clarify me, what functional difference between these declarations ?

The ::method as a string is a special feature of the form API.

It's basically a shorthand for [$this, 'method'] and does almost exactly the same. See FormState::prepareCallback

There is one interesting difference, [$this, 'method'] has to serialize the whole form object within the form structure, to then unserialize it to call a method on it. But at that point, on a cached request, it is actually a different object because the form system also created a new form object, as part of initializing it and starting to process the request. ::method will actually call the method on the new form object.

Whenever possible, use the short version, sometimes that's not possible, for example when you are inside a plugin (e.g. a field widget) or other class called by the form, in this case, it is recommend to use a static method.


Force initialization of custom field set in CiviCRM I have created a custom fieldset "Social Profile" in CiviCRM which contains one Yes/No field "Publish my profile" that is set to Yes (value 1) by default. If i edit the fieldset in one contact, i can see my default value is working fine.

Then, I have created a membership page that allow people to become new members. When they fill the form a new CiviCRM contact is created. The form doesn't contains the "Social Profile".

When a new member register, the information Publish my profile is not initialized. After verification, it seems that the custom fieldset is not initialized for the contact - no data in civicrm_value_xx for entity_id = <NEW_CONTACT_ID>

So my question : Is there a way to force initialization of the custom field set for a new contact ?

Can you include 'publish my profile' custom field in your membership page?
If option 1 is not possible, the next best bet might be to implement the civicrm postProcess hook on membership form and create the custom field record in the form.

Civi only creates custom field records on a as needed basis

alternatively you might be able to do the above via use of mysql triggers (maybe on creation of a contact record?)


Limiting allowed HTML tags in comments only I can't figure out how I can limit my text format or HTML codes for the comment sections on a node. If I edit the input formats with user roles, it edits the entire thing, including the node body and other fields.

For example, I want to have filtered text on the body field of a node, but only plain text (or other custom text format) in the comments section.

The problem I'm running into is that I have added <embed>, <param>, <iframe>, <object> into the allowed HTML tags field in my filtered text format settings, but this also allows users to post Youtube videos into the comments section, and I don't want that.

How can I do this?

You need to create two "Filtered Text" formats, one that is used by people with the access to post nodes and one for comments.

If you can't separate the two forms by access control (e.g. users are allowed to post nodes and comments, but shouldn't be allowed to post videos in comments), you could use hook_form_alter() in a custom module to limit the allowed filters for the comment form.


How to create a rule to automatically assign users to different profile 2 types? I'm working on a project where different people can register.

1) Only certain domains can register. I've used the User restrictions module for this purpose.

2) Admins can create files/resources and assign them to different people. To accomplish this, I installed Profile2 module and created an entity reference field in my custom content type where admins can decide which profile types can view this resource.

My problem is now I'm trying to come up with a rule that when somebody registers, based on the domain name of their email address, I'd like to associate them to different profile types.

Is that possible?

Below is a potential solution for your "... based on the domain name of their email address, I'd like to associate them to different profile types ...").

You might want to try using the Conditional Rules module: use an "if condition" (contained in the Rules Action), and the Rules Action "... to associate them to different profile types ..." would only be executed if the "if condition" would be true. For a sample using the Conditional Rules module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Instead of using Conditional (if/else) logic within the Rules Action, you can also use Switch logic.

Be aware: this module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).


How to use stye attribute in custom block markup? I'm developing a custom block in Drupal 8. In my build() method I've got:

$progress_markup = array(
  '#theme' => 'progress_bar',
  '#percentage' => $registration_percentage,
  '#message' => array('#markup' => $registration_node_count . ' of ' . $this->configuration['capacity']),
);
$markup = \Drupal::theme()->render('progress_bar', $progress_markup);

This generates the following HTML:

%

30 of 120

However, when the block renders on the page, the style attribute has been removed. Here's the relevant D8 issue.

What I don't understand is: if I create a custom block and use Full HTML, and paste in the generated markup that contains the style attribute, Drupal 8 will happily render it. But when I generate this markup in the build() method, it gets removed.

Is there a way to specify, in the block plugin definition, that the build() method should not filter out any HTML? Any other thoughts on how ot get around this issue?

This is a working example of adding the style attribute to the render array of a block via the build() method.

<?php
/**
 * @file
 * Contains Drupal\foo\Plugin\Block\FooBlock
 */

namespace Drupal\foo\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * @block(
 *   id = "foo",
 *   admin_label = @Translation("Foo block")
 * )
 */
class FooBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * If a block should not be rendered because it has no content, then this
   * method must also ensure to return no content: it must then only return an
   * empty array, or an empty array with #cache set (with cacheability metadata
   * indicating the circumstances for it being empty).
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    return [
      'inside' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => 'Hello world',
        '#attributes' => [
          'class' => ['some-class'],
          'style' => ['color:red']
        ]
      ]
    ];
  }
}


Dashboard is empty for roles apart from admin I want to create a role specific dashboard on drupal 7.
So I have added some blocks on the dashboard and also the "View dashboard" permission for this role.
However,when I login using the above role,the dashboard is empty.
What is the reason for this and how can I fix that?
P.S.Admin can see these blocks on dashboard

May be you have assign blocks to the region of non admin theme. If so, you have to assign the blocks to the region of admin theme(seven or enabled admin theme in your drupal system).


Is there a way to park a domain name to a single Drupal node? Is it possible to set up a Drupal website so that other domain names can go to specific nodes but show the domain name instead of the natural URL in the address bar? Can I use the Domain module, or some other method, so that example2.com goes to example.com/page2 but still shows example2.com in the address bar?

Any internal links still go to example.com/whatever, and that's fine. The page is designed as a one page unbranded website.

I already have the domain (example2.com) pointed to our servers (example.com) and have some familiarity with setting up vhosts in apache if needed as part of the Domain module set up. I'm not sure if I'm understanding what this module does and if it will do this job. I've also posted on Server Fault but am not getting anywhere because I think I'm not asking the question properly.

Drupal 7.59. Debian and Apache

I was able to set different domain-based landing pages for existing nodes of our main site using the Domain module. This module is fairly complex and will either be exactly what you need, or not.

Our use case is that we have multiple one-page partner projects, such as campaigns, that need their own domain name but that share content from our regular website, such as our blogs.

The following are the steps taken for Drupal 7.

Be sure to read the entire readme file, the quick install and the install instructions before starting. There are many variables specific to your use case and environment.

Step 1

In order to use it, you will need to be able to configure the domains on the server to reference the primary website's docroot. In my case, that means I needed to point the domains over to the same server, and set up different vhost files as follows:

<VirtualHost *:80>
        DocumentRoot "/var/www/html/example/docroot"
        ServerName example2.com
</VirtualHost>

Step 2

You will then need to add some code to your sites/default/settings.php. Make sure the path is correct, according to your set up.

/**
 * Add the domain module setup routine.
 */
include DRUPAL_ROOT . '/sites/all/modules/contrib/domain/settings.inc';

Step 3

Once this is done, install the domain module and enable only the domain module, but none of the submodules yet. Then rebuild permissions (/admin/reports/status/rebuild). Then enable the domain_conf anddomain_settings and any others. Once enabled, set your primary domain to default.

Step 4

Add your new domains by clicking on "Create domain"

Step 5

In order for the blog and other relative links to go back to the primary domain, I needed to set the following in advanced settings (Structure > Domains > Settings):

(Here, FosterClub is my primary domain).

After this, there are other sub-modules you can enable to further customize what you need to accomplish. Be sure to set your permissions. You are also able to assign domain access to specific roles and users, which allows them to edit and create content restricted to specific domains, using the "edit domain content" permission, with the domain_content sub-module:

This is a screenshot of settings under a specific user.


Why the content of a block created in an external module does not appear? I am creating a module for wich i need to create a block with php code. I`m making it as follow:

function my_modulo_block_info() {
   $blocks = array();
   $blocks['start'] = array(
      'title' => 'Start',
      'info' => t('The start block'),
      'status' => TRUE,
      'region' => 'content',
   );
   return $blocks;
}

function my_modulo_block_view($delta='') {
   $block = array();
   switch($delta) {
      case 'start' :
         $block['content'] = '<?php echo "Hello world"; ?>';
         break;
   }
   return $block;
}

But i see only the block name on the page, it dont print Hello world. Any body know why?

call a php function to built block-content, in hook_view code should be:

//construct your output as a function
$block['content'] = myfunctionname(); // this function is called 3 lines below
....
return $block;
//then call your output content function
function myfunctionname() {
$output = 'whatever you want(arrays, functions, html, more php, ....)'
 };
 return $output;

that will return $output as your content.


Where does drupal store LDAP server information? I am looking for the location where drupal stores the LDAP server once it is set in the website.

By default Drupal doesn't store any LDAP server information.
If anything is stored by other modules, it's stored in the database.
Depending on different modules, these data is saved in different tables.

If you're using LDAP module for Drupal 7, you can find the settings in ldap_servers table.

If you're using LDAP module for Drupal 6, you can find the settings in ldapauth table.


Update field value without edit page I need to create a button that will allow a user to update a field value on a node without accessing the edit page. I'm using access control to limit access to the node, and roles which could define which user sees the button. The field I need to update is a custom pick list.

Is there a module to do this? I can't find one. THANKS!

(More info on my specific implementation)

My site allows users to list resources for other users to book. When a user wishes to book an item, he creates a new node (Booking). The owner of the resource is also given access to this node. Here, they can comment and exchange files (attachments) to work out the details. This node has a field called "Stage", which starts as "Pending". Once the owner has confirmed the details of the booking, I want him to be able to click "Approve" on the booking node, changing the status to "Approved". When the resource has been returned, the owner should hit a "Completed" button, changing the status to "Complete". I'd also like both users to see a "Cancel" button at all times.

See editablefields module.

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).


Need to change User Pages Title and Breadcrumb in drupal 7? I want to change Title and breadcrumb for user pages to username to My Account.
I don't want to user drupal_set_title or drupal_set_breadcrumb bcoz its in lots of pages

I saw below code in user core module

  $items['user/%user'] = array(
        'title' => 'My account',
        'title callback' => 'user_page_title',
        'title arguments' => array(1),
        'page callback' => 'user_view_page',
        'page arguments' => array(1),
        'access callback' => 'user_view_access',
        'access arguments' => array(1),
        // By assigning a different menu name, this item (and all registered child
        // paths) are no longer considered as children of 'user'. When accessing the
        // user account pages, the preferred menu link that is used to build the
        // active trail (breadcrumb) will be found in this menu (unless there is
        // more specific link), so the link to 'user' will not be in the breadcrumb.
        'menu_name' => 'navigation',
      );

/**
 * Menu item title callback - use the user name.
 */
function user_page_title($account) {
  return is_object($account) ? format_username($account) : '';
}

User menu is calling title callback function and set the user name in that callback function. So i have tried hook_menu_alter to change title callback of user menu but it is not working

My Code

function health_portal_menu_alter(&$items) {
  $items['user/%user']['title callback'] = 'health_portal_user_menu_title';
}

function health_portal_user_menu_title() {
  return 'Test';
}

Anybody tell me what is wrong with this code and what i do?

Thanks

Before trying to implement through code, give a try to these modules:

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

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


How to edit Calendar title Module: https://www.drupal.org/project/calendar

I wan to remove Saturday. Only display August 1, 2015.

Picture below show that I already change some setting, but not working at all.

What should I do? Many Thanks.

The format of the pager header can be modified on the date view configuration page admin/config/regional/date-time/date-views. On that page, find the format that you wish to update, in your case Date views day format with year, which by default is l, F j, Y.

Update that value to be F j, Y, since l returns the weekday, and your date will show as you need it.


Get Json From Module I have to create a module that return a list of my language, only the list without template,and I have to call this url via curl

I create something like this ( inside my module )

function my_module_menu() {
  $items['my_module'] = array( //URL
    'page callback' => 'get_all_languages',
    'access arguments' => array(''),
  );
  return $items;
}

/**
 * @return string
 */
function get_all_languages() {
    $out = array();
    $result = language_list('enabled');
    foreach ($result as $key => $value) {
      foreach ($value as $k => $v) {
        $out[$v->language] = $v->name;
      }
    }

    $p = json_encode($out);
    print $p;
    drupal_exit();
}

I tried also

  drupal_add_http_header('Content-Type', 'application/json');
  $p = drupal_json_encode($out);

But this url is not Json infact if call this url by Curl, I can see all the template.
I want to have the result like using this module, or can i Create a view that use my module result?

I have another problem when use curl, my content is

  You are not authorized to access this page.

Pretty close; here's the correct way:

/**
 * Implements hook_menu().
 */
function YOURMODULE_menu() {
  $items['languages'] = array(
    'page callback' => 'YOURMODULE_languages_enabled_json',
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Render enabled languages in JSON.
 */
function YOURMODULE_languages_enabled_json() {
  $out = array();
  foreach (language_list('enabled') as $languages) {
    foreach ($languages as $language) {
      $out[$language->language] = $language->name;
    }
  }
  drupal_json_output($out);
}

The important piece is https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_output/7 which should be used for JavaScript callback functions returning data in JSON format, and it sets the header for the JavaScript output.


Solve "Cron run failed" without Watchdog Some years ago i wanted to turn off watchdog because it's memory and db consumption, but today i need info about why my cron isn't running because need to use Search module from now?

Trying to run cron manually (admin/reports/status/run-cron) return

  Cron run failed.

calling /cron.php and running from server's command line has no return,

How can i debug this?

or

There is any other way to turn on logging?

  admin/settings/logging/dblog

has no return

SELECT * FROM `watchdog`

MySQL returned an empty result set

function watchdog()

still there in bootstrap.inc

settings.php and .htaccess free from any relevant "error", "watch", "dog", "bdlog", "repor" keywords (have no php.ini)

  /modules/dblog/dblog.module

still untouched. XML sitemap and Search is disabled

No logging, no cron, i am puzzled. Thanks for any help.

To enable the recording of the watchdog() messages, you just need to enable the Database logging module (short name: dblog). Once you enable it, on admin/reports/dblog you will start reading the recent log entries.

As for the possible error that could return cron, they are the following ones:

Cron has been running for more than an hour and is most likely stuck
Cron is already running and you try to re-run it

This is evident from Drupal code. The function that is executed when you go to admin/reports/status/run-cron is system_cron_run(), which returns the error you are seeing when drupal_cron_run() doesn't return TRUE. This is that function code.

  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
  }

  // Fetch the cron semaphore
  $semaphore = variable_get('cron_semaphore', FALSE);

  if ($semaphore) {
    if (time() - $semaphore > 3600) {
      // Either cron has been running for more than an hour or the semaphore
      // was not reset due to a database error.
      watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);

      // Release cron semaphore
      variable_del('cron_semaphore');
    }
    else {
      // Cron is still running normally.
      watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
    }
  }
  else {
    // Register shutdown callback
    register_shutdown_function('drupal_cron_cleanup');

    // Lock cron semaphore
    variable_set('cron_semaphore', time());

    // Iterate through the modules calling their cron handlers (if any):
    module_invoke_all('cron');

    // Record cron time
    variable_set('cron_last', time());
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

    // Release cron semaphore
    variable_del('cron_semaphore');

    // Return TRUE so other functions can check if it did run successfully
    return TRUE;
  }

As for why Drupal thinks cron is still running, that happens when an error in the code (generally one of the hook_cron() implementations) doesn't permit drupal_cron_run() to execute the following line:

    // Release cron semaphore
    variable_del('cron_semaphore');

This means that to debug why cron doesn't work properly, you need to check any hook_cron() implementation, and see what is wrong with them. The problem could also be an implementation of hook_node_view() which is wrongly calling drupal_goto().


Commerce File won't let anyone download files I've got a website running Drupal 7.32 with Drupal Commerce. I want to let users download files so I've got the Commerce Licence and Commerce File modules installed and I've them working for a while, and then I updated everything to the latest versions and now I can not download any files that have been licensed - even as the administrator. All I get is an access denied page whenever I try to click the download link, but the link does appear in the View for licensed files.

I have checked the permissions and everything there seems correct - and I've also look at the following issue, which is the issue I am having, with no avail: https://www.drupal.org/node/1288156

Does anyone have a solution to this problem or even a work around?

Thanks in advance

In case anybody else runs into this problem, I managed to solve this issue by applying a patch for the generation of the access token, found here.

In breif, the patch is needed because the latest update to the File Entity module (which Commerce File utilises) changes the way that access tokens are generated and Commerce File has not yet been updated to account for this.


Receive a file with Drupal 7 I have a java application that will send a CSV file to a Drupal 7 site through using POST method.

how i receive file on drupal side by using custom module

I need to parse the file to add data into a custom table.

I will try again:

you can var_dump($_POST); to get all posted variables on the site and know the array index in which your application POST's


Views: list all nodes based on relationship I have a datastructure where "Courses" has many "Activities". I've accomplished this by using entity reference to add a course_field to the activity content type.

I am pretty conused, however, as to how to set up a view listing all activities belonging to a certain course.

I've created a view that displays activities and I've set the relationship on the view to "Entity Reference: Referenced Entity". I am a bit confused though, as to whether I should set it to "Entity Reference: Referencing Entity", but I figured the first one made more sense as activities are referencing courses with a field on the activity model.

Now I set the contextual filter to "Content: Course", but when I preview the contextual filter, typing the name of one of the courses does not filter the activities.

What is the correct way to filter activities according to what course they belong to?

You are correct in setting your relationship as "Entity Reference: Referenced Entity". To recap: you have a view of nodes filtered by Activity. Activity has the entity relationship field that references Course. The direction is from Activity to Course and you are building a bridge from activities to course.

Normally one would set the contextual filter up as node:nid. As you want to list all activities associated with a course, you therefore need to pass in a context that uniquely identifies the Course. Nid fits this perfectly. The nid coming in as the contextual filter needs to be of type Course. So how do you tell Views. You already have a bridge from activities to course (your relationship), and to indicate to views that the nid contextual filter is of type Course you set the relationship that you added on it. Using nid as contextual filter makes more sense in most cases, as it is the unique identifier. It could be taken from the url as a default, or could be sent in via a panel etc.

You can if you wish add another field as the contextual filter, as in the title (it may or may not be unique). But always you will need to add the relationship to the contextual filter to identify the context as belonging to Course.

Now to explain what you did with setting the contextual filter to 'Content Course'. You added the field that appears on the Activity type and which is your entity relationship field to Course, as the contextual filter. This field does not exist in the Course type, so you will never get a result from it. As you want to show a view of activities associated with a Course type, you have to add the relationship that links activities with courses (which you did), and then your contextual filter has to be of a field that appears in Course type. So you must first select a field that does indeed appear in Course type, and then you have to tell Views to use the relationship on that field (remember, your relationship takes you from an Activity type, which is the begin-point, to the Course type, which is an end-point, and your context needs to be on the end-type). Imagine using the nid or the title as the contextual filter. Both course and activity have both of these fields, so which type's should Views use?

The relationship is also considered when adding Fields, Filter Criteria, and Sort Criteria on your view. You have to decide whether the field, filter, or sort belongs to your base type, or to a type that you are bringing in with a relationship.

For a brilliant video tutorial series on Views, have a look at Johan Falk's Taming the Beast: Learn Views with NodeOne


Hide block if content is empty not working I want to hide an entiere block is it has not result.

I went into my view, then I add "Contextual filter", "Empty", "Hide view".

But my view is always hidden if I do this, and I don't understand why... (I have content in this view, but it could be empty).

Do display my view, I'm using this : https://drupal-bootstrap.org/api/bootstrap/templates%21system%21region.html.twig/8

See my config :

Up solution :

In views, go to "advanced". At the very bottom, see "hide block if view is empty". Change it to yes and it will work.


How do I create a container entity that contains variable number of fields I am interested in creating a content type that contains a variable number of fields. Each field contains an entity reference to another entity, but as I said there may be one field or 4 fields. I'm a little unclear the best way to implement this

I'm not sure if I understand correctly what you want to achieve, but the following two modules come to my mind that could be helpful:

Field collection

  Field collection provides a field-collection field, to which any number of fields can be attached.

Field Group

  All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

I suppose in your case Field Group would actually be the more interesting module to look at. You can wrap a group of fields and you can then set the number of the field group to unlimited.

You can also have groups inside of groups. But things can actually get a bit 'messy' when editing a node with grouped groups.


Call to a member function getFileUri() on null in ImageItem::presave() I have a node migration as part of a D6->D8 migration, and for the image field in the node, I've done a separate files migration, and then in my node migration, I just refer to the files migration to get the destination fid and write that to the image field.

field_image:
  plugin: iterator
  source: field_thumbnail
  process:
    target_id:
      plugin: migration
      migration: file
      source: fid

The problem I'm running into is the error listed in the title. This is the presave() function:

public function preSave() {
  parent::preSave();

  $width = $this->width;
  $height = $this->height;

  // Determine the dimensions if necessary.
  if (empty($width) || empty($height)) {
    $image = \Drupal::service('image.factory')->get($this->entity->getFileUri());
    if ($image->isValid()) {
      $this->width = $image->getWidth();
      $this->height = $image->getHeight();
    }
  }
}

It seems like it's dying because there is no image for that node, because it's dying at this line:

$image = \Drupal::service('image.factory')->get($this->entity->getFileUri());

It works just fine when there is an image for the node. Shouldn't this be skipped if there is no image found in the files migration? Is there a config option in the .yml file I can use to avoid this error?

Thanks.

UPDATE: I found this docs page on the skip_on_empty process plugin, and implemented as suggested on that page:

field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: migration
      migration: file
      source: fid
    -
      plugin: skip_on_empty
      method: row

but I still get the same error, more than likely because in the pipeline, it's already errored out before it gets to the skip_on_empty plugin. However, if I switch things around:

field_image:
  plugin: iterator
  source: field_thumbnail
    process:
    target_id:
    -
      plugin: skip_on_empty
      method: row
    -
      plugin: migration
      migration: file
      source: fid

Then the entire blog node is skipped if there is no image. How can I just skip trying to migrate the image if there is none?

I a similar issue on a previous migration, I found that a core issue sometimes causes that error.

The patch submitted fixed the problem on my case.


Complex Views / Field Collection question Is there a way to do a subquery in a View that filters entities based on a filter value in a field collection, but also by another value attached to that field collection item?

For example, people are searching properties. Property rates are stored in a field collection that references dates, the price, and if it is available.

When a user uses the view and searches by a particular date, I only want to return the entities that have both that date AND an available = 1 on that field collection item. Just adding the 'available' filter on the View is not enough, because it needs to search the value attached to the field collection item id that the date is attached to.

My first thought was to use hook_views_query_alter:

$lookup = new EntityFieldQuery;
    $lookup->entityCondition('entity_type', 'field_collection_item')
        ->entityCondition('bundle', 'field_property_booking');
    $lookup->fieldCondition('field_property_booking_basis', 'value', 'Weekly', '=');
    $lookup->fieldCondition('field_property_booking_period', 'value', 1348891200, '=');
    $lookup->fieldCondition('field_property_booking_available', 'value', 1, '=');
    $rates = $lookup->execute();

Okay, so, based on the timestamp from the form submission, I get 5,172 results. I am not sure where to go at this point. I want to say something like the main entity has field collection item IDs IN () with the item id's above, but I am not sure how to do that.

Can I plug in somehow with $query->where conditions? Or is there a better way to do this?

After some direction from merlinofchaos, here is what I did:

Add the field as an exposed filter
Use form_alter to change it to hidden
Use javascript to set the value to 1, bound to a change event on the date select

Otherwise its like asking for a conditional filter (if filter X has value, then set these filters to Y) which is not so easy in UI.

You could also inspect $_GET and use hook_views_query_alter to add a $query->where, but I had better luck with Javascript.

Hope this helps others.


How do I mimic the route handling? In drupal 7 I have a chunk of code that gets the page content by mimicking what drupal does:

$router_item = menu_get_item($href);
if ($router_item['access']) {
  if ($router_item['include_file']) {
    require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
  }
  $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
}

$page_callback_result will then hold the HMTL of the content region of that page.

I'm trying to port this to drupal 8 but I'm stuck. Anyone has a clue how to do this?
I'm close, but I'm struggling on getting the controller:

 $request = Request::create('/' . $href);
 $controller_resolver = \Drupal::getContainer()->get('controller_resolver');
 //$controller = $controller_resolver->getController($request);
 $callable = $controller_resolver->getControllerFromDefinition('\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage');
 $arguments = $controller_resolver->getArguments($request, $callable);
 $page_content = call_user_func_array($callable, $arguments);

The problem is that $controller = $controller_resolver->getController($request); returns FALSE. I'm trying to get the proper controller for a request, for some reason this won't work...

I'm not sure what is the purpose of this, now in Drupal 8 Guzzle is available to creating external and internal request.

$this->httpClient->get($href)->getBody(TRUE);

The httpClient is a service in Drupal 8  api.drupal.org/api/drupal/core%21core.services.yml/service/http_client/8

you need inject this service in your class.

if you need read the Route properties like callback, permissions, etc. you need use the routeProvider service.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Routing%21RouteProvider.php/class/RouteProvider/8

maybe more information about that problem help us to understand what is the best way to porting for Drupal 8

UPDATE:

Thinking a little more, you want to make a sub-request?

something like https://gist.github.com/dmouse/4976461875a27689d155


How to add new roles in drupal 7? Drupal by defaults gives us three roles

Administrator
Authenticated users
Anonymous user

Can i add a new roles in it? Like:

suscriber
trusted customer

Yes, it is possible.

Go to "Home » Administration » People » Permissions"
Select the roles shown at the top right
Add a new role using the input textbox at the bottom

Your role will be created.


How to change column chart color programmatically I have created view block using different content type. I am displaying this block as a column chart using Drupal module Highcharts, it is working but if I want to display separate color of content type node I mean one color for one content type node and other color for other content type.
Can any one tell me how to change this? Is there any module by which I can sort out my problem?

Attempt to answer the last question, i.e.:

  Is there any module by which I can sort out my problem?

To create charts in Drupal, consider the comparison of charting modules as a possible place to start from, to find the module that best fits your needs. That comparison does include the modules mentioned here, but quite AbitMORE charting modules ...

Possible alternatives that should solve this specific question, are the Chart module, or the Charts module. I recently created quite a lot of new Chart documentation, and Charts documentation. Though there are other alternatives in that comparison that might be a better fit for this specific case.

The license that comes with the related charting library (engine) in each of these modules, should be considered also. It is one of the (important?) selection criteria for deciding on the module to go for. 'Possible privacy concerns' or 'Yes or no support for saving charts in PDFs' is another typical item to consider.

Be aware: I'm a new (co-) maintainer of both module 'chart' and 'charts' (confusing names, I didn't invent those names), and the author of the comparison.

Ps: the question does not say why it has to be done programmatically. But note that the Charts module ships with out-of-the-box samples which seems to be very close to what you are trying to create. Adapting these samples to exactly fit your needs seems like cloning these samples in a new views display or a new view.


How can I make a view showing all users who have not created any nodes or made comments? I am trying to fix a site that has had more than 10,000 spam user registrations.  However, some legitimate user registrations have also been made, so I cannot simply delete all the accounts.

Manually sorting through all of this would take a very long time.  However, it appears to be the case that no spam users made any comments or created any nodes.  So, I thought I might be able to create a view that shows all the users that have not created content or made any comments, and then use VBO to delete all such users.

But, although I can make a view that shows users who have created content, I haven't been able to figure out a way that shows users who have not created any content/comments.  How might I go about this?

Before some days I was also work on some thing like this. In my registration page there is a field named looking-for. I was created a view to show all the members as per there looking-for field. It mean that if user selected male in looking for then only male is shown. I have added below code in the view. You can change condition as per your condition & add relationship & filter criteria.

global $user;
  $profiles = profile2_load_by_user($user);
    foreach ($profiles as $profile) {
        if ($items = field_get_items('profile2', $profile, 'field_sex')) {
        break;
      }
    }
    $i_am=$items[0]['value'];
 if($i_am=='sdmale' || $i_am=='sbmale'){

  $looking='smfemale+sbfemale';

}

if($i_am=='smfemale' || $i_am=='sbfemale'){

  $looking='sdmale+sbmale';

}

   return $looking;


Secure file download from other server This is an unusual one. Let's say I have two web servers A and B. How would I go about making a link to a file from a Drupal website on server A to a file on server B such that the link is secure (the link to the file can't be accessed directly/shared)? I would have some control over server B, but it would just be a standard web server.

The reason for wanting this is that I need to serve some files to users behind the "Great Firewall of China", but the website is within China.

The first thing that pops to mind is to create a custom module, with a menu callback to obfuscate the real url. This is the same way the drupal private filesystem (private://) handles this.

Create a menu entry in your custom module's hook_menu() to obfuscate the real url and perform access checks.

function my_module_menu() {
  $items['my-module/download'] = array(
    'title' => 'File download',
    'page callback' => 'my_module_page_callback',
    'access callback' => TRUE, // Let the page callback handle the checks.
    'type' => MENU_CALLBACK,
  );
}

Have the page callback transfer the file and check access. Based on file_download().

function my_module_page_callback() {
  $args = func_get_args(); // Get the path elements after `my-module/download`
  $target = implode('/', $args); // Join them into a string.
  $uri = 'http://some-other-server.com/files/' . $target;

  if (function_to_check_if_file_exists($uri)) { // Define this function yourself.
    $headers = array('Content-Type' => 'file mime-type'); // Set the correct mime-type for the file here.

    if (function_to_check_access()) { // Define this function yourself.
      file_transfer($uri, $headers);
    }
    drupal_access_denied();
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}

Accessing an url like example.com/my-module/download/documents/1.pdf should now serve a file from http://some-other-server.com/files/documents/1.pdf.

In order to register the files you will have to construct a file object, set the uri to my-module/download/[remote-path] and save the file to the file_managed table. Then attach the file to a node. There might be better ways for this, but this is what I can think of now.

$f = (object) array(
  'uid'         => 1,
  'filename'    => '',
  'uri'         => 'my-module/download/[remote-path]',
  'filemime'    => '',
  'filesize'    => 12345,
  'status'      => 1,
);
file_save($f);

$node = node_load(1);
$node->field_file[LANGUAGE_NONE][0] = (array)$f; // Add a file field on a content type and use the name here.
node_save($node);


Getting 443 Forbidden Error on my custom module I am learning drupal 8 and creating my own custom module. I have a clean localhost installation and was following some tutorials online to create a very basic "hello" for my first attempt.

The issue I am running into is when I attempt to go to my routing area, I get the following error:

Forbidden
You don't have permission to access /tag on this server.

Here is my code. Can someone tell me why this isn't working? If I followed the online tutorials right, I should have access.

tagnbag.info.yml file:

name: Tag N Bag
description: 'Create a custom grocery list.'
type: module
package: Custom
version: 1.0
core: 8.x

tagnbag.routing.yml:

tagnbag:
  path: '/tag'
  defaults:
    _controller: 'Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
    requirements:
      _permission: 'TRUE'

TagBagController.php:

<?php
/**
 * @file
 * Contains \Drupal\tagnbag\Controller\TagBagController.
 */

namespace Drupal\tagnbag\Controller;
use Drupal\Core\Controller\ControllerBase;

class TagBagController extends ControllerBase {
    public function welcome() {
        return array(
            '#type' => 'markup',
            '#markup' => 'Content for Tag N Bag.'
        );
    }
}

_permission: 'TRUE' is not a thing unless you've defined a custom permission TRUE (and if you did, I'd advise you to change that). What you have is looking to see if a user has the permission TRUE - which I doubt any user has, and correctly denying access. If you want to grant access to the route for everyone, in all contexts, use _access: 'TRUE'. See Structure of Routes on d.o for more info.


Extracting user field values from dynamic SQL queries Aim
I have successfully written a fairly long dynamic sql query, however am struggling with a seemingly simple part at the end.
Although, I am able to successfully extract mail and name from the users table, when I try to extract field_first_name it returns the error below.
The users table has a column with the machine name: field_first_name
Code
    $database = \Drupal::service('database');

    $select = $database->select('flagging', 'f');
    $select->fields('f', array('uid', 'entity_id'));
    $select->leftJoin('node__field_start_datetime', 'nfds', 'nfds.entity_id = f.entity_id');
    $select->fields('nfds', array('field_start_datetime_value'));
    $select->leftJoin('node_field_data', 'nfd', 'nfd.nid = f.entity_id');
    $select->fields('nfd', array('title'));
    $select->leftJoin('users_field_data', 'ufd', 'ufd.uid = f.uid');
    // TODO extract first name
    $select->fields('ufd', ['mail', 'name', 'field_first_name']);

    $executed = $select->execute();
    $results = $executed->fetchAll(\PDO::FETCH_ASSOC);

    $username = $result['name'];
    $email = $result['mail'];
    $first_name = $result['field_first_name'];

Error
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ufd.field_first_name' in 'field list': SELECT f.uid AS uid, f.entity_id AS entity_id, nfds.field_start_datetime_value AS field_start_datetime_value, nfd.title AS title, ufd.mail AS mail, ufd.name AS name, ufd.field_first_name AS field_first_name FROM {flagging} f LEFT OUTER JOIN {node__field_start_datetime} nfds ON nfds.entity_id = f.entity_id LEFT OUTER JOIN {node_field_data} nfd ON nfd.nid = f.entity_id LEFT OUTER JOIN {users_field_data} ufd ON ufd.uid = f.uid; Array ( ) in event_notification_cron() (line 63 of /app/modules/custom/event_notification/event_notification.module).

Field

Assuming your field is a string, the field in the database will be field_first_name_value
Assuming the field is attached to a user entity, the table for that field should be user__field_first_name (2 underscores between user and the field name) your need one more join to get that field value, it's not stored in users_field_data

$database = \Drupal::service('database');

$select = $database->select('flagging', 'f');
$select->fields('f', array('uid', 'entity_id'));
$select->leftJoin('node__field_start_datetime', 'nfds', 'nfds.entity_id = f.entity_id');
$select->fields('nfds', array('field_start_datetime_value'));
$select->leftJoin('node_field_data', 'nfd', 'nfd.nid = f.entity_id');
$select->fields('nfd', array('title'));
$select->leftJoin('users_field_data', 'ufd', 'ufd.uid = f.uid');
$select->leftJoin('user__field_first_name', 'uffn', 'uffn.uid = f.uid');
// TODO extract first name
$select->fields('ufd', ['mail', 'name']);
$select->fields('uffn', ['field_first_name_value']);

$executed = $select->execute();
$results = $executed->fetchAll(\PDO::FETCH_ASSOC);

$username = $result['name'];
$email = $result['mail'];
$first_name = $result['field_first_name_value'];


WYSIWYG do not make url when pasted in a hyperlink When I paste a URL into a TinyMCE editor using WYWIWYG it converts the text into a  link.

So http://vimeo.com/18150336 would be come http://vimeo.com/18150336. I would like to keep the plain text. Is their a way to configure TinyMCE to keep the link as plain text.

I do not want to strip out  tags as adding a hyperlinks should be an option on the toolbar. It should just not happen by default.

This is the solution--
On drupal administration:

Administration » Configuration » Content authoring » Text formats

you must remove "Converts URL into links" and then all it's Right!!


Jquery Ajax to Drupal to External site, reading response I have a drupal site.

There is a page (page 1) with a form that gathers user info and submits it via AJAX to a Drupal Module page.

The AJAX format is jquery

var responseTarget = '/site/module/page_name';
  jQuery.post(responseTarget, {
      key1: value1, key2: value2,.......
  }, function(responseText, statusText, xhr) {
    if (xhr.status === 200) {
      PROCESS SUCCESS
    }
    else PROCESS FAILURE

The module page has the URL format "site/module/page_name" (page 2) and is constructed from the module file "page_name.tpl.php".

This (page 2) processes the user information and sends it to an external server.

The server replies to my (page 2) which processes the response by saving a value to the user account.

The (page 2) then responds to the AJAX call on (page 1).

When my AJAX receives the response it is the response from Drupal (page 2), not from the external server.

responseText = the whole Drupal page2, as it is part of a module it contains the header and footer and the processed php of the page as HTML, no objects or values.
xhr.status = 200 // Drupal page2 success

What I would like to do is read the response from the server in my page 2 and pass this pack to the AJAX script, or process the value returned from the server in page 2 and pass a status/value/... back to the AJAX script based on this.

I have tried getting Drupal page 2 to echo a JSON object but this is done within the module and Drupal prints it out as part of the page HTML.

Summary

[page 1 (ajax)] --> [page 2 (Drupal module)] --> [External Server]

[External Server (modifies an object)] --> [page 2 (processes the object and incorporates it into a full Drupal page, and removes whatever header, status was sent from external server] --> [page 1 (ajax) receives the status and data from page 2]

Try this:

ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('node/1');
print ajax_render($commands);
exit;

Reference D7 AJAX Form Redirect.


How to use Taxonomy Facets together with Apache Solr Multisite Search ? This regards http://drupal.org/project/apachesolr_multisitesearch
I'm trying to enable Multisite Search Facets (based on Taxonomies) for a few sites. The 'normal' multisite facets such as 'filter by site', 'current search' etc appear fine but facets based on Taxonomies do not appear not matter what I do. The facets are enabled and the blocks added to regions, caches cleared etc.

Tested in Drupal Core 6.20 with the latest stable version of Apache Solr & Apache Solr Multisite Search

Has anyone else successfully enabled this functionality?

Any help greatly appreciated

A little patch that solve the issue

Index: apachesolr_multisitesearch.module
===================================================================
--- apachesolr_multisitesearch.module   (révision 32470)
+++ apachesolr_multisitesearch.module   (copie de travail)
@@ -331,6 +331,10 @@
             return apachesolr_date_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by post date'));
           case 'hash':
             return apachesolr_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by site'), 'theme_apachesolr_breadcrumb_hash');
+
+           //syg on ajoute un retour pours toutes les autres facets
+          default:
+            return apachesolr_facet_block($response, $query, 'apachesolr_multisitesearch', $delta, $delta, t('Filter by %field', array('%field'=> $delta)));
         }
       }
       break;


Best way to Improve live site and then push changes from dev to live? Currently I am applying a new Drupal theme on an existing site.
I have created a separate instance for Development and copied the live site database and started working.

The new theme requires many new features ( modules, blocks, views etc ). I am just writing down every thing and of-course I need to redo it on live site once the theming is completed.

Is it possible that my Dev database gets updated automatically if changes are made on live site?

So once the theming is finished, I can drop the live DB and replace with Dev DB? Seems like a dream to me ..

Any help ?

Is it possible that my dev database gets updated automatically if changes are made on live site ?
So once the theming is finished, i can drop the live DB and replace with Dev one:) Seems like a dream to me ..

Databases shouldn't be migrated up (ie dev -> prod), only down (ie prod -> dev). If you migrate a database up, you will overwrite anything new on the production server. For example, any new accounts, comments, pages, or anything else that is in the database.
If you use the Features module, it will allow you to migrate some database settings as code (a features module) that can potentially solve your issue. Or if you are on D8, you can export configuration and import it in the other site.


How to programmatically fetch the results of a view with facet filtering Setup

Drupal 8.2 + Views + Facets
View articles …

… with first sub-view page_1
… has facets

View filter: field_title
View facet: field_facet allows multiple values, e.g. A and B

Concept

I would like to fetch the view results programmatically by reusing the $_GET query values. (The $_GET values are serialized and stored for later usage.)

Problem

The results are correct when working with only non-facet filters. Facet filter values are ignored and won't be filtering the results by the provided snippet.

Is the View working as expected?

Yes, the view is working as expected: Filtering works when visiting the website with a HTTP client and the query ?field_title=Hello&field_facet[0]=A&field_facet[1]=B.

Snippet

<?php

use Drupal\views\Views;

$view = Views::getView('articles');

$query = [
    // Filters results with title `Hello` as expected.
    'field_title' => 'Hello',

    // The programatically executed View ignores
    // the following facet based values for filtering.
    'field_facet' => ['A', 'B'],
];

$view->setExposedInput($query);

// bool(true)
var_dump($view->execute('page_1'));

$result = [];

/** @var Drupal\views\ResultRow $row */
foreach ($view->result as $row) {
    /** @var Drupal\search_api\Item\Item $item */
    $item = $row->_item;

    /** @var Drupal\node\Entity\Node $node */
    $node = $item->getOriginalObject()->getValue();

    $result[] = [
        'nid' => $node->id(),
        'title ($item)' => $item->getField('title')->getValues()[0],
        'title ($node)' => $node->get('title')->getValue(),
    ];
}

Experiments with the REST module

The REST module allows to create views with JSON results.
Sadly, this module is also ignoring facet based filters.

Question

How do I inject/attach the facets to use their filters?

Kinda old question but i just needed the same thing and here is how i did it.

use Drupal\views\Views;
use Symfony\Component\HttpFoundation\Request;

$view_id = 'VIEWID';
$display_id = 'rest_export_1';
$filters = [
  // Filters results with title `Hello` as expected.
  'field_title' => 'Hello',

  // The programatically executed View ignores
  // the following facet based values for filtering.
  'field_facet' => ['A', 'B'],
];

$view = Views::getView($view_id);
$view->setDisplay($display_id);

// Here comes the part that did the trick for my REST JSON request.
// Create a new request with your filters / url query and set that.
$request = new Request($filters);
$view->setRequest($request);

$view->execute();

//TMP debug the json decoded value
$view_result = \Drupal::service('renderer')->renderRoot($view->render());
$view_json_decode = json_decode($view_result);

The rest export view puts the exposed filter inside the view request so instead of setting the exposedfilters i made a request with the query args and it worked fine.

The documentation is missing a lot so if anyone finds a better way then let me know.


How to migrate an admin.inc file which creates a configuration form for settings? I am trying to migrate a module from drupal 7 to drupal 8, but sadly I cannot find any proper documentation on how to do this. I already re-wrote .info file to .info.yml but at this point its just a dead-end. For example I have a admin.inc file which creates a configuration form for settings. It looks like this:

function commerce_shipping_gls_settings() {
  $form = array();
  $form['rates'] = array(
    '#type' => 'fieldset',
    '#title' => t('Shipping costs'),
  );
  $form['rates']['commerce_shipping_gls_shipping_rate_amount'] = array(
    '#type' => 'textfield',
    '#title' => t('Shipping service rate amount'),
    '#default_value' => variable_get('commerce_shipping_gls_shipping_rate_amount', 3900),
    '#required' => TRUE,
    '#element_validate' => array('element_validate_integer_positive'),
  );
  return system_settings_form($form);
}

I was trying to find how to convert a config file to drupal 8, but sadly I didn't get much. Could someone please give me some guidance on how can I achieve this?

system_settings_form() is replaced by \Drupal\Core\Form\ConfigFormBase in D8.

you can see
https://www.drupal.org/node/1910694
Working with Configuration Forms

Example:

namespace Drupal\example_module\Forms;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

class StudentConfigForm extends ConfigFormBase {
  // The Form ID that is used in alter hooks.
  public function getFormId() {
    return 'student_config_form';
  }
  // Configuration names that will be editable
  public function getEditableConfigNames() {
    return ['example_module.student'];
  }

  public function buildForm(array $form, FormStateInterface $form_state, $args = '' ){
    $config = $this->config('example_module.student');
    $values = $config->get();
    $form['student'] = array(
      '#type' => 'details',
      '#title' => $this->t('Student'),
      '#open' => TRUE,
      '#tree' => TRUE,
    );
    $form['student']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('First name'),
      '#default_value' => $values['student']['first_name']
    );
    $form['student']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Job title'),
      '#default_value' => $values['student']['last_name']
    );
    $form['student']['age'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Age'),
      '#default_value' => $values['student']['age']
    );
    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $state) {
    $values = $state->getValues();
    $config = $this->config('example_module.student')
      ->set('student', $values['student'])
      ->save();
  }
}


Image widget stopped working after core update I recently did a long overdue update from 7.20 to 7.33.

However, after I've made the update, the "Image" widget has stopped working when trying to edit content through the admin screen. I cannot add or remove any images using this widget - it makes an AJAX call and the request comes back as 200, but the image upload/removal fails without an error.

I think it's a problem with the AJAX but I can't be sure.

Got it - the AJAX form was not being cached by memcache, and so it was failing out every single time. Restarting memcache did the trick.


Fatal error undefined function taxonomy_get_tree() I want to write a module that makes a select search form based on taxonomy terms. (with hierarchical select boxes)
This is on drupal 7.0 and status is up to date.
The form is made and Ajax is properly working with testing values.
But now I need to find a way to fill up my select boxes with taxonomy terms,
wanted to use the function taxonomy_get_tree (modules/taxonomy/taxonomy.module, line 836) and received the message:

Fatal error: Call to undefined function taxonomy_get_tree()

When I've put the function from modules/taxonomy/taxonomy.module in my own module I receive the message:

Fatal error: Cannot redeclare taxonomy_get_tree()

Should it be that I have to hook my module in any kind of way with the taxonomy.module file, or ar there other ways to achieve my goal?

This is on a mymodule.module file placed in drupal7/sites/all/sitename/modules/custom/mymodule/mymodule.module

The code is like

$tree = taxonomy_get_tree(6, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
print_r($tree);

I'm unable to approach all functions in the taxonomy.module page...

Maybe the taxonomy module is just loaded after yours... Have you tried to load the taxonomy module before calling taxonomy_get_tree()? :

drupal_load('module', 'taxonomy');
$tree = taxonomy_get_tree(6, $parent = 0, $max_depth = NULL, $load_entities = FALSE);
print_r($tree);


Show nodes related to referenced node I have 3 content types: "Files", "Actions" and "Templates".

In each "Files" node there's a entity reference to an "Actions" node
In each "Templates" node there' a entity reference to an "Actions" node

How can I setup a view that shows a list of links to "Templates" nodes on a "Files" node page, based on the entity reference to an "Actions" node for this specific "Files" node?

Edit - I couldnt get Felix' answer to work, so here's a more detailed description of my case:

I have a node called "BAG001", this node has content type "Files.
I have a node called "Procedure A1", this node has content type "Actions"
I have a node called "Form A1", this node has content type "Templates"

In "BAG001" I make an entity reference to "Procedure A1" (field name is "field_action")
In "Form A1" I make an entity reference to "Procedure A1" (field name is "field_related_action")

On the "BAG001" page there's should be a views generated block, showing all templates related to "Procedure A1". In this case that would be "Form A1".

I tried setting up a view using the following settings:

1) Relationship -> Entity reference: field_action
2) Relationship -> (Content entity referenced from field_action) Entity Reference: Referencing Entity [with a relationship to (1)]
3) Contextual filter -> Content: NID [with a relationship to (2)]

Create a view that shows a list of templates.
Add a relationship to the actions content type (Entity Reference: Referenced Entity via field_related_action).
Add a relationship to the files content type (Entity Reference: Referencing entity via field_related_action).
Create a contextual filter based on the current nodes nid. When you create the filter then When the filter value is NOT available select Provide default value and choose content ID from URL. Also this filter should be for the second join to the file node type.
Set that view to show in a block on each files page.


Ajax webform do submit without ajax when it is loaded via ajax I'm trying to load a node containing an ajax webform and add it to an existing div, this works fine, but when I click to next step, the form is submitted to the webform action path.

Any idea?

Thanks!

          $.ajax({
            url: '/path/to/my/node/with/webform'
            success: function (data) {
              // Add html to existing container.
              $(data).appendTo('body');
            }
          });

Short answer: you need to attach the Drupal behaviors after inserting your new content into the DOM:

$.ajax({
  url: '/path/to/my/node/with/webform'
  success: function (data) {
    // Add html to existing container.
    $(data).appendTo('body');
    // Attach the new behaviors to the DOM
    Drupal.attachBehaviors();
  }
});

Long answer: Although Drupal has jQuery included with core, it does not use jQuery functions like $.on() or $.delegate() or $.live(), which attach behaviors to elements when they are inserted into the DOM. Instead Drupal uses behaviors, which is a Drupal specific method of attaching behaviors to elements.

Behaviors have three parts:

1) Scripts add new behaviors to the Drupal.behaviors object. Example:

Drupal.behaviors.someArbitraryKey = {
  attach: function (context, settings) {
    attachHandlerToElement(context, settings);
  }
};

Generally people consider this to be an onload function, as it is called when the document has loaded and is ready to have JavaScript executed on it. However, it can also be called using Drupal.attachBehaviors(), which will be addressed in #3 below. When the DOM is loaded, or Drupal.attachBehaviors() is called, the .attach() function of the behavior is executed, in this case calling attachHandlerToElement(context, settings); whenever this is executed.

2) $.once() is used to ensure that handlers are not attached multiple times to an element. Because behaviors can be executed multiple times, event handlers can be attached to elements multiple times, if steps aren't taken to prevent that. The jQuery $.once() function, provided by core, ensures that the code it contains is only attached to the element a single time:

function attachHandlerToElement(context) {
  $(context).find(".some_selector").once("some-arbitrary-key").each(function () {
    // Note that $(this) is the current iteration
    // of .some_selector
    $(this).click(function () {
      // Do something.
    });
  });
}

By calling $.once() on elements, the contained code in the $.each() loop is only ever attached a single time. This means that the $.click() handler above is only attached a single time to elements with the class .some_selector.

3) When new content is inserted into the DOM, whether that be from an AJAX call, or even just new elements inserted using JavaScript, Drupal.attachBehaviors() is called. This in turn loops through all behaviors, and executes their attach() handler.

A final note on context. On initial page load, context is the full DOM. Drupal.attachBehaviors(context) takes an argument, context, which should be an element of the DOM (not a jQuery object containing it). In your case, you are appending your content to the body, so there is no need to pass an argument, as you will need to parse the full DOM. If you were appending your content to some element though, you could do something like this:

$(data).appendTo('#some_element');
Drupal.attachBehaviors($(#some_element").eq(0));

This would pass it the element of the DOM to which the new content was attached. This element becomes context in the attach() handler, and is more efficient than passing in the full DOM.


How to disable quickedit for specific block, but keep contextual links I want to disable the quick edit feature for a specific block so that it does not show up in the contextual links anymore.
However, I want to keep the other contextual links for this specific block (e.g. configure block).
I do not want to entirely turn off quick edit, because I still need it on some elements.
Hope someone can help with this one?

It looks like you can use module https://www.drupal.org/project/block_content_permissions for that. To cite the project page:

Add the following permissions to allow access to edit blocks in-place (on-page):

Use contextual links (Contextual Links module)
Access in-place editing (optional, Quick Edit module)

However, it might not be feasible depending on the number of blocks on you site.


How do I create a log/statistics of on page events? I am using drupal 7, I have seen there are already statistic modules but can't find any for my situation

On my website I am trying to track certain on page activities which site admins can see in a table.

Example of activities are if users engage with certain elements on a page, if certain images load before user leaves, and browser information. Alot of information is only available through JS or Jquery not PHP.

On my site I can build a client side log, so when I go to console I can see the statistics I am looking for, but what is the best way to save this log/statistics to by drupal database.

I was thinking of building a content type called 'page log' with different fields relating to page info I need, which would be loaded on every page and filled/submitted via javascript. But think this would be too resource intensive.

To summarise, I have been building a function in javascript which collects on page activities which currently I can view in my browser console. I am looking for a way to save the log for each page to my drupal site in a way which can be recalled easily. Probably through views.

How can I save this log? Thanks for any help

Since, you've built everything in js, next thing to do is send the data from the client. You could do that with an endpoint in a custom module and sending everything you want there with ajax.
From there it depends how often you anticipate db writes from these data and you can assess the next step to take. You could:

Create a content type and programmatically save data to it.
Create a custom db table with only the fields you want and implement some db logic to save data.
Use mongoDB and setup a document table to store these data. This is the best option performance wise. You would need to setup the mongoDB module for it.