Parse entity_embed module markup I'm using Drupal 8.1.1 with Acquia's Lightning distribution. I need to be able to embed a media entity (a tweet, instagram post, youtube video, image, etc.) and then captured the resultant HTML output in a hook. However, $node->body->value just gives me a weird markup like this:

<drupal-entity data-align=\"none\" data-caption=\"\" data-embed-button=\"media_library\" data-entity-embed-display=\"entity_reference:entity_reference_entity_view\" data-entity-embed-settings=\"{&quot;view_mode&quot;:&quot;media_library&quot;}\" data-entity-id=\"21\" data-entity-type=\"media\" data-entity-uuid=\"ea90ea95-6b7e-4e44-a1a6-4e7baabe3cb7\"></drupal-entity>\r\n"

And rendering the entity through the renderer service gives me the entire output of the node, rather than just the html equivalent of the aforementioned markup.

Is there any way to parse this output and get the actual HTML of the embedded entity?

The body contains tokens set when you press an embed button in ckeditor.

This raw body content is processed by this filter:

http://cgit.drupalcode.org/entity_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

 public function process($text, $langcode) {
    $result = new FilterProcessResult($text);

    if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
      $dom = Html::load($text);
      $xpath = new \DOMXPath($dom);

      foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
        /** @var \DOMElement $node */
....

You would have to build a view mode in ui with only the body field or apply the filter in code.


How can I add an age validator page? To access the site, all users (except the logged-in users) need to pass through an age gate. They can only leave the welcome page if they are 18 years or older.

I started by adding a session to my custom theme.theme file.

<?php

function scottishleader_preprocess(&$variables, $hook) {
  static $hooks;

  $route_name = \Drupal::routeMatch()->getRouteName();
  $response = new\Symfony\Component\HttpFoundation\RedirectResponse('/welcome');
  $session = \Drupal::request()->getSession();
  $session->set('initialSession', 'initial');

  if ($session->get('ageGate') == 'passed') {
    $session->remove('initialSession');
  }
  if ($route_name != 'agegate.route' && $session->get('initialSession') == 'initial') {
    $response->send();
  }
  if ($route_name == 'agegate.route' && $session->get('ageGate') == 'passed') {
    $homeRoute = new\Symfony\Component\HttpFoundation\RedirectResponse('/');

    $homeRoute->send();
  }
}

Next, I created a custom module for the age gate and the routing.yml looks like the following.

agegate.route:
  path: '/welcome'
  defaults:
    _controller: '\Drupal\agegate\Controller\AgeGateController::content'
    _form: '\Drupal\agegate\Form\AgeGateForm'
  requirements:
    _permission: 'access content'

The AgeGateController class renders a form.

class AgeGateController extends ControllerBase {
  public function content(){
    return \Drupal::formBuilder()->getForm('Drupal\agegate\Form\AgeGateForm');
  }
}

It was all working fine until I realized that, if I am logged and I try to access the front page, I get redirected infinite times!

So, for some reason, my code only works on users that aren't logged-in.

How can I create this age gate functionality?

Implement the redirect in a module. Either in a kernel request subscriber, see this change record https://www.drupal.org/node/2013014 or in a kernel response subscriber, see https://git.drupalcode.org/project/age_verification/blob/8.x/src/EventSubscriber/pathGate.php.

The second example is from a contrib module you can try as it is. I don't have first-hand experience with this module, so I can't recommend or not recommend it, but this would be off-topic here anyway.


How to use Recurring Dates with Views properly? I am trying to use recurring dates for one of my content types (Event) to limit the amount of Event records.

I would like to have one Event record created for all dates of that Event.
For example if an Event occurs every week for a year I have 1 record instead of 52.

Still I would like to see 52 separate lines in the related View because I would like to be able to sort/filter the View to see current week's Events only.

How to set up a Events View for that data so that each view line shows one date only ?

I would like a View to return a list like this...

 - Event A  12-10-2011
 - Event B  12-11-2011
 - Event A  12-12-2011
 - Event B  12-13-2011
 - Event A  12-14-2011
 - Event B  12-15-2011

(Event A and B are recurring every second day )

...instead of a list like this:

 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011
 - Event A
    - 12-10-2011
    - 12-12-2011
    - 12-14-2011
 - Event B
    - 12-11-2011
    - 12-13-2011
    - 12-15-2011

Eventually I found how to set this up an easy way:

Go to your View
Go to Displays --> <your display name,  for example Page> --> Edit
Select Format : Table
Add a date field:
Select a Content: <your date field name>
You will see Configure field: Content: <your date field name>
Go to "Multiple field settings"
Uncheck "Display all values in the same row"

  If checked, multiple values for this field will be shown in the same
  row. If not checked, each value in this field will create a new row.
  If using group by, please make sure to group by "Entity ID" for this
  setting to have any effect.


Admin approved file uploads I want to allow all authenticated users to upload files, but I want them to be approved first before they're publically viewable.  I'm currently using a single image field for the uploads, that can have unlimited values.

I'm not sure what is a good way of going about this.  Let's say, the user uploads 4 images, which are all shortly after approved.  Then, later, they upload one more image... I still want the first four to be publically viewable, but I don't want the fifth one to be until it's approved.

Also, I am kind of concerned about the fact that the files would be downloadable immediately, as soon as they are uploaded via sites/default/files.  Is this a big deal?  Concerned about copyright violations and such.

I believe what you wanted is similar to commerce file module where users can upload file and have configurable settings, where you can limit access duration, number of downloads etc. and about this one downloadable immediately, as soon as they uploaded via sites/default/files. Is this a big deal? yes it is big deal once you uploaded it in sites/default/files everyone can access it and download anytime without restriction you may violate some regulation. you should upload it outside Drupal where users can't access it via url. Where in commerce file already have this settings where you could place your file folder outside Drupal. I am not sure if this is already available in Drupal 8.


How to add a referenced taxonomy term name to the node title in page-title.html.twig Using a term reference field, I am adding the manufacturer's name to the front of our node titles in views for styling and line breaks between the manufacturer field and the title which is really nice. For the node display titles, I am currently using a block view for the manufacturer's name, and placing it above the page title block in the block layout. This stacks the Manufacturers name above the Node title which i don't really prefer:

Manufacturer
Some Node Title

I would like to add the field_manufacturer field to the node display title as a prefix so that it is inline and not stacked like my example above, and I need to add a class to it so that I can target and style it. I am not sure which twig file is responsible for rendering the title, so I would really appreciate help marking this up properly.

Thanks!

Posting this answer to help those trying to accomplish the same thing. I was told the code above had security vulnerabilities (which has since been removed see comments below).  On the Drupal Slack channel, someone pointed out the following concern with runwithscissors' answer:

  "This code is potentially dangerous:$variables['title'] = \Drupal\Core\Render\Markup::create($new_title); A user could set  as the Node or Term title and potentially execute code on the site. Typically you don’t want to ever create Markup objects manually. For what you’re doing, I’d suggest setting $term_name to a new key in $variables, then forming your combined title in the Twig template like {{ term_name}} {{ title }}"

So what i ended up doing was adding this template_preprocess_page_title to my MY_SITE.theme file.

(Note:  field_manufacturer is the specific field for my use case, so you would need to change all instances of that to your taxonomy reference field name.)

/* Add field_manufacturer to all node titles with field_manufacturer and not empty */
function template_preprocess_page_title(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   if ($node && $node->hasField('field_manufacturer') && !$node->field_manufacturer->isEmpty()) {
     $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_manufacturer')->target_id);
     $term_name = $term->getName();
     $variables['term_name'] = $term->getName();
   }
 }

This applies to all nodes with the field_manufacturer, but also checks that the term field is NOT empty with && !$node->field_manufacturer->isEmpty()). This was critical as the reference field was not required, so nodes that had the field but didn't have a value crashed the site with Error: Call to a member function getName() on null in template_preprocess_page_title()

Then I copied and overwrote the page-title.html.twig file from my bootstrap base theme which originally renders the title like this:

{% if title %}

{{ title }}

{% endif %}

And changed the H1 title line to this:

{% if title %}

    {% if term_name %}
      {{ term_name }}
    {% endif %}
  {{ title }}

{% endif %}

This adds a MY-DESIRED-CLASS-NAME span class to the term_name. Also by putting it within {% if term_name %}/{% endif %} statement, it prevents that class from being rendered in the html where there is no term_name present.

Hope this helps someone!


Remove HTML element when pasting from Word I am pasting a GDoc content using "paste from word" button on the ckeditor (4.5.4) and I want to remove the extra span with style associated with links in the text (so that it uses my theme css).
Here is how a link is styled after pasting to ckeditor:

         Neil Armstrong

I want it to be just

Neil Armstrong

I tried in ckeditor profile under Advanced options:

config.allowedContent = true;
config.disallowedContent = 'span {color, font*, text-decoration}';

This is not working!

Hi You can use https://www.drupal.org/project/wysiwyg_filter
and configure him in /admin/config/content/ckeditor , content types


Server Error 500 - Edit Tab of Managing Custom Fields of Custom Content Types Alright, I've got a very irritating error with my site. Whenever I try and Edit a file or image field I get what appears to be a half-loaded page (see image below)

I have check an error log and have received this error at about the same time I was accessing this type of page...

 [15-Jun-2016 22:03:35 America/Denver] PHP Fatal error:  Allowed memory
    size of 134217728 bytes exhausted (tried to allocate 9332483 bytes) in
    /home/cocempro/public_html/portal/includes/database/database.inc on line 2171

And while double checking that maybe it wasn't just my browser, I also have received this error from Internet Edge (I don't normally use it, just thought I'd try):

SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. GET - http://example.org/admin/structure/types/manage/site-photograph-gallery/fields/field_-images

So is this with my server or my Drupal installation? I will clarify that I have found that no other field type (either text, date, summary, whatever) is affected by this, only file and image field types.

Any ideas?

------EDIT----
Oh and none of the other tabs (such as Widget settings, or delete) are affected by this error...

This turned out to be a max_post_limit issue, requiring I go from 128 to 256 on my PHP version configuration.


how to Add new Role employer also display in url like user/employer? the default roles anonymous user, authenticated user, administrator and i want to add new role  employer i did it people -> permissions -> roles -> add roles.
i want to create new sign up web form that employer user ? and i want URL like user/employer

You can do this by using any of below module :

Registration role module. After register your self by user can directly assign the role.

  Registration role lets an administrator select a role to automatically
  assign to new users. The selected role will be assigned to new
  registrants.

Webform Rules module.

  This module adds rules integration on webforms. Webform Rules makes it
  possible to catch webform submissions by rules and do whatever you'd
  like to do with it.

Auto Assign Role - This module definitely solve your both the issues i.e assigning role after registration & passing role on URL.

  The Auto Assign Role serves three primary purposes :

  Provide an automatic assignment of roles when a new account is
  created.
  Allow the end user the option of choosing
  their own role or roles when they create their account.
  Provide paths that will trigger a specific role when an account is
  created.

For the user/employer url you also do this by using Path Auto module.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.

Multiforms module.

  The Multiforms module is designed for the collection of data from
  users. It can be used to easily author multi-page forms which are
  published as nodes. The data collected by the forms can then be
  exported. It was originally designed to handle contest.


Clean output "View source" I just pasted a google analytics snipped into my template. When I preview the view source for the page, the script snipped is displaying all in one line.

How do I get it to display as it does in the page.tpl.php file?

I am using netbeans.

My guess is that you are running into EOL marker differences. That boils down to editor settings, and NetBeans copnfiguration help would be best at a sister side,  If the code works, then don't worry about it.

As a side note, I don't recall running into any situations that prevented me from using the normal Google Analytics module.  Recent versions let you adjust the code, so you should be able to match up with any tracking code you have.  In addition, you can configure it to ignore admins, track downloads, and do a lot more.


How to deny access if url is changed manually? Maybe the way I'm doing this is not the correct one but here it goes.

I have a page in my site where I have a form. In that form I have a select list that I fill with user ids from a query.

So for example, my site has 10 users and the list will be filled with only user 3 and 7.

When I submit the form, the url is changed to have the uid as a parameter:
&user=3 or
&user=7

My problem is that I can change the url manually to other user I want and I'm not denied the access.

How can I deny access in this case?

I've managed to solve this.

In my hook_form I have:

$querystring = drupal_get_query_parameters();

So for this case I just need to check if the user in the url is in the array of users allowed. If not, I can deny the access to the page (I still don't know how to deny the access though)


Profile2 -> Update node on submit? I have a specific user role with a profile attached too them. Every user with this role has a corresponding node with the same information that can be found on the user's profile. Now I'm looking for a way to keep the two in sync, so if you change the user's profile, it would update the corresponding node as well. Is there a way to hook in to Profile2's form submit handler, or something similar?

Can't you just add your own submit handler to the form you're talking about rather than trying to override an existing one?


Taxonomy term not getting invalidated I'm learning the new caching system. For testing purposes I have turned off Page Cache and Dynamic Page Cache.

I've set a custom block with the following:

<some code>
$build_array = $view_builder->view($referenced_entity, self::VIEW_MODE, self::LANG_CODE);

$build_array['#cache']['contexts'][] = "route";
$build_array['#cache']['keys'] = ['mymodule_panels_blocks','taxonomy_term', $term->id()];

This is for displaying an eck entity with an image that is attached to a taxonomy term.

The expected behavior is that when I point the term to a different eck entity, the taxonomy term is invalidated.

When I check the full list of tags (using http.response.debug_cacheability_headers: true) I see my taxonomy term listed (taxonomy_term:209).

So it would seem I'm all set up. Yet when I change the eck entity to a new one, click Save, then click View, I see the old image still.

When I flush the render cache, I see my new image.

Isn't the invalidation of the taxonomy term automatic when the term is saved? Or do I have to write a hook to invalidate the taxonomy term when it changes?

Yes, the invalidation is automatic. From the debugging you have done so far you only know that the tag is somewhere on the page, but you don't know where it is and obviously it is not where you want it to be. Look in the database table cache_render. Clear the cache, so that it is emptied. Now request the page with the block and check for all cached elements the column tags.

By the way, you don't need to set cache keys on a block, because blocks do this automatically and for the problem here it's confusing, because the taxonomy id you set in the keys is not invalidated.


Remove or hide the submit button on search block in Drupal 7 I need to do some custom theming on the search block in Drupal 7.

Specifically, I need to add a class to the submit button that makes it invisible and removes it from the content flow.  So:

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

Becomes...

  <input type="submit" id="edit-submit" name="op" value="Search" class="form-submit">

I added element-invisible to the edit-actions div element.  However, I can't figure out how to do this.  What's the best practice for doing this sort of thing?

One of the standard ways to do this would be to use hook_form_alter() and add the attributes to the actions element directly:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['actions']['#attributes']['class'][] = 'element-invisible';
  }
}


Disable search form in nav from collapsing Is there a way I can have my search form in nav bar not collapsed when screen size decreases? I'm using bootstrap on Drupal 7

You can change your markup using the page.tpl.php

Copy the page.tpl.php file from /bootstrap/templates/system to your theme.
Edit the page.tpl.php that you've copied.
Move the line 108 - 110 below / above the navbar-collapse collapse div.

Create a new div.
Put the code from line 108 - 110 into the new div.
Save
The changes should be like the screenshot below.

Flush cache


Mysql query that performs sums between different tables I am struggling to make a query in a custom service function in Drupal 7, which should make 3 sums. In each table (3), there are 2 records saved with the following values:

field_data_field_monto_15pts with field [field_monto_15pts_value] data: 5 and 6
field_data_field_monto_14pts with field [field_monto_14pts_value] data: 3 and 4
field_data_field_monto_13pts with field [field_monto_13pts_value] data: 1 and 2

The service function that performs the query and returns data in the JSON format is the following.

$cantidad = db_query('
  SELECT SUM(field_monto_15pts_value) AS 15pts,
         SUM(field_monto_14pts_value) AS 14pts,
         SUM(field_monto_13pts_value) AS 13pts
  FROM {field_data_field_monto_15pts},  {field_data_field_monto_14pts},  {field_data_field_monto_13pts}')
  ->fetchAssoc();

return $cantidad;

What I expect from the function is the following values.

{
  "15pts": "11",
   "14pts": "7",
   "13pts": "3"
}

What the function returns is this.

{
   "15pts": "44",
   "14pts": "28",
   "13pts": "12"
}

What is wrong in the code I am using?

Well ... Since no one had this problem, or nobody has a solution, I put the solution that I have given on the site https://www.drupal.org/node/2898276

The problem is how I wrote the query to the database. A Cartesian product is produced. After rewriting the query was solved. It was finally written:

$lo_que_che= db_query('SELECT (SELECT SUM(field_monto_15pts_value) AS 15pts FROM {field_data_field_monto_15pts}) 15pts, (SELECT SUM(field_monto_14pts_value) AS 14pts FROM {field_data_field_monto_14pts}) 14pts, SUM(field_monto_13pts_value) AS 13pts FROM field_data_field_monto_13pts}') ->fetchAssoc();  return $lo_que_che;


How do I see *which user* last updated a node? In admin/content, how might I override this display to list the User who last updated a piece of content. We can see the initial author and that's fine. But I'd like a running trail on who touched a node.

What I've tried

Revisions: However, some Content Types use a field by Jquery Tabs which lose their content when going back to a certain revision.

Use Administration Views module to replace default content page for admins.

Find new View created by that module and add Relationship -

Content revision: User

Then add field to your View "User: Name" and use that relationship on it. It will show you the username of the User who edited content last.


Date popup in exposed filter I'm using Drupal 7 with views 3.

I have used an exposed filter for a date field and I want to provide option to choose date from datepopup for date filter? How can I do this?

The Better Exposed Filters module integrates with the date type fields, including the date popup. You can use this module to easily add an exposed filter with the date popup.

There are some known issues with BEF's integration with the date module; from the module page:

  (Note: Support for fields supplied by the Date module is a little funky until #392836: Exposed Date filter format (in Views) and/or #502824: Date format in exposed filter (views) are resolved).

Also, you can only add this type of filter to entity fields at the moment, not properties. There are various discussions going on about this.


How to update from Drupal core 8.5.0 to 8.5.5? In the past (Drupal 7), security-only update via drush was simple as:

drush up --security-only

now, Drush 9.3 returns:

  Command "up" is ambiguous.
  Did you mean one of these?
  ...

composer does not help either:

composer outdated drupal/*

returns nothing.

In fact, my Drupal is outdated:

How can I update Drupal security updates via command line?

UPDATE (composer prohibits):

$ composer prohibits drupal/core:8.5.5
There is no installed package depending on "drupal/core" in versions not matching 8.5.5

It's all here Update core via Composer.

Short version, turn on maintenance mode

drush sset system.maintenance_mode 1

then run

composer update drupal/core --with-dependencies
drush updatedb
drush cr

Turn off maintenance mode

drush sset system.maintenance_mode 0

  If you run the composer update command above but drupal/core is not
  updated, there might be another dependency holding back the Drupal
  upgrade. You can check for blocking dependencies using the command
  composer prohibits. For example, if you are trying to upgrade from
  8.4.5 to 8.5.0, you can run composer prohibits drupal/core:8.5.0, and it should give a list of dependencies blocking the upgrade. Update
  those dependencies along with drupal/core and it should work (e.g.
  composer update drupal/core symfony/* --with-dependencies).


Move user profiles under a menu item In Drupal 7, currently when I go to a user profile, the breadcrumbs go as follows: "Home > username."
I have a People section as part of my main navigation, so I would like the breadcrumbs to behave more like: "Home > People > username."

How can this be accomplished?

There are two possibilities: You can implement a hook in a module, or implement a theme function in the theme you are currently using.

Module

In Drupal 7, you can implement hook_menu_breadcrumb_alter(). The hook implementation receives the current breadcrumb array by reference, and the menu item for the currently visualized page. The example provided in the documentation page is the following one:

function hook_menu_breadcrumb_alter(&$active_trail, $item) {
  // Always display a link to the current page by duplicating the last link in
  // the active trail. This means that menu_get_active_breadcrumb() will remove
  // the last link (for the current page), but since it is added once more here,
  // it will appear.
  if (!drupal_is_front_page()) {
    $end = end($active_trail);
    if ($item['href'] == $end['href']) {
      $active_trail[] = $end;
    }
  }
}

An example of implementation of such hook could be the following one ("mymodule" needs to be replaced with the short name of the module that contains the hook):

function mymodule_menu_breadcrumb_alter(&$active_trail, $item) {
  if (substr($item['href'], 0, 4) == 'user') {
    // Add a trail item before the one linking to the user profile page.
  }
}

For a method that can be used on Drupal 6 too (when you want to develop code that is for both Drupal 6 and Drupal 7, and you don't want to write code for each Drupal version), you can use drupal_set_breadcrumb() to set the breadcrumb for the user profile pages.

An example of how the function can be called is the following Drupal function:

function blog_view($node, $view_mode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    // Breadcrumb navigation.  l() escapes title, so we should not escape !name.
    drupal_set_breadcrumb(array(l(t('Home'), NULL), l(t('Blogs'), 'blog'), l(t("!name's blog", array('!name' => format_username($node))), 'blog/' . $node->uid)));
  }
  return $node;
}

You could alter the menu callback for the menu items associated with the user profiles, and use a menu callback that first sets the breadcrumb, and then calls the original menu callback. The hook to implement in this case is hook_menu_alter().

Theme

As far as I recall, a theme can also implement some alter hooks as a module does; alternatively, a theme just overrides a theme function ("mytheme" needs to be replaced with the short name of the theme).

function mytheme_breadcrumb($variables) {
    $breadcrumb = $variables['breadcrumb'];

    // Modify the breadcrumb.
}

The variable $breadcrumb is an array containing the HTML for the single parts of the breadcrumb.
The default implementation of the theme function is the following one:

function theme_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  if (!empty($breadcrumb)) {
    // Provide a navigational heading to give context for breadcrumb links to
    // screen-reader users. Make the heading invisible with .element-invisible.
    $output = '
' . t('You are here') . '
';

    $output .= '
' . implode(' » ', $breadcrumb) . '
';
    return $output;
  }
}

Between the two possible implementations, I would rather use a module, as it doesn't depend from the currently set theme; the theme can be changed, and the code would still change the breadcrumb. Generally, the code of a theme should alter the way elements are rendered, not to change the breadcrumb to alter the links it contains.


Issue with content access and multilingual system I have a multilingual website using English, Arabic and French. 2 days ago I noticed that anytime when I clicked on node/add/* for the English section, it returns an access denied page. And that is just for English (the other languages are fine and nothing wrong with them).

I use the Content Access module but even after I uninstalled it the issue remains the same.

I'm using Drupal version 7.32 and I18n 7.x-1.11.

Does anyone have an idea about this issue?

I see 2 possible explanations for your issue, as further detailed below. Consider checking both of them to see if either one of them apply in this case.

Cookie problem

It is possibly an issue with a cookie. So try the same scenario usiing another browser. If with that browser the problem does not occur, then it is probably a cookie problem. In that case, just delete the session cookie in the browser where the problem occurs. Then check if the issue is resolved.

Site may be hacked

Since the version of this Drupal site is 7.32, it might simply be that your site was hacked. Refer to SA-CORE-2014-005 (posted a week before this question was asked ...) for some more details.

For way more details about that, and possible approaches to do more research on that, refer to Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised?, which also suggests to use the Drupalgeddon module.


Load all titles and body text from one content type into array I'm working on an input format filter that should work as following. I have a content-type called glossary, the user can fill in a word (title) and description (body). Then there is a content-type article. When a word in the article matches a word in the glossary it should wrap that word with a span. Something like word. I already did a quick and dirty tryout and that worked fine. I already did a speed test and it worked out fine only a delay of 0.2s max.
But now I try to make it as it should and I got stuck.

The way I think this could work is to have an array with all words and descriptions from the glossary content-type in a array. And then search through the text.

So I created a Plugin/Filter/Filtername.php file. In this file I try to load all node from the glossary content-type (as advised) via dependency injection.

What I found is a way to get all nids, via this code added in to my filter class:

class FilterName extends FilterBase {
    public function __construct(QueryFactory $entity_query)
    {
        $this->entity_query = $entity_query;
    }

    public static function create(ContainerInterface $container){
        return new static(
          $container->get('entity.query')
        );
    }

    public function process(){
        $query = $this->entity_query
        $query->condition('bundle','woordenlijst');
        $nids = $query->execute();
    }
}

So this should give me all nids of the node I'm looking for but how do I get these node loaded to get there title and body text? I found this lesson about entity loading. Which is usefull but there are some deprecated functions used and I have no idea how to combine these to to get een array of titles and body texts.

So what is currently the best method to load nodes and how can I combine this with the code I already have? And am I even on the right path or not, or is there a better/easier way to do this?

Thanks in advance.

If yau have lots of node's than its difficult load all nodes at a time and also , to get only title and body, its not fair to load complete node.
Rather than load node and get values, we can use select query and fetch required values.

I am using cache concept here, once your query loaded, set it in cache untill any node values changes or any new node creates.
Use node hooks to remove cache for "node_data"
Below is the query:

  $nodedata = array();
  // Check cache exists
  $cache_node = \Drupal::cache()->get('node_data');
  if ($cache_node) {
    $array = $cache_node->data;
    $nodedata = json_decode($array, TRUE);
  }
  else {
    // Query for node title and body.
    $connection = \Drupal::database();
    $query = $connection->select('node', 'n');
    $query->leftJoin('node__body', 'b', 'b.entity_id = n.nid');
    $query->leftJoin('node_field_data', 't', 't.nid = n.nid');
    $query->fields('t', array('title'));
    $query->fields('b', array('body_value'));
    $query->condition('n.type', 'glossary', '=');
    $result = $query->execute()->fetchAll();
    foreach ($result as $key => $value) {
      $nodedata[] = array(
        'node_title' => $value->title,
        'node_body' => $value->body_value,
      );
    }
    // Set Cache.
    \Drupal::cache()->set('node_data', json_encode($nodedata));
  }
  dsm($nodedata);


Using Backup and Migrate Module to download windows compatible backup I have created a Drupal7 based web-site on my hosting server. I have made changes to the themes, created views and done other customizations. I would like to create a duplicate copy of the site on my local laptop, so that I can test my changes locally before making them live on the site. I installed the Backup and Migrate module on my host server and downloaded a backup of the entire site to my windows 7 laptop. I already have a WAMP installation and all required services running for creating drupal7 site.

The file I downloaded looks like a tar ball of the entire drupal folder and the DB and the size is 106 MB. Since, it is a tar ball I could not open the existing file in windows. My questions:

Is there a way to get around the tar ball? I tried specifying zip as the compression format, but that did not help. I do not see any option to specify no tar.
What is the correct way to create a copy of the site locally, considering I have made changes not only to DB, but other files too. I have seen other options such as exporting the DB and FTPing the sites folder. If I were to do this, how do I FTP the sites folder to my windows laptop?

Thanks

There's a couple steps you still need to do:

To "untar" the tar ball on Windows, you just need the right software for it. An easy to use and free software that supports TONS of compression types is 7-Zip -- http://www.filehippo.com/download_7-zip_64.
Once you have all the files available to you, you'll need to import the database into MySQL. Luckily WampServer comes with phpMyAdmin. You can find a link to it in the tray icon for WampServer. First create your database, then use the Import tab to load in the SQL file.
Modify the settings.php file to match the database database connection information for your local MySQL installation. The default installation of Drupal creates this file is at /sites/default/settings.php.
Then visit http:// my-local-host/ (or http:// my-local-host/[my-drupal-subdirectory]/) to see if it's working. (Replace "my-local-host" with "localhost" since StackExchange doesn't like "localhost" in a link).


Why direction nav transition not working on Flexslider module? I am using the following modules: Flexslider module (version flexslider 2.2), FlexSlider Views Slideshow Module and Views, in Drupal 7.

I build the slideshow, and define the Direction Nav (prev / next).

when I looked at the demo of the flexslider, I saw that these is a transition to the arrows when they are appearing and disappearing- it looks they are coming from the sides when I hover, and they going out when I stop hover.

unfortunately, I don't see any transition on my slider, and the the arrow just appear and disappear.

When I checked, I notice that the problem is that when I stop hovering, and then immediately hover again, I see that the transition is in fact happening, but it's only visible if I hover immediately again.

Does someone know what is the problem and can you help me solve this issue?

here is the direction nav code:

/* FlexSlider Default Theme
*********************************/
.flexslider { margin: 0 0 60px; background: #fff; border: 4px solid #fff; position: relative; -webkit-border-radius: 4px; -moz-border-radius: 4px; -o-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: 0 1px 4px rgba(0,0,0,.2); -moz-box-shadow: 0 1px 4px rgba(0,0,0,.2); -o-box-shadow: 0 1px 4px rgba(0,0,0,.2); box-shadow: 0 1px 4px rgba(0,0,0,.2); zoom: 1; }
.flex-viewport { max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; -o-transition: all 1s ease; transition: all 1s ease; }
.loading .flex-viewport { max-height: 300px; }
.flexslider .slides { zoom: 1; }
.carousel li { margin-right: 5px; }

/* Direction Nav */
    .flex-direction-nav {*height: 0;}
    .flex-direction-nav a  { display: block; width: 40px; height: 40px; margin: -20px 0 0; position: absolute; top: 50%; z-index: 10; overflow: hidden; opacity: 0; cursor: pointer; color: rgba(0,0,0,0.8); text-shadow: 1px 1px 0 rgba(255,255,255,0.3); -webkit-transition: all .3s ease; -moz-transition: all .3s ease; transition: all .3s ease; }
    .flex-direction-nav .flex-prev { left: -50px; }
    .flex-direction-nav .flex-next { right: -50px; text-align: right; }
    .flexslider:hover .flex-prev { opacity: 0.7; left: 10px; }
    .flexslider:hover .flex-next { opacity: 0.7; right: 10px; }
    .flexslider:hover .flex-next:hover, .flexslider:hover .flex-prev:hover { opacity: 1; }
    .flex-direction-nav .flex-disabled { opacity: 0!important; filter:alpha(opacity=0); cursor: default; }
    .flex-direction-nav a:before  { font-family: "flexslider-icon"; font-size: 40px; display: inline-block; content: '\f001'; }
    .flex-direction-nav a.flex-next:before  { content: '\f002'; }

I see the same issue sometimes.
When I look at my local direction anchors, they are display:none by default, but the WooThemes example they are display:block.
Also, obviously, the opacity and left/right css3 transitions don't work.

In Chrome you can test the :hover selector on the .flexslider element.

I have seen this work properly in some sites.

It looks like there's a responsive breakpoint at 860px that you need to consider, so I placed these styles at min-width:861px.
If you make these styles the default, the arrows will always be visible under 860px. This is why I put the styles at 861 and above.

Anyway, my approach to 'fixing' this was to simply reinforce the display, opacity, left/right, and transition settings in my theme CSS.
Not sure if all of this is necessary, but it does work :)

/** Media Queries: min 861 only Flexslider
------------------------------*/
@media (min-width: 861px) {
    .flex-direction-nav .flex-prev {
        -webkit-transition-property:left, opacity;
        -moz-transition-property:left, opacity;
        -o-transition-property:left, opacity;
        transition-property:left, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    .flex-direction-nav .flex-next {
        -webkit-transition-property:right, opacity;
        -moz-transition-property:right, opacity;
        -o-transition-property:right, opacity;
        transition-property:right, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    div.flexslider .flex-direction-nav a {
        display:block
    }
}


robots.txt vs language path prefix The default robots.txt shipped with Drupal contains rules such as this:

Disallow: /user/register/

If I understand correctly, the leading slash means this really has to match the beginning of the path. E.g. a path like /xyz/user/register/ would not match the rule. (Please correct me if I'm wrong)

(For the ending slash I am not sure)

With the language path prefix option, Drupal will have urls like /fr/user/register etc.

It can be assumed that if we want to exclude /user/register, we also want to exclude /fr/user/register and other language versions.

However, a /*/user/register/ might be too generic, as it also would match other urls which we don't want to exclude.

Questions:

Will Drupal's default robots.txt also exclude language-specific versions of the targeted urls? (according to my own assumption it does not).
What would be the simplest / cleanest way to exclude all language versions for a given path?

I think this applies equally to Drupal 7 and Drupal 8.

Whatever you are unhappy with, with Drupal's default robots.txt, delete it, and install RobotsTxt to provide an UI to let your SEO person edit the robots.txt according your needs.

  Use this module when you are running multiple Drupal sites from a
  single code base (multisite) and you need a different robots.txt file
  for each one. This module generates the robots.txt file dynamically
  and gives you the chance to edit it, on a per-site basis, from the web
  UI.

Look what I found. This duplicate issue on drupal.org robots.txt: add wildcarded paths for multilingual sites leads to this open issue Fix path matching in robots.txt, which actually could need your input.

But basically some commenters seem to recommend exactly what you came up with, wildcarding the path prefix.


Do I have to set a default value to a variable in Twig Normally in php I would have to set a default value to a variable but in Twig do I have to set a default value?

{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}

<div{{ attributes.addClass(classes).setAttribute('data-offset', offset) }}>

I think it works but not sure if I should do this:

{% set offset = ''  %}
{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}

It's controlled by a Twig environment setting, strict_variables:

  If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false).

Drupal doesn't change the default value, so if you also leave that setting at false you won't need to make sure variables exist before referencing them. In fact, if you set it to true I imagine quite a few core and contrib would start throwing exceptions.


drush sql-sanitize: exclude user #1? When I run drush sql-sanitize, is there a way to exclude user #1 (or specific other users, for that matter) so his email address and password are not changed?

There's no such option in drush, all users are sanitized.

As a workaround you can save the user 1 data (or any other user you want) with drush sqlq and restore after sanitization.

Using bash:

user_data=$(drush sqlq "SELECT pass, mail FROM users WHERE uid = 1"| tail -n1)
user_pass=$(echo $user_data | cut -f1 -d" ")
user_mail=$(echo $user_data | cut -f2 -d" ")

drush sql-sanitize ...

drush sqlq "UPDATE users SET pass='$user_pass', mail='$user_mail' WHERE uid = 1"


Why do I get a Drupal\Core\DependencyInjection\ContainerNotInitializedException exception error? I am using Drupal 8.1.3, Drush 8.1.7, and PHP 5.6.2 on a Mac OS X.

I've installed a fresh Drupal 8 site demo from Zircon on a local MAMP stack. When I try to run watchdog show, and some other commands, I get the following error:

  Drupal\Core\DependencyInjection\ContainerNotInitializedException: \Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container. in Drupal::getContainer() (line 129 of /Applications/MAMP/htdocs/example/docroot/core/lib/Drupal.php).

I was able to run the following commands successfully:

drush cr
drush version
drush status

I've just updated to latest version of drush, but this is my first time seeing this error.

Also, drush pm-update returns:

  Command pm-update needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.

Edit/Update:

Here is the output of drush status:

Drupal version         :  8.1.3
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  ******
 Database name          :  ******
 PHP configuration      :  /Applications/MAMP/bin/php/php5.6.2/conf/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.7
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Applications/MAMP/htdocs/example/docroot
 Drupal Settings File   :  sites/default/settings.php
 Site path              :  sites/default
 Sync config path       :  sites/default/files/config_pHswhbzOqqMuWn7c6kYMbap6DKcyXxItrvbtsCQeJYoQ04xTi19pOZywbF8KZ8Wrx43VrLsVMw/sync

The user interface does work.

Update: I checked some of my other projects (Drupal 7 and 8 sites), for which drush worked perfectly fine on, and they are throwing errors with the same Drush command, which tells me it's probably not a Drupal 8 problem but probably due to changes I made on my dev platform. I had installed Composer and upgraded Drush, and other related changes.

I had the same problem with Drush throwing an exception for a test site on localhost. I was able to access the site from the browser, from where I didn't get any error message, not even a message from a exception handler. This puzzled me, since the site was clearly working.

It started to work again when I changed the file permissions for the Drupal files. The user account I was using to execute the command line was missing the permission to write in some directories.


Filter view from $_GET parameters I have a classic view with fields from classic nodes. I have made a custom form that reload the view with parameters :

mypage?nid=168

But to display only the wanted data, my view use CONTEXTUAL FILTERS and need this format :

mypage/168

How can I filter my view from $_GET parameters.

Use "Global: PHP" field to get the required parameter value. If views_php is not installed, then use this link, views_php to install the module and give the permission using admin/people/permissions.

Go to your Views -> CONTEXTUAL FILTERS -> ADD -> Select "Global: PHP" then you can retrieve the parameter using $_SERVER[QUERY_STRING] and retrieve the value.

And also you can use $_GET['nid'] to get the value.


Where is place $content in node--product--type.tpl.php be generated and manipulated in drupal commerce? I am a beginner of drupal commerce, I know Drupal Commerce display product with node--product--type.tpl.php, "render($content)" does this work.

I need to add a property "monthly sales" to each node(product display) so that I can display it in node page.

With drupal core, I can use hook_load and hook_view to display custom properties, but it seems Drupal Commerce doesn't work by this way.

Where is place the array $content be generated and manipulated in Drupal Commerce? Which hook can I use?

Appreciate for any help or comments.

I got it, It's hook_entity_view. We can read profiles\commerce_kickstart\modules\contrib\commerce\modules\product_reference\commerce_product_reference.module for reference.


How should I replace jQuery UI dialog? I try to use jQuery UI dialog.
Based on this, I put this in a node:

        This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.

    Some stuff...

And it works! The popup window shows up automatically when the node is displayed.
But I noticed that jQuery is deprecated in Drupal 8.
So, how should I do the same thing in a more "Drupal" way?

[EDIT] Making progress...
@leymannx Using the 1rst example of Ajax Dialog Boxes page you provided, I get this working (see the screen capture).
My next step: how to have the dialog box displayed automatically when the page is reached without having to click the link?

jQuery hasn't been deprecated. Some unused jQuery UI components have been deprecated in 8.8 and will be removed in Drupal 9.0. core/jquery.ui.dialog is not among them.

[8.8 issue] Deprecate unused jQuery UI components in favour of a suite of contrib modules
[8.8 change record] Deprecated unused jQuery UI asset libraries
[9.0 issue] Remove deprecated jQuery UI components and fork remaining source code into core
[9.0 change record] jQuery UI source added to Drupal core and deprecated code removed

Nonetheless there's the new Dialog API. For that you have to require the core/drupal.dialog library or the core/drupal.dialog.ajax library for more advanced stuff. Some examples can be found in the docs on Ajax Dialog Boxes. The following sample requires the core/drupal.dialog.ajax library.

  This link opens /node/1 in a modal dialog box:

<a class="use-ajax"
    data-dialog-options="{&quot;width&quot;:400}"
    data-dialog-type="modal"
    href="/node/1">
    First node displayed in modal dialog.
</a>

What you currently do in your code sample hasn't much to do with Drupal at all. To do it the Drupal way check the docs on adding JS/CSS to your module or theme first. You could attach the library simply to your theme or directly to all nodes of a given type for example.

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


phpwkhtmltopdf engine pdf printing configuration issues The screenshot below shows my Entity Print configurations for created styled PDFs from node content.

As shown in the screenshot I am using the phpwkhtmltopdf engine and the mikehaertl/phpwkhtmltopdf package is installed via composer.
However, when I try generating the target PDF, the following errors results:

Error generating document: Failed to generate PDF:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 1:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: cannot open
?php: No such file
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 2:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: namespace:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 4:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: use: not
found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 6:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: /bin:
Permission denied
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 7:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 8:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 9:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: INSTALL.txt:
not found /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php:
10: /opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php:
INSTALL.txt: not found
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: 12:
/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: Syntax
error: newline unexpected

I gave Pdf.php 777 permissions too.
Can anyone help, please?

/opt/drupal/vendor/mikehaertl/phpwkhtmltopdf/src/Pdf.php: cannot open
?php: No such file

You need to install the missing library using composer
composer require mikehaertl/phpwkhtmltopdf

In addition, you might also need h4cc/wkhtmltopdf, see Entity Print documentation


Custom Date Format Not Available to my Date Field I'm sure I'm missing something super simple, but for some reason, my date field that I've created cannot make use of the "custom format" option in Views. I'm using D7 7.22 and the Date Module, 7.x.2.6

I've noticed that the field that I created is labelled differently than a normal date field which is "content: post date".

Mine is labelled, "Choose how users view dates and times"

The regular field is labelled simply "date format"

I've created a content type that has a date field with day, month, year, and time specified for each node. It doesn't matter which formatter I select - plain, time ago, date and time -  I do not have the option for a custom format for this field and I'm baffled. I can see the custom formats I created at admin/config/regional/date-time but no option for a custom format in Views.

I need to reformat the output of the values in contained in that field so that I can theme it appropriately, and will roughly be following this: http://highrockmedia.com/blog/theming-views-post-date-drupal-7-date-parts

Any ideas on why this would not be an available option? I've cleared all caches, removed and recreated the field - everything I can think of but I can't find anything on why I cannot use that field in Views.

You can see the difference in this screen grab: http://bit.ly/1cGQMkY

Thanks in advance

They seem to be build differently, you really can't do that I guess. But do this:

Add a new format at admin/config/regional/date-time/formats. Then add a new Date type at
admin/config/regional/date-time and here select your new format. Then you can select this in the view.


How to get field Type from View I have a view that takes fields and combines them or compares them and then gives me results in a new field (views conditional, global text etc..) but I need the TYPE of data that is returned. How can I figure this out? I do not have Drush on my current setup or we'd be good to go... I looked in the DOM and see nothing special about the field for example...

Use Php views and in it  use gettype, I think you can acheive it by Php views ( also you can achieve it with hook_views_pre_render) and return data tye with gettype.

gettype — Get the type of a variable Description
string gettype (mixed $var )
Returns the type of the PHP variable var.


Control Fieldset Width in a Block? Anyone know how to control the width of a drupal fieldset that's in a block? I have a custom block that I've added 3 fieldsets to using the same exact fieldset code in each, however out of the three, the top one's width is fine, the middle one's is overflowing into the middle column, and then last one is fine. The screenshot shows the top block and the "broken one below it. I want the width to be the same as the top block, which is automatically setting it's width the same as all of the rest of the other blocks in the same column.

Screenshot

I would do this with CSS as @Ivanhoe123 suggested.

fieldset {
    width: 100px;
}


Custom validation of route parameters I have something like the following on my .routing.yml file:

my.path:
  path: '/my-path/{node}'
  defaults:
    _form: 'Drupal\mymodule\Form\MyForm'
  requirements:
    _entity_access: 'node.update'
    node: \d+

This works fine, it checks that the user has permissions to edit the node and all. Now, I want to restrict this route to work only for nodes of a certain content type. Ideally, something like this as the final line:

    node.bundle: 'article'   # this doesn't work, of course

How can I do this?

I could find three possible ways. Supposing your module name is example and content type to check is article.
1. Validating the argument in the form builder
It is the simplest way.
First define your route as usual:
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'

Then simply put these lines to Drupal\example\Form\ExampleNodeForm::buildForm before the other code.
if ($node->getType() != 'article') {
  throw new AccessDeniedHttpException();
}

2. Validate the argument using custom access callback
The route definition is the same as above except custom_access option under the requirements section.
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'
    _custom_access:  'Drupal\example\Form\ExampleNodeForm::access'

Drupal\example\Form\ExampleNodeForm::access() should return instance of Drupal\Core\Access\AccessResult. This can be done as follows.
return AccessResult::allowedIf($node->getType() == 'article');

3. Validation the argument with access checker
example.routing.yml
 example.node.edit_form:
  path: /example/{node}/edit
  defaults:
    _form: 'Drupal\example\Form\ExampleNodeForm'
  options:
    _node_operation_route: TRUE
    parameters:
      node:
        type: entity:node
  requirements:
    _permission: 'edit any article content'
    _content_type:  'article'

As you can see this includes _content_type requirement. To make it work you need to implement custom access check service.
example.services.yml
services:
  example.content_type_access_checker:
    class: Drupal\example\Access\ContentTypeAccessCheck
    tags:
      - { name: access_check, applies_to: _content_type }

Drupal\example\src\Access\ContentTypeAccessCheck.php
namespace Drupal\example\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\Routing\Route;

/**
 * Checks if node type matches the one provided in the route configuration.
 */
class ContentTypeAccessCheck implements AccessInterface {

  /**
   * Access callback.
   */
  public function access(Route $route, NodeInterface $node) {
    return AccessResult::allowedIf($node->getType() == $route->getRequirement('_content_type'));
  }
}

The last approach can be helpful if you want to reuse access control code accross multiple routes.
Documentation: https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes.


Make interaction between multisites Well look I have a multisite.

The main site that uses the sites/all folder for its modules and libreries
and another subdomain that uses sites/subdomain for its modules, themes, etc...

they are in separate databases but share the same drupal instance

In the main site I have an inventory app for a local store they manage their inventory and their invoices there.

In the subdomain I did a ecommerce store so they will sell their products through that subdomain, I need that when an user buys a product in the ecommerce store ten automatically I need that purchase to be registered in the inventory that is in the other site.

How to do this connection betweed the 2 sites in a multisite config?

Thanks for your help

The "standard" way of creating multiple sites with some interaction between them using Drupal is to use the Domain Access module rather than multisites.

However, there is great write-up about using interacting multisites at Drupal Redesign: Domain Access vs. Multisite.

The gist of it is that you set up a multi-site as you normally do. Then you create a custom module to take care of interaction and sharing data between the sites.

Drupal can handle multiple databases, but you can avoid the complexity of managing multiple databases by using a single database and use a database table prefix to avoid namespace collisions.  If you already have created the databases as separate databases, you need to use hook_update_N (or SQL operations outside of Drupal) to refactor the schemas.


.info file having a name that is different from the name of the theme's folder My .info file is prosperpro.info, but my theme's folder is named prosperpro8. I had not realized this difference because the code was working. When I realized this, and tried to changed the .info file back to prosperpro8.info, the code would no longer work.

I thought that the .info file required to have the same name of the theme's folder.

Am I wrong? If they must have the same names, how can I correct it? (Changing the file name will result in code break.)

You cant give same name for theme and module.
I have found an article on drupal.org

  How to Resolve module-theme name collision

  When developing a site it can happen that a module and theme are being
  given the same name. This results in very weird behavior: overriding
  hooks can make your blocks disappear, print $content returns only
  'array', hence disappearing admin interfaces which force us to alter
  the database to get back on track.

  Now we have to find out how to remove the new theme and switch back to
  an old one. if your site is big, with lots of content, then
  reinstalling is not an option. I tested this with MySQL, so these
  hints are for MySQL only.

  Make a backup of your database first. We are going to edit the dumped
  records, and reinsert the database. I used this method because using
  my favorite editor is way easier and safer than using MySQL shell
  (anyway we shouldn't edit a live site database).

  The theme name is registered in the following tables in your database:
  system, variables and block. Clear the cache manually, meaning to
  remove all the INSERT INTO cache_ lines in order to see results.
  Change the 'default_theme' value in system. Note that 's' stands for
  string length, so be sure you put the string length after the 's:'.
  Also make sure you change the value to an existing theme (available
  themes are listed in system). And remove, or rename your troublesome
  theme.

  The change in block is imperative, otherwise the blocks will not
  appear. Drop your old database from the sql server and insert the
  edited one. Voila, we have recovered from a theme crash.

© drupal.org

And

Never give a module and a theme the same name

Here's the D7 Patch


Paragraphs Align Media Left or Right of Text with CSS I am using Paragraphs module to create a cutom paragraph. The custom paragraph will have three fields: Image, Text and Position. Would like to use css to align as follows based on the value of the Position field.

Image Left  | Text Right

Text Left | Image Right

Image Top / Text Below

How do I go about doing this? Do I need any extra configuration for the paragraph? Or is all the magic done in CSS?

Yes, just CSS. You could use Classy Paragraphs to append CSS classes to your paragraphs depending on some field values, or you can do this very easily yourself (recommended) by preprocessing the paragraph in your theme's *.theme file.

Let's assume the position field is a single-value List (Text) field with the following allowed values:

image-left|image-left
image-right|image-right
image-top|image-top

Then you can easily retrieve that value and append it as CSS class by implementing hook_preprocess_HOOK:

/**
 * Implements template_preprocess_paragraph().
 */
function MYTHEME_preprocess_paragraph(&$variables) {

  $paragraph = $variables['paragraph'];

  // Retrieve certain field's values and add them as CSS classes.
  $classy_fields = [
    'field_image_position',
    'field_background_color',
    'field_social_media_type',
  ];

  foreach ($classy_fields as $classy_field) {

    if ($paragraph->hasField($classy_field)) {

      if (!$paragraph->get($classy_field)->isEmpty()) {

        $variables['attributes']['class'][] = $paragraph->get($classy_field)->getString();
      }
    }
  }
}

Which will result in image-right or whatever other class getting appended to this paragraph's attributes and it now can by styled accordingly:

<div class="paragraph-MYPARAGRAPH view-mode--default image-right">


How insert values from client page to database by use custom module Help me pls. I need update database table in Drupal 8. Exemple on image.

When user click on button "ADD PRODUCT TO CART", cart value must update on page (its not a problem), cart value and user ip-address must be write to database.
Im try use ajax for this logic, but values do not write to database.
Js code:

jQuery('.cart button').on('click', function () {
var price = jQuery('.price').text();
var priceValue = parseInt(price.substring(0, price.length - 1));
var cart = jQuery('#cart');
var cartValue = parseInt(cart.text().substring(0, cart.text().length - 1));
cart.text(cartValue + priceValue + '$');

jQuery.getJSON("http://jsonip.com/?callback=?", function (data) {
    var ip = data.ip.toString();

    jQuery.ajax({
        type: "POST",
        url: "../myupdate.php",
        data: ["ip="+ip, "cart="+jQuery('#cart').text()]
    }).done(function () {
        console.log('done');
    }).error(function () {
        console.log('error');
    });

});

});

php code:

<?php
$ip = $_POST[ip];
$cart = $_POST[cart];
db_insert('abweb')
    ->fields(array('ip' => $ip, 'product' => 'some product', 'price' => $cart))
    ->execute();

This logic is implemented in the custom module. HELP PLS!!

Here is way to do this. use line item type and create your filed.  Hook_commerce_cart_product_add() call in custom module.

  function mymodule_commerce_cart_product_add($order, $product, $quantity, $line_item) {

         $commerce_line_item = commerce_line_item_load($line_item->line_item_id);

         $field_main = $product->field_main['und']['0']['value'];

         $line_item->field_update[LANGUAGE_NONE][0]['value'] = $field_main;

         commerce_line_item_save($line_item);
     }

When user click on button "ADD PRODUCT TO CART", cart value add/update your commerce line item field.


How to clear cache for config entity after making changes? We have a custom form mymoduleForm that has mymodule.settings which stores some values that we need to run some logic when calling mymodule_preprocess_node() hook. The form just has a text area where we insert URIs and use that in the mymodule_preprocess_node hook to perform some action.

We can store the values in a Config entity as expected (see below). When we make changes to the Config entity, we want to clear cache for the config entity as well. How can we clear the Config Entity's Cache after making changes?

Goal:

When there are updates to the Config entity, clear the cache for the entity so that the latest entity is used in mymodule_preprocess_node hook.

Issue:

When we make changes to the Config entity using the custom form, the logic that we need to run is not running with the latest settings.

What we have tried:

Tried adding addCacheableDependency($form, $config);  to the buildForm(), but it is not working.

mymoduleForm.php

class mymoduleForm extends ConfigFormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    if (!$this->entity->isNew()) {
        \Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
      }

    $config = $this->config('mymodule.settings');

    $form['some_field'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Some field title'),
      '#description' => $this->t('some description'),
      '#default_value' => $config->get('some_field'),
    ];

    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('mymodule.settings'),
      ->set('some_field', $form_state->getValue('some_fields'))
      ->save();
  }
}

mymodule_preprocess_node

function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}

Yes, you have to add the cacheable dependencies of the config object, not only to the form, but also to the render array in preprocess, so that the rendered output gets the correct cache data:

function mymodule_preprocess_node(&$variables) {
  $config = \Drupal::config('mymodule.settings');
  $config_value = $config->get('some_field');
  // add the cache tag, so that the output gets invalidated when the config is saved
  \Drupal::service('renderer')->addCacheableDependency($variables, $config);

  $library = 'mymodule/some-library';

  if($config_value == 'some_value') {
    $variables['#attached']['library'][] = $library;
  }
}


Seven subtheme not inheriting correct block structure I am using Drupal 8.

I have subthemed the Seven theme so we can add some minor customisation to the admin theme.

The new theme however is getting all the active theme's blocks thrown into - seemingly - random blocks inside its regions.

I want to create a subtheme which initially is identical to seven and can be activated across several sites with predictable block placement.

I don't want users to be put in a position were they have to go through and manually move/disable blocks after turning on the new admin theme. This is especially true given the clunky nature of adjusting block placement on the admin theme; every time you disable/delete a block and save the change it takes you back to the ACTIVE theme block page rather than the admin one...

Is there a way to do this?

You can provide custom block configurations in config/install as with a module. As soon as there is at least one block, Drupal will not add any additional blocks, if there are none, it will copy those from the default theme.


Where to define permissions for user roles in FCKEDitor file uploads? There is this page where you upload files with FCKeditor
My admin user can do that , but I want the same for the Editor role
(I already defined a profile for it)
It´s a matter of permissions and I´ve enabled all on the FCKEditor but I´m sure it´s something else...that I have to enable...

Are you using the IMCE module for file uploads/directory? It could be a setting there that you need to enable.


How to find which content type is using which context? How to find which content type (abc) is using which context? As I do have around 30 contexts in my site.

Is there a way to find which context is using content type (abc)?

Here are some module suggestions that may help get you closer to find the exact answer to your question:

Context Inspector block provided by the Devel module

If you use the Devel module you'll have a "Context Inspector" block. You can place that block in a region on a page and then see the current contexts output via Krumho.
Devel Catcher module

To enhance your "debugging" experience (hm, hm ...), there is also the Devel Catcher module, which has Devel as a module dependency.

Here is an excerpt from its project page (why you may want to consider this module):

  ... aggregates or "catches" all development debug info into one easy to access place.

  Similar in style to Firebug or Chrome's Inspector. Devel Catcher intercepts common debug info into a tabbed interface as opposed to having to assign debug blocks to a region or dumping the output at the end of your HTML document.

  Currently Devel Catcher can catch the query log from the Devel module, node access rules from the Devel Node Access module and the context inspector block from the Context UI module.

So by using (repeating) this approach for a page of each of your content types, you might be able to find out which content type is using which context, no?


local drush - installation failed I recently manually upgraded to Drupal 8.4, from 8.3 because I couldn't get drush to work. I'm now trying to install drush locally as this seems to be the recommended way from the drush documentation. (I removed the global install of it I had), but I get the following errors (below).

[www public_html]$ composer require drush/drush
Using version ^8.1 for drush/drush
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - drush/drush 8.1.0 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.1 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.2 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.3 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.4 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.5 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.6 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.7 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.8 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - drush/drush 8.1.9 conflicts with drupal/drupal[No version set (parsed as 1.0.0)].
    - Conclusion: don't install drush/drush 8.1.14
    - Conclusion: don't install drush/drush 8.1.13
    - Conclusion: don't install drush/drush 8.1.12
    - Conclusion: don't install drush/drush 8.1.11
    - Conclusion: don't install drush/drush 8.1.10
    - Conclusion: don't install drush/drush 8.x-dev
    - Installation request for drupal/drupal No version set (parsed as 1.0.0) -> satisfiable by drupal/drupal[No version set (parsed as 1.0.0)].
    - Conclusion: remove symfony/console v3.2.8
    - Installation request for symfony/dependency-injection (locked at v3.2.8, required as ~3.2.8) -> satisfiable by symfony/dependency-injection[v3.2.8].
    - Installation request for drush/drush ^8.1 -> satisfiable by drush/drush[8.1.0, 8.1.1, 8.1.10, 8.1.11, 8.1.12, 8.1.13, 8.1.14, 8.1.2, 8.1.3, 8.1.4, 8.1.5, 8.1.6, 8.1.7, 8.1.8, 8.1.9, 8.8.x-dev, 8.x-dev].
    - Conclusion: don't install symfony/console v3.2.8
    - drush/drush 8.8.x-dev requires symfony/console ~2.7 -> satisfiable by symfony/console[2.7.x-dev, 2.8.x-dev].
    - Can only install one of: symfony/console[2.7.x-dev, v3.2.8].
    - Can only install one of: symfony/console[2.8.x-dev, v3.2.8].
    - Installation request for symfony/console (locked at v3.2.8, required as ~3.2.8) -> satisfiable by symfony/console[v3.2.8].

Installation failed, reverting ./composer.json to its original content.

Download this:

https://dev.acquia.com/downloads

Then install it in one click.

After your site is installed, click on the left on +more.

Once you click on that, console pop ups and Drush is installed and working, turn key


$node->type and $node problems The following doesn't work after calling the $node->type. Can someone help?

$nid = 0;
$term_1 = "";

if (arg(0) == 'node' && is_numeric(arg(1))){
$nid = arg(1);

$node = node_load($nid);

if(true == strpos($node->type,'article'))
{
    $result = field_view_field('node', $node, 'field_tags_test', array('default'));
    $term_name = isset($result['#items'][0]['taxonomy_term']->name) ? $result['#items'][0]['taxonomy_term']->name : "";
   }
 }

If I take out the inner if-statement, then it works just fine.

Thanks for any help.

strpos() returns the zero-based offset of the first occurrence of the test string. So if your string is article and the node type is article, it will return 0.

Your if statement is basically doing this check:

if (true == 0) { ...

Since 0 is a boolean FALSE in PHP the condition isn't satisfied, and the if construct is never entered.

There are a few ways you can change the if statement which basically boil down to the same thing:

if ($node->type == 'article') {
if (strpos($node->type, 'article') !== FALSE) {
if (strpos($node->type, 'article') === 0) {


Access denied on Password Recovery page I tried to customize the "password recovery" page under Drupal 7, based on this tutorial : http://www.absolutecross.com/tutorials/drupal/theming-the-user-account-page-in-drupal.
I did so for the register and edit page, and it works ok.

However, for this page, I run into a problem. When the page "/user/pass" (is that the standard url by the way ?) is called, I ran into an access denied page.

I browse through the permissions : nothing in there to allow/deny access to this page. I also use loginToboggan, disabled it for a while, to no avail.

Any idea of what I could I have overlooked ? I am lost...

Thank you.

The password recovery page is at "/user/password", not "/user/pass".

I also get an Access Denied when visiting "/user/pass" on one of my sites, whether I'm logged in or not, so I think you can assume this is the expected behaviour for that particular path.


How can I add a link to users of an organic groups in views I have a views which lists groups (I am using drupal commons distribution). I like to add a link in this view to members of that group.
Any idea how this might be accomplished?

Thanks.

Build a new view or block listing users and limit access to members of the users of group. Go to you current view and add a link to the new view or block.

Got to Structure>Views and add a view. Name and set to Users

Set groups fields and filter to specific group.

Change the page URL

Save

Copy url of view and go to existing view and create the link.


How do I send an email from a module using an Easy Email module email template? I am creating a form that needs to send an email upon form submission. I want to use the Easy Email module to send HTML emails. I want to send an email from my module, using an Easy Email template. How can I send an email from my custom module using an Easy Email template?

Sending an email from a custom module using an Easy Email template requires the following steps:

Create a new Easy Email template
Implement [MODULE].emails.yml
Tell the system to use the template from step 1 when sending the mail from your module
Send the mail from your module
(Optional) - Export and save configuration to your module

This example will show how to send an email to admins with the role site_admin when a group (using the Groups module) has applied for a review of some kind. The email requires the Group entity, to provide the group name and a link to the group.

1) Create a new Easy Email template

The email in this example will require a new template, with an entity reference field on the template for the Group entity that the email will refer to.

Navigate to Admin -> Structure -> Email Templates and click 'Add Email Template'.
Enter a name for the template, and make note of the machine name (the email template key). Save and proceed
In the template, set the following field values:

From Name: [site:name]
From Address: [site:mail]

Save.
Find the template you just created in the list, and under 'Operations', click 'manage fields'
Add an entity reference field to the Group entity and save
Back on the email templates listing page, edit the email. Group fields are available as tokens in the template body due to the entity reference to the group. The recipient of the mail is also available, and [easy_email:recipient_uid:0:entity:display-name] will provide the name of the recipient. Example email:

[easy_email:recipient_uid:0:entity:display-name],

The group [easy_email:field_group:entity:title] has submitted an application for something. Please review it.

&nbsp;

Thank you,

--&nbsp; [site:name] team

2. Implement [MODULE].emails.yml

Next, [MODULE].emails.yml needs to be implemented, so that the Easy Email module knows to override the email.

Note that this will require an arbitrary key for the email, that will be used to send the email from the module in step 4. In this example, the email key is group_something_application_received.

# This is the ID of the email override. I have keyed it by
# [ENTITY TYPE].[MAIL KEY].
group.something_application_received:
  # Re-use of the same ID above.
  id: 'group.something_application_received'
  # A label to be shown on the email override interface.
  label: 'Group: Custom domain application received'
  # This should be replaced with the machine name of the module.
  module: 'example'
  # The email key. This will be used by the module to send the email.
  key: 'group_something_application_received'
  # An array of parameters. At a minimum, account will be required for
  # the recipient of the email. In this example, Group is also required
  # to fill in the group values of the template.
  params:
    account:
      type: 'entity:user'
      label: 'Account'
    group:
      type: 'entity:group'
      label: 'Group'

3) Tell the system to use the template from step 1 when sending the mail from your module

The next thing is to link the email the module will send to the template created in step 1.

Navigate to Admin -> Structure -> Email templates
Click the 'Overrides' tab (note - requires the Easy Email Override module to be enabled)
Click 'Add Email Override'
Give it a label. Under 'Email to override', select the value entered for 'label' in `[MODULE].emails.yml'. Under 'Easy email template', select the template created in step 1. Save.

4) Send the mail from your module

Finally, emails can be sent using the system default email manager. The Easy Email manager will handle the rest of it. In this example, the email is being sent from the submission handler of a form that stored a Group object in the form state.

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
  $group = $form_state->get('group_entity');

  // Do some submission stuff (not shown).

  // Get the UIDs of all users with the site admin role.
  $uids = $this->entityTypeManager->getStorage('user')->getQuery()
    ->condition('status', 1)
    ->condition('roles', 'site_admin')
    ->execute();

  // Load the admins.
  $admins = User::loadMultiple($uids);
  // Loop through the admins, and send the email:
  foreach ($admins as $admin) {

    // Send an email to the admin using the mail manager.
    \Drupal::service('plugin.manager.mail')->mail(
      // The module machine name:
      'example',
      // The email machine name (use the same one declared in [MODULE].emails.yml)
      'group_something_application_received',
      $admin->getEmail(),
      $admin->getPreferredAdminLangcode(),
      // Populate the parameters declared in [MODULE].emails.yml:
      [
        'account' => $admin,
        'group' => $group,
      ]
    );
  }
}

5) (Optional) - Export and save configuration to your module

This step is optional insofar as the module will send mail after completing step 4. However, if the module is to be used in multiple systems, default configuration should be exported from the system and saved to the [MODULE]/config/install directory. The configuration exported should be:

Template configuration for the easy email template
Override configuration for the email override

Note that if you wanted your module to easy-email compatible, but not dependent, you can put the configuration in [MODULE]/config/optional, and do not declare the Easy Email module a dependency. This way your configuration will be used if the Easy Email module is already installed on the system, but will not require it. If you do take this path, you'll also need to implement hook_mail() in your module and react to the key group_something_application_received to create the email text that will be sent when the Easy Email module is not installed.


Can I make a Views "Rendered Node" field not be linked to the original node? I have a view that outputs rendered nodes. Setting "Show: Rendered Entity" doesn't work, because I need to add other things like edit links and custom text. So I set "Show: Fields" and used a "Rendered Node" field to output the node contents alongside everything else I needed.

The problem is that Views brilliantly wraps the entire node contents in  tags and links it to the node's page! This would be fine if I were just showing the titles, but I'm showing the node's entire rendered contents, with all sorts of
s and other links that need to work and other things.

Is there a way to make it not do that? There's no option for it in the field settings and I can't find where in the Views module this field is implemented.

Alternately, is there another way I can show a list of rendered nodes alongside other fields without them being stupidly linked in unconfigurable ways?

This happens because whenever Drupal renders a node someplace other than the node's page (for example, /node/12345) it will include the title as a link to the node itself. This is done in modules/node/node.tpl.php:

<?php if (!$page): ?>
  <h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>">
  <?php print $title; ?>

<?php endif; ?>

To stop this from happening in your view when using the rendered node as a field, you probably want to tweak the view field template. If you override node.tpl.php in your theme, other displays of nodes (for example, the default front page) will stop working as you expect.

I did this in views-view-field--test--rendered-entity.tpl.php using preg_replace:

$output = preg_replace('@(\s+
]*>\s+)]*>([^<>]*)(\s+
\s+)@', '$1$2$3', $output);
print $output;

Note that the exact regex will depend on the theme you're using. This is for an Omega subtheme.


drush cim creates and immediately deletes field Importing the following yml fails. With UUID it wants to be deleted. After removing the UUID it fails with field type doesn't exist. Any ideas? Is there some kind of order that might make the import fail.

uuid: null
langcode: de
status: true
dependencies:
  config:
    - field.storage.node.comment_forum
    - node.type.forum
  module:
    - comment
_core:
  default_config_hash: Tqw7kBEqm9_VZSK9bsNBAgJqAmJGP6cKEzXtf_KlqBo
id: node.forum.comment_forum
field_name: comment_forum
entity_type: node
bundle: forum
label: Comments
description: ''
required: true
translatable: true
default_value:
  -
    status: 2
    cid: 0
    last_comment_name: null
    last_comment_timestamp: 0
    last_comment_uid: 0
    comment_count: 0
default_value_callback: ''
settings:
  default_mode: 1
  per_page: 30
  form_location: true
  anonymous: 0
  preview: 1
field_type: comment

After doing a drush cex and reverting the affected file I now only have left those two lines when doing a drush cim. So the field seems to be created and deleted again. I can't find any config that is triggering that delete. Any clue?

Okay, there was a second field.field.node.forum.comment_forum.yml in the code of a custom module. It was just a simple setting which sould rewrite the code above but lead into a conflicting import. It looks like the second yml file gets imported first.
So far deleting the second yml file fixed the problem.

P.S. We will now try to find out why the rewrite doesn't work in the correct order.


"Accept answer" button for Advanced Forum comment I have a forum using the Advanced Forum module in which users ask questions. I want to add a button next to responses, so that the poster of the question can accept one of the answers (in fact, just like this forum works). I then want that post to appear highlighted as being the correct answer.

I realise that Flag is the module to use for this functionality, but I'm not sure how to make the "Accepted answer" appear to all users when the node owner flags the comment, when they are not owners of the original comment. Any ideas about how I can implement this functionality?

Answers module as a possible alternative

To implement something like "the poster of the question can accept one of the answers" (as in your question), you'll need something to allow one or more answers to be posted, and also have a way to create a (visual) relationship between the answer(s) and the question.

To do so, you might want to have a look at the Answers module (disclosure: I'm a (co-)maintainer of it). Either to actually use this module, or to get inspiration from it to see some of its features at work.

Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Since a picture is worth more then 1000 words, here is a sample screenprint of it (head over to its project page for more details):

About the Answers module

At its core, this module exists of 2 typical content types: Question and Answer (what other names would you expect ...).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module (and supports voting, which in this use case may not be needed, unless you want users that evaluate offers to use it).

To be complete:

You can use the "Best Answer" submodule for implementing something like "Node author can accept". And you could make the Rules module trigger all sorts of subsequent things to happen "when an answer gets marked as best answer".
It also comes with a "subscribe" feature (based on the "Message stack", with the amazing the Message module at its core).
Since the module is using (2) standard content types, all sorts of the typical standard Drupal facilities are also available, or can be enabled. E.g. if you want, you can also use a text format like "Markdown text", provided you first enable/configure the Markdown filter module.
... (there is really a lot, not just a bit, more).

Demo site

Have a look at the demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

These views also use the dataTables format, but you could easily replace that with any views display format you'd want. And because of the search box that comes with dataTables, there is no need for extra menu links to search within questions, answers or rankings.

These new/enhanced views were created starting from the 7.x-4.x-rc2 release of Answers, and will be included in the next release of it also (together with various other enhancements not yet visible in the demo site).

Try it out

To experience it yourself, try out a demo of it. Here are the steps to do so:

Head over to the demo site.
Just accept the defaults to create a sandbox demo site (make sure you're using the most recent 7.x-4.x version). Then hit the create sandbox button, and wait for the process to complete. Make sure you also enable the Answers Theme (sub-module of Answers, new as of 7.x-4.x).
Create at least 1 question using either the "Add content" menu link and then selecting "Question", or just enter relative path /node/add/question. And complete the title and body of the question.
After you save the question, you'll see the question that's created (in view mode). And below the question, you should see "No answers yet." (since you just completed posting the question). And then there is the "Your Answer" form right below that. That is the form you can use to post an answer to the question.
If you then use that (answer) form to post your answer, and also save that, the (first) answer is shown below the question, and below that answer there is now the "Your Answer" form again (to allow for posting an additional answer).
Use the Questions tab (or enter relative path /questions, to get a list (a tabular display) of all existing questions so far (there should be at least one if you completed the previous step).

Release recommendation

To decide between the 7.x-3.2 and the 7.x-4.0-rc2 release, I would recommend the 7.x-4.0-rc2 (which also has the shiny new theming stuff ...). Even though it is not yet an official release, it is fairly stable/functional, and only has a few more minor glitches to be resolved. Pretty soon an rc-3 (the last 'rc' release?) should become available also, which will include the newest features as you can see in the demo site already. More important: if you're just starting with the module, you won't have to "migrate" from 3.x in the future (some type of migration will be needed, which is still an open issue for now).


Why isn't  the node ID available as "replacement pattern" for the title link? I have a simple view for a node using an "unformatted list" and fields. I want to link the title to another URL and pass the NID. However, as "replacement pattern" I only have the "[title]" token.
When I add the NID field to the view I can link it just fine. What am I missing?

You've to add the nid field and exclude it from display, after your NID must be before your title and you'll have access to it.

Even, if is not right, normally you'll have it.


How to create an add content link with views I have a view of the Project node type (created by the pm module) that works well. For authorized users I would like to create a link button that will allow them to create a new project. I've spent the last several hours surfing the web trying to find out how to do this. I am new to Drupal so a solution that avoids using CSS & php would be most welcome.

You needn't use the PHP module, using PHP in the backend UI is usually a bad idea anyway.

First of all, the node creation link is simply a system link like /node/add/project which works only for users with the correct permissions.

There are ways to correctly route links through Drupal in Views (custom text—output as link), but as this is just for administrative reasons, you can probably simplay paste HTML like add Project in a custom text field / View header / View footer.
This displays the link for everyone with access to the View though.

If you want to display the link to specific users only, the easiest way is to simply create a block with the aforementioned link, display it on the same page as the View and show it only on specific user roles.

You could also set up a different view with different access privileges and attach it via an additional module, but I would deem this overkill.


Aggregated SUM from "Referencing entity" relationship, how to include nodes without relationship I have two content types - contact and payment. Payment have field_contact that is an reference to contact and also field_payment_amount which is decimal.

In views I'm showing list of contacts (with filter by type = contact) but also would like to show SUM of payments for given contact. I added relationship: Entity Reference: Referencing entity to entities that are referencing my contact by field field_contact, turned on aggregation, and added to view field_payment_amount aggregated as SUM, and using my relationship. In this configuration all contacts are shown but field that should show my sum is empty.

Next I added another filter (by type), now using my relationship and for this relationship filtering by type = payment. In this configuration I can see my sums - great! But! If contact have no payments - it is excluded from table completely.

How can I show contacts without payments with "0" as sum of payments and calculate proper sums for contacts with payments? I feel like I'm missing something simple, or maybe not?

Added:

Ok, I reduced problem to most simple case, and analyzed query. Now interesting thing is that looks like the same query executed manually by me, and by view - gives different results O_o .

Query:

SELECT node.nid AS nid, MIN(field_contact_node.nid) AS field_contact_node_nid, 'node' AS field_data_field_payment_amount_node_entity_type, SUM(field_contact_node__field_data_field_payment_amount.field_payment_amount_value) AS field_contact_node__field_data_field_payment_amount_field_pa
FROM
{node} node
LEFT JOIN {field_data_field_contact} field_data_field_contact ON node.nid = field_data_field_contact.field_contact_target_id AND (field_data_field_contact.entity_type = 'node' AND field_data_field_contact.deleted = '0')
LEFT JOIN {node} field_contact_node ON field_data_field_contact.entity_id = field_contact_node.nid
LEFT JOIN {field_data_field_payment_amount} field_contact_node__field_data_field_payment_amount ON field_contact_node.nid = field_contact_node__field_data_field_payment_amount.entity_id AND (field_contact_node__field_data_field_payment_amount.entity_type = 'node' AND field_contact_node__field_data_field_payment_amount.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('contact')) ))
GROUP BY nid, field_data_field_payment_amount_node_entity_type
LIMIT 12 OFFSET 0

Views output:

Query manual execution result:

Does anyone have possible explanation of this interesting behavior?

I was debugging like crazy to figure this out and then after checking some values in views_handler_field_field I realized what was wrong, and for sure it weren't Views! I forgot, or rather though of it as irrelevant, that there was third content type - a comment, that had a field "field_contact". The problem occurred because Views when summing up, was also using existing "comment" nodes, but because they didn't have "field_payment_amount" at all - Views got confused. So the real answer is that we need to filter out any additional types that are using "field_contact" field in our relationship.

I guess Views could act a bit better on this, and not get confused but use only available fields from proper nodes to create a sum, but it isn't much problem as long as we can filter out useless (for SUM) types that are using our reference field.

This explains why I got random/wrong results without type filtering on relationship, but when I added filter for "payment" - I didn't get "0" results, because then view assumed that relationship is required. The proper solution is then EXCLUDING wrong types that are in our relationship.


How do I enable modules in a Simpletest-Selenium test (Selenium module)? I am using the Selenium module for Drupal, which is integrated with SimpleTest.

One thing I have not been able to do is to enable modules for the test cases. I am able to enable them on SimpleTest tests (using setUp()).

How do I enable modules in the Selenium Tests?

It should work completely the same. You should be able to enable modules passing arguments to setUp().

Implementation of the setUp() method for DrupalSeleniumWebTestCase is

protected function setUp() {
  $modules = func_get_args();
  parent::setUp($modules);
  //...
}

So everything passed to it is passed to parent setUp method that should enable modules for you.