Display file size next to file link I'm trying to override the file-link.html.twig to display the size next to the file link (also the file MIME type, but I think I can figure that out once I figure out how to display the size) but so far I've been failing spectacularly. I assume this must be super simple and I'm missing something obvious.

Using kint($variables) in the function themename_preprocess_file_link(&$variables) I see the filesize:

$args array (1)
array (15
'file' => Drupal\file\Entity\File(27)
"contents" tab:
    protected values -> array(13)
    'filesize' => array(1)
    'x-default' => string(7) "2245389"

But I can't figure out how to turn this into a variable I can use in a template file.

I tried following How can I override template_preprocess_file_link function? but then I couldn't figure out what was suppose to be the variable to use in the template file. Also, his "code" just seems to be same as what is on https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/template_preprocess_file_link/8.6.x.

Using HOOK_preprocess_field(&$variables):

/**
 * Implements HOOK_preprocess_field().
 *
 * @inheritdoc
 */
function HOOK_preprocess_field(&$variables) {
  $element = $variables['element'];
  // Check that field_name is set.
  if (isset($element['#field_name'])) {
    // Checking for field_name, but could check for field_type.
    if ($element['#field_name'] == 'field_name') {
      // Set our file size to a variable.
      $fileSize = $element[0]['#file']->filesize->value;
      // Edit our title for the field display.
      $element[0]['#file']->filename->value = $element[0]['#file']->filename->value . ' ' . $fileSize;
    }
  }
}

Using HOOK_preprocess_file_link(&$variables):

/**
 * Add the "file-link.html.twig" template to your theme and adjust as needed.
 *
 * Twig variables:
 * - {{ fileLinkDisplay.fileBundle }}
 * - {{ fileLinkDisplay.fileCreatedTime }}
 * - {{ fileLinkDisplay.fileChangedTime }}
 * - {{ fileLinkDisplay.fileFid }}
 * - {{ fileLinkDisplay.fileLangcode }}
 * - {{ fileLinkDisplay.fileMime }}
 * - {{ fileLinkDisplay.fileName }}
 * - {{ fileLinkDisplay.fileOwnerId }}
 * - {{ fileLinkDisplay.fileOwnerName }}
 * - {{ fileLinkDisplay.fileOwnerUserPictureUrl }}
 * - {{ fileLinkDisplay.fileSize }}
 * - {{ fileLinkDisplay.fileSizeFormatted }}
 * - {{ fileLinkDisplay.fileStatus }}
 * - {{ fileLinkDisplay.fileUrl }}
 * - {{ fileLinkDisplay.fileUuid }}
 */

function HOOK_preprocess_file_link(&$variables) {
  if (isset($variables['file'])) {
    $variables['fileLinkDisplay'] = [
      'fileBundle' => $variables['file']
        ->bundle(),
      'fileCreatedTime' => $variables['file']
        ->getCreatedTime(),
      'fileChangedTime' => $variables['file']
        ->getChangedTime(),
      'fileFid' => $variables['file']
        ->fid->value,
      'fileLangcode' => $variables['file']
        ->langcode->value,
      'fileMime' => $variables['file']
        ->getMimeType(),
      'fileName' => $variables['file']
        ->getFilename(),
      'fileOwnerId' => $variables['file']
        ->getOwnerId(),
      'fileOwnerName' => $variables['file']
        ->getOwner()->name->value,
      'fileOwnerUserPictureUrl' => file_create_url($variables['file']
        ->getOwner()->user_picture->entity->uri->value),
      'fileSize' => $variables['file']
        ->getSize(),
      'fileSizeFormatted' => format_size($variables['file']
        ->getSize()),
      'fileStatus' => $variables['file']
        ->status->value,
      'fileUrl' => file_create_url($variables['file']
        ->getFileUri()),
      'fileUuid' => $variables['file']
        ->uuid->value,
    ];
  }
}

See https://gitlab.com/prestosaurus/file-link-display/blob/master/file_link_display.module

Then your file-link.html.twig might look like:

{#
/**
 * @file
 * Theme override for a link to a file.
 *
 * @see template_preprocess_file_link()
 */
#}
{{ attach_library('classy/file') }}
<span{{ attributes }}>{{ icon }} {{ link }} {{ fileLinkDisplay.fileSize }} {{ fileLinkDisplay.fileMime }}</span>


Add an attribute to a specific tag in text body of page I would like to add an attribute to a specific tag in the text body of a page.

I was thinking in this direction:

add MYTHEME_preprocess_field(&$variables) to template.php
apply regular expression to the right field (but which one? $variables['items'][0]['safe_value']?)

Can anyone give me a specific working example of applying a regular expression to the body field of a page?

Thanks!

Since you are just looking to add an attribute to a tag, you could do your changes to the field #markup instead. A simple example:

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
    $markup = preg_replace('/href=/', 'title="foo" href=', $variables['items']['0']['#markup']);
    $variables['items']['0']['#markup'] = $markup;
  }
}


Is there a way to provide the login provision for anonymous user when anonymous commenting is enabled? I have enabled provision for Anonymous commenting. But it provides the only option of

Your Name
Email Address
Homepage

What I would like is, above this, there should be a provision of Login. Hence this way user can see that, So he/she will have two options, either he/she can login OR he/she can comment anonymously.

What happen with current system is, Anonymous user keep on commenting as anonymous only, If there is a option of Login, then he may think about that.

So, I would like to make the system in commenting like,

  Add Comment

**Login/create account**

OR

**Comment Anonymously**

Your-name*  |  Email*  |  Homepage

Comment field

Update:

I just need a Link, like what appears above the comments title on every drupal site, as shown in following image, Log in or register to post comment

Image

Since you want to edit something in the contact form, you can use the same  hook_form_FORM_ID_alter of my previous answer to alter the comment_form.

As you can see in the comment form all author details are in an array $form['author']. So you need to add an item to this array and move it to the top.

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  // Any code you already have here

  // Check if the user was not yet logged in. (It would be useless to show this otherwise.)
  if (!user_is_logged_in()) {

    $form['author']['login_url'] = array(
      '#type' => 'markup',
      '#markup' => t('Login or create account', array('@login' => url('user/login'), '@create' => url('user/register'))),
      '#weight' => -10, // Play with this value to control the height.
    );
  }
}


How to pass rendered form results to page Drupal 8.7.x

I have a custom form that currently replaces the form with the output of the form like so:

CalculationForm.php

  public function submitForm(array &$form, FormStateInterface $form_state) {

    ...

    // Result overview.
    $result = [
      '#theme' => 'THEME_calculation_overview',
      '#name' => !empty($values['company_name']) ? $values['company_name'] : $form_state->getValue('firstname') . ' ' . $form_state->getValue('surname'),
      '#product' => $product,
      '#address' => $address,
      '#results' => $result_clean,
      '#urls' => $product_urls,
    ];

    // Bundle (rendered) results.
    $results_overview .= render($result);

    // Show rendered results.
    $this->response->addCommand(new ReplaceCommand('#form-calculation-container', $results_overview));
}

Currently the form submission makes an ajaxcall that replaces the container which holds the form with the rendered output (Replacecommand). Because we can't track the form submission with GTM I'm switching over to a normal form submission which redirects to a page.

My question is, how can I pass $results_overview to the redirect page and make it render as part of the content variable.

Thanks in advance

in your submitForm function you need to set rebuilt to true (the default is false) on the FormStateInterface then add the result as a value to the form_state. And in the buildForm function you need to check for the presence of the results variable and accordingly you can add it to the form. Something like this:

  public function buildForm(array $form, FormStateInterface $form_state) {

    ...

    $result = $form_state->getValue('result');
    if($result){
      $form['calculation'] = $result;
    }

    ...

    return $form;
  }

and

public function submitForm(array &$form, FormStateInterface $form_state) {

  ...

  // Result overview.
  $result = [
    '#theme' => 'THEME_calculation_overview',
    '#name' => !empty($values['company_name']) ? $values['company_name'] : $form_state->getValue('firstname') . ' ' . $form_state->getValue('surname'),
    '#product' => $product,
    '#address' => $address,
    '#results' => $result_clean,
    '#urls' => $product_urls,
  ];

  $form_state->setRebuild();
  $form_state->setValue('result', $result);

}


Way to integrate a latex-based wiki into a drupal 6 site I have a website with users already designed in Drupal 6. We would like to add an area/module that would allow registered users of a certain type/category to be able to collectively edit/contribute to a set of wiki-based statistical documents, ideally written in LaTeX, but that other users (registered and anonymous) could download in the original LaTeX or exported to .pdf. (Imagine a wiki-based, open-source statistics textbook.) There are wiki modules and LaTeX modules for Drupal, but no LaTeX-wiki modules.

Is there some stand-alone wiki software that could be hosted on a sub-domain of our site but uses the Drupal user permissions to manage access? Is there a Drupal module or option I haven't found?

What we have:
Drupal 6 site that anyone can visit/see, but that requires registered user status to contribute/participate on site. We can add subdomains/create any databases, etc. needed on the servers to do what we need to do.

What we envision:
A wiki that allows a subset of registered users to collaboratively edit/write statistical texts easily (many of these users are already familiar with LaTeX) that will preserve mathematical equations and render them onscreen (.html) and as .pdf output.

Version tracking and attribution to particular users is necessary.

Any user can view .html of current wiki, or download the raw LaTeX file (for their own use), or choose certain wiki pages to be exported as .pdf.

Is there some stand-alone wiki software that would meet these criteria? And, if so, could we somehow use the same user database as our drupal install to set permissions? We anticipate hiring someone to do the programming necessary (our current Drupal developers do not do this level of development), but it would be helpful to know whether we're looking for someone to modify two existing tools to work together or to write a new drupal module that suits our needs.

A solution would be to have a Drupal based wiki on your website and then to allow the usage of LaTeX markup for the wiki content. DruTeX]1 may allow the later, while Wikitools should provide the former. They will both need to be properly configured.


Form alter in a custom module I am trying to modify a form with a hook_form_FORM_ID_alter within a module though it doesn t seem to have any effect at all when called from within my module.

My code looks like something like this:

function fb_reg_form_user_register_form_alter(&$form, &$form_state, $form_id ){
    $form['field_lang_list']['#prefix'] = '
';
    $form['field_lang_list']['#suffix'] = '
';

   $fbu = fb_facebook_user();
   if ($fbu || is_numeric($fbu)){
   $fb_account = fb_api($fbu);

   krumo($fb_account);
   $form['account']['mail']['#prefix']= '<fb:profile-pic uid="'.$fbu.'" linked="false"></fb:profile-pic>';
    $form['account']['mail']['#default_value'] = $fb_account['email'];
    $form['account']['name']['#default_value'] = $fb_account['name'];
    //$form['account']['name']['#default_value'] = $fb_account['name'];
   }
}

The thing i don't understand is that this works as expected when the hook is called from within the template.php but when in the module it self i can't seem to get it work.

Would anyone have any idea on what s going on?

EDIT: Could this have something to do module weight ?

Many thanks,

If the part of the form you're altering doesn't exist when you're altering it (if it's put there by some other form-altering module) OR if some other module is altering the form after you and wiping out what you're doing then you can indeed have a module weight problem. The way to find out is to put a dsm() (see devel module) in your code and see what the form looks like before your alter. Or use a debugger of course (recommended!)


How to suppress output of  tags in a views2 field output? I've determined that I have an extra blank line above/below a field as output by views2.  The generated html code examination shows a set of paragraph tags enclosing the field.  I can find nowhere within this view to suppress that output.  Is there a way either within views2 or via some css attribute?

You could go through the effort of overriding the template for that field, or you could just target the p tag with css and set the margins to 0px.

Views adds pretty granular classes to every field and row to make it easy to target.


Related Terms Block Based on Terms Fields I am not sure where to begin except experimenting with contextual filters which is not getting me very far. I am trying to display taxonomy terms in a block based on if a certain field has the same info that is on the same taxonomy page.

For example

Current term page = Radioshack
Radioshack has the fields:
Term Field City: San diego
Term Field Type: Electronic

And the terms I want to list would be
Term: Frys Electronics
Term Field City: San Diego
Term Field Type: Electronics Store

Term: Best Buy
Term Field City: La Jolla
Term Field Type: Electronics Store

So if you notice they all have the same type which is electronic store so it would display those 2 terms on the current page which is radioshack and any other terms with the same type electronics

I was able to get this done by adding my code in into my contextual filter which would be Taxonomy Term:[You term field name].

This is the code I used.

$path = drupal_get_path_alias($_GET['q']);
$path = explode('/', $path);
$termname = array_pop($path);
$termname = str_replace("-", " ", $termname);
$terms = taxonomy_get_term_by_name($termname );
$term = reset($terms);
$term->tid;
$term_list = taxonomy_term_load($term->tid);
return $term_list->field_companies_industry['und']['0']['value'];


Alternative to "Vote Up Down" module for? Is there any other module like vote_up_down, but for Drupal 7? This one has a development version but as the author says it is unstable.

  7.x (unstable, on development, do not use this version for production)

Use the Fivestar module for rating. Or the Rate module. Some more details about these modules (quotes included are from their project pages):

Fivestar:

  ... adds a clean, attractive voting widget to nodes and comments and any entity. It features:

  jQuery rollover effects and AJAX no-reload voting
  Configurable star sets
  Graceful degradation to an HTML rating form when JavaScript is turned off
  Support for anonymous voters
  Spam protection to keep users from filling your DB with bogus votes
  Easy-to-use integration with Views module for lists sorted by rating, or filtered by min/max ratings
  A Fivestar CCK field for use in custom node types
  An easy-to-use Form API element type for use in other modules
  Compatible with all versions of jQuery (1.0 - 1.8)

Rate:

  ... provides flexible voting widgets for nodes and comments. "The cck model for voting with Drupal".


Is there a special way to list Commerce Products? Drupal core 8.2.6
Drupal Commerce 8.x-2.0-beta5
Bootstrap 8.x-3.2

I tried making a View that renders Products in view mode (Grid of Products in Default view), but when I try to add a product to cart - if the product has no variations - often times a wrong product that has no variations gets added. If the product that I try to add has variations I get a php error: InvalidArgumentException: Unknown attribute field name "attribute_period". in Drupal\commerce_product\Entity\ProductVariation->getAttributeValueId() (line 260 of drupal/modules/commerce/modules/product/src/Entity/ProductVariation.php).

Other attributes pop up there as well if I add a different product to cart.

It seems like it still tries to add a different product but provides the right variation name, which the different product does not have, so it errors.

If I view just the product on its own - works just fine. So for now I have the view show a table of products with "View" link, but I'd really like to be able to add products to cart right from the view. Any ideas for how to make that happen? I can't seem to find any tickets about this issue.

I believe we have this captured in an issue. The main issue was https://www.drupal.org/node/2831895 and is now in https://www.drupal.org/node/2827721.

Part of our blocker has been getting tests for this. We need to build a test for the use case then work towards a resolution.

There is a pull request in progress at https://github.com/drupalcommerce/commerce/pull/582. I have not reviewed this and not sure how close it is to a final solution.

The issue is unique form IDs.


Giving a default value to a password element in D7 form API? I wrote a custom feeds fetcher class that does an authentication call before it gets the feed. In its settings, I have username and password fields in the form. I tried to set the field #type to password, but it seemed not to use the #default_value element, thus obliterating the saved password when you hit the 'save' button.

This maintains the password, but shows it in plaintext:

$form['password'] = array(
  '#type' => 'textfield',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

This shows dots for the password, but does not populate the field using the #default_value, causing you to have to enter the password any time you want to change and save any value on the form:

$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#default_value' => $this->config['password'],
);

I need to be able to have the user enter a password and have it stay no matter what other values they change on the form and save. Does this preclude me from using the password field type, since it appears not to use the #default_value element?

You can try to add your default value directly with #attributes option just like that :

$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#attributes' => array('value' => $this->config['password']),
);

After I'm not sure if you will be able to get that value on validate and submitcallback, you should check.


Exposed filter with Load more I have 2 problems with drupal.org/project/views_load_more & exposed filter:

When I change the exposed filter selection, it only filters the result which is in first lot (e.g if I have given a limit of 8 and then change exposed filter selection it filters among those 8 results only).
I get duplicate records; if I remove the load more limit I get distinct records

Please help.

To address the 2nd bullet of your question, consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


How would I be able to get the full URL from an image field? In a node template, how would I be able to get the URL from an image field?
Like if it were something like this:

  {{ content.field_image.URL }}

Or if there is a similar alternative perhaps?

Have you seen the answer of this question?


Is it possible to migrate taxonomy terms when having only the term name? I'm starting to learn the migration module because i have to do quite a complicate migration from a Drupal 6 site to a Drupal 7 Importing nodes with different field names from Drupal 6 to 7

And i'm wondering if it's possible to migrate taxonomy terms if you have only their name but not the tid (or better, the tid is different between the sites), and if it's possible how? (that is, other than making a query to load the tid from the db, i'd like to know if there's a more "automated" way)

I probably will use feeds module and hook_feeds_presave to manually re-import taxonomy name and reset the node associate your that taxonomy.


Drush not connecting: bootstrap error? I've installed Drupal 7, Drush 7.0 and the Omega 4 theme. I'm using MAMP. I'm attempting to create an Omega subtheme with the command line:

drush omega-wizard

I then receive the following error.

When I run drush --debug, this is the result. Can anyone decipher this?

Is your settings.php file in a folder called 'default'?  If not, you might need to tell Drush where to find it by using --uri=mysite.com or -l mysite.com.

See: Drush Bootstrap Error on Multi-Site Install


Trying to find variable names from $user array I need to manually pull through user images and and users first name for a comment section, but i cant find what these array items are named, if anybody knows please tell me and or tell me how to find similar information in the future.

The best way to do this is use the devel module.

Once enabled you can use the dpm($variable) function to have it printed out on the screen.

Another (more complex to set up) solution would be to use xdebug and a debugger.


Panel Page with Node Views, Flags and Rules Integration I created a page where users can submit friendly games. Other users can show their interest by flagging (Flag A) these games.

The author of the game can see all prospects in another view (View 3 integrated in View 2 with Views field).

The author than can choose which prospect for a friendly game he accepts. He does this by flagging the prospects flag with an accept flag (flag B).

The accepted prospect than gets an email confirming the friendly game.

How is it possible for me to send emails to all prospects who did not get accepted?

I tried Rules (on flagging event) and Rules Link.

How do I tell Rules what friendly game node this is all about?

Hello, thank you for your ongoing help! I created a list of friendly games with relationships and contextual filters that display these users.

When I use "Load a list of entity objects from a VBO View." or "entity ids" drupal throws error messages at me.

Warning: Invalid argument supplied for foreach() in _views_bulk_operations_get_field()

Another really strange error for this rule is "Illegal choice blog in type element." The view does not display blog types... I'll try to figure this whole mess out.

Another problem in my opinion would be that in my view is a contextual filter that gets the NID of the friendly game by the view it is integrated in by "views field module". So how does the view know what users it should display if I loop it with a rule? Wouldn't it just loop through all users that flagged any friendly game who are not flagged?

If you can create a view (using the Views module) of those users that correspond to all those "prospects who did not get accepted" for a given game node, then you can process the results of a VBO enabled view via Rules, using a rule that looks like so:

Rules Event: After flagging the prospects flag with an accept flag (flag B).
Rules Actions:

Load the VBO list of the users in your View.
Add a loop to perform a Rules Action "Send an eMail", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Is there a way to remove a menu item from the active trail without removing it from the menu parent? I'm a relative newcomer to Drupal and I'm not sure how to handle this. On this page:

http://staging.stvincentdepaul.net/volunteer

You can see that Volunteer is highlighted in the main nav but so is Today. If you hover over those L1 links, you'll see that each one has a Donate and Volunteer button. These are all part of the main navigation menu in the admin section so each Donate and Volunteer button falls under each L1 link. The Today section was the last to have Donate/Volunteer added so it is attaching the active-trail class to that link since it can only have one.

Is there a way to keep those Donate/Volunteer links in the menu but not part of the active trail?

This is a common headache. I keep meaning to write a contrib module to address this by letting users define a "canonical" menu item in the event there are several menu items that point to the same page in the same menu.

That said, there are some workarounds you can use.

The best option is to use the Redirect module. You create a redirect to your Donate and Volunteer pages then put the redirects in the menus.

So if your volunteer page is at /volunteer and donate is at /donate, then you can create two redirects. One called /go-volunteer and another called /go-donate which redirect to their respective pages. Then you'd put /go-volunteer and /go-donate in the menu which, when clicked, will take the user to the appropriate page.

Since they're redirects, they won't trigger the active trail.


Why does js click function run multiple times? I'm creating some accordion functionality for fields and paragraphs using a combination of twig templates and a custom JavaScript file.

Everything prints as expected and the basic accordion functionality works; however, the click function script is running multiple times, causing an "expand-collapse-expand-collapse..." behavior. See image:

Here is the script file:

(function($, Drupal) {

/* Add span to wysiwyg button classes for alignment
------------------------------------ */
Drupal.behaviors.accordionFaqFunction = {
  attach: function (context, settings) {
        $('.toggle').click(function(e) {

                e.preventDefault();
                var $this = $(this);

                if ($this.next().hasClass('show')) {
                        $this.next().removeClass('show');
                        $this.next().slideUp(350);
                        console.log("hiding");
                } else {
                        $this.parent().parent().find('li .inner').removeClass('show');
                        $this.parent().parent().find('li .inner').slideUp(350);
                        console.log("showing");
                        $this.next().toggleClass('show');
                        $this.next().slideToggle(350);
                }
        });

  }
};

})(jQuery, Drupal);

Why is the script running multiple times?

Most importantly you have to use the JQuery selector context. Otherwise you run the entire DOM through your js code anytime when Drupal behaviors passes you only context to process.

If your function still runs multiple times, add once() with a unique identifier:

$('input.myCustom', context).once('mySecondBehavior').each(function () {

Don't forget to add the library core/jquery.once to mytheme.libraries.yml, see https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


How do I override views-view-summary-unformatted.tpl.php inside my own theme? I cannot override views-view-summary-unformatted.tpl.php inside my own theme. I copy the tpl from the views module directory, paste into my theme directory and modify the code. My website will not recognize the new tpl. If I make the changes directly inside the views module, then I can see my changes on my website. However, I know it is not best practice to hack a contributed module. I've tried adding "--myViewName" to the tpl file, but this doesn't help. When I look at the Theme Information in my view, I don't see views-view-summary-unformatted.tpl.php listed there. (The reason I am trying to override this tpl is that I want my alpha bar to include all letters of the alphabet even if there are no entries for a particular letter.) Can someone please help me figure out what I am doing wrong? Thanks!

I know this is old but today I struggled with this and thought I should provide a solution.

First, you have to rename your copy of 'views-view-summary-unformatted.tpl.php' so views can discover it. It should be named 'views-view-summary-unformatted--my-view.tpl.php'.

You then need to click the 'rescan template files' button under the theme information in the view.


Add rule for a webform checkbox to autosend email after specified time Im running D7 with webform.  I have a multstep form, on the last step the user is asked to participate in a future survey.  If they enter their email and check the box to agree, they should receive an email reminder with a  link to a new survey I have created in two weeks from when they agreed.

Im planning to use webform rules, rules, and token modules to create this feature.

Am I going to be able to verify the condition and generate a scheduled email using these modules?  Or do you think I should focus my efforts on a custom module?

You will also need Webform Rules, but once you can react to the submission, you should have no problem getting this going. You'll need to schedule the rule to run in the future and will probably need to add a Rules Component containing the actions to run at that time.

In your triggered rule that reacts to the Webform submission, you need a condition checking if that checkbox was checked and an action that runs the Rule Component you defined earlier. You will want to pass the user object to it (or uid, or email address, or Webform submission - whatever you need) to make sure it works correctly.

I am using Drupal 7 terminology here, but this is achievable in Drupal 6 as well. Just replace "Rule Components" with "rule sets."


How do I use the mail manager without the $to value? I want to send an email for multiple users without a to address. Setting $to NULL, and empty string 'undisclosed-recipients:;' doesn't work.
How can I send an email with just BCC recipients?

I would suggest that you avoid this approach as messages with lots of recipients in the bcc field are more likely to trigger spam filters on the receiving mail server.
I would loop through each email address and send them a separate email instead, if there are a lot of emails to send then consider moving them into a batch operation.


How to list articles by an author in a views? In Drupal 7, I have defined a node type 'article' which has an 'author' field (The author is not a user, but just a 3rd party contributor). Now I want to list articles by the each author in a view. How can I do that?

I know that it can be done somehow using contextual filters but got quite perplexed so  appreciate your help.

In your case, i would create a Vocabulary "authors" and add them with a Auto Tag Widget to the Content Type. And add the Authors as a Taxonomy Tag. There are much more Handly then Text Fields.
Then you can easily Create a View with the author Tag. And much more, you can also add more fields to the Taxonomy such as author Picture and Author Description.


Add elements to webform dynamically via hook_form_alter I'm trying to dynamically add multiple toggle fields to a form (in my case webform) via a form-alter-hook.

function module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
....
  foreach ($roles as $role) {
    $form['elements'][$role->id()] = array(
      '#type' => 'webform_toggle',
      '#title' => t($role->label()),
      '#default_value' => 0,
      // More webform specific arguments follow here.
      '#webform_id' => "edit_membership_roles--" . $role->id(),
      '#webform_key' => $role->id(),
      '#webform_parent_key' => "",
      '#webform_parent_flexbox' => FALSE,
      '#webform_depth' => 0,
      '#webform_children' => [],
      '#webform_parents' => [$role->id()],
      '#webform_multiple' => FALSE,
      '#webform_composite' => FALSE,
      '#admin_title' => $role->id(),
      '#webform' => "edit_membership_roles",
      '#webform_submission' => NULL,
      '#access' => TRUE,
      '#webform_element' => TRUE,
      '#element_validate' => [],
    );
  }
}

This works in a way that the form is displayed correctly, with all dynamically added toggle elements. However, when trying to load the WebformSubmissionInterface $webform_submission via $webform_submission->getData(); in my custom class FormHandler extends WebformHandlerBase {...}, the array only contains the elements that I manually added to the webform via the GUI.

I checked the first answer of this question, but my $form does not have a $form['submitted']

Am I just missing something or does this approach not work at all?

Update

I did the same approach with a custom form built with Drupal FormApi and it works. So I must be missing something specific to webforms.

Adding elements dynamically via hook form alter does not work because the Webform module can't recognize the new elements.  Your best bet is to create a custom webform element.


Why do many Drupal themes markup images with typeof="foaf:Image" attribute? Does this attribute simply enhance semantics?

Yes, it’s about semantics of your content. That way, your page/content is part of the Semantic Web.

Background

The typeof attribute is defined by RDFa.
RDFa is a syntax to embed RDF in markup languages like HTML.

The value foaf:Image (most likely) refers to the Friend of a Friend vocabulary/ontology. The namespace foaf: typically stands for the URI of that vocabulary (http://xmlns.com/foaf/0.1/), so the value is actually the URI http://xmlns.com/foaf/0.1/Image.

http://xmlns.com/foaf/0.1/Image is a class. It’s (= what it means) documented here: http://xmlns.com/foaf/spec/#term_Image.


Drupal 7 - dynamic, collapsible, navigation bar/block/thing in the sidebar first Because a picture tells more than 1000 words.
Click here to see the image --> OPEN IMAGE
On the left side, you will see what I need.
On the right side, you see what I already have.

The question:

Is there a possibility for showing all the chapters in a navigation block (or something simular) like a navigationtree ? with collapsible nodes and meanwhile if you click on some of those chapters, the main page changes?

perhaps with jquery?
But I can't find any good documentation whereby I can say, That's what I need.

I hope that someone can help

Kind regards.

Dieter

You can use DHTML Menu or Accordion Menu to get the desired effect.

IMO, DHTML Menu is simpler to use.


Send email to different email depending on taxonomy term This was fairly simple to do in D7 and is a common request. How would I send an email to a different email address depending on a taxonomy term chosen from a dropdown box on the contact form?

I don't know how you did it in D7, but hook_mail_alter is my preferred solution. And in hook_form_contact_site_form_alter i would add taxonomy term reference field to the contact form.

  This still works in D8

Code would look like this in your custom module:

/**
 * Implements hook_mail_alter().
 */
function YOUR_MODULE_mail_alter(&$message) {

  if ($message['id'] == 'contact_page_mail') {

    $tid = $message['params']['your_form_field'];
    if (!empty($tid) && $tid > 0) {
      // $tid to determine the address ?!
      $message['to'] = 'your@emai.l';
    }
  }

}


Watchdog "404 page not found" entries from spambot guessing urls Browsing through the watchdog list I found a lot of page not found entries with urls like:

http://example.com/wp/wp-trackback.php
http://example.com/phpMyAdmin-2.5.5-pl1/index.php
http://example.com/flpurrbiao.html
http://example.com/gxksjgjrwk.html

What's best practice to stop these hits?

Block them using these modules, study these and related modules for perfect working solution to your need :

http://drupal.org/project/httpbl

http://drupal.org/project/badbehavior

http://drupal.org/project/antispam (Apart from blocking comment spam, disables bot showing 403 error)

http://drupal.org/project/botcha

Install http://configserver.com/cp/csf.html and use Real Time Block Lists (RBLs)

And finally a free-service like http://www.cloudflare.com/features-security will get things working.


PHP switch and translations Given a PHP switch statement, would it be a good (or bad) idea to use t() in case statements?

switch ($button_value) {
  case t('Clear'):
    // …
    break;
  case t('Search'):
    // …
    break;
}

In general, it would be a bad development practice. The whole purpose of t() is to provide human-readable translated text. As such, it can't be guaranteed as consistent switch logic because the translation context might differ.

In practice (e.g. a input button submit value on a basic form with little-to-no translation contexts), you might get away with it, but you're adding technical debt; if your application grows and other features start to rely on the switch logic, it's only a matter of time before the inconsistent logic will bite you.


Get User's other field instead of Username,in the View? I have one content type called "Test".In that content type i have Entity Reference field Referencing to Users called "field_authors"[can have more than one user] . I have created a view of this type.Here while showing 'field_authors' , it is showing User username, but Instead of username ,i want to show other field value of the User.
How can i achieve this? Can anybody please help me?
Drupal version:8.2.0
Details:
Currently View table column Output is: CC111,CC112,CC113 [which are the usernames of different users in the site]
I need user's other fields like "First name" instead of username in above Case.
I tried adding Relationship '(author) field_authors' and Added field in view Table 'field_authors'[selected use relationship] , But still output is CC111,CC112,CC113 etc instead of comma separated names.
I Got partial output after adding Relationship to that field,but since it is a multi field,output is coming in 3 different rows.Instead of it I need output in one row comma separated values.[Ex:Name1,Name2,Name3]

In order to use fields of user, you have to add a relationship  (panel to the right, under contextual filter). Create a relation to the user entity.


WYSIWYG Editor for node titles? Is it possible to use a WYSIWYG Editor such as a CKEditor for node titles in the node creation form?

Update: Okay, so let's suppouse that I am developing a newspaper, and I want the journalists to be able to set the size of the title (i.e. if it is a very important news, they will select big font size for the title, otherwise, if it's a regular news, the title size will be medium).

Is the correct way to achieve this through Display Suite Extras, and some CSS classes?

I think there is a module for that --> https://www.drupal.org/project/html_title

An other way is probably to use the Body field (or any other) instead of the title and leave the title field as is. You could for example use the Display Suite module for this or alter your content type displays where you need it.


How to display all users except current user? How to display all users in a view except the current login user?

I try to write some php code in contextual filter, but that not work. I think there is an easy way but I don't know it.

I was able to make a view that displayed all the users while excluding the current user.  Here is a screenshot of the settings I used:

Note that the important filter here is the "User: Current (No)".  That is the one you'll need to have.


Drupal 7 Ajax GET - Error 400 (Hook_menu) I am trying to send an array back to Drupal to save in a database table. I'm getting an error 400 though when inspecting in the console and the url seems correct:

  GET http://localhost/audiophreak/callback/%?[1,2,3,4,5,6,45,46,47] 400
  (Bad Request)

Here is my hook_menu:

/**
* Implementation of hook_menu().
*/
function my_db_module_menu() {
  $items['callback/%?'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
    'page arguments' => array(1),
  );
  return $items;
}

Here is my callback:

/**
 * My callback
 */
function mymodule_getinfo($data) {

echo drupal_json_decode($data);

  // //Parse the data and input it into the database
  // $result = db_insert('my_db')
  // ->fields(array(
    // 'nid' => $data->node,
    // 'uid' => $data->user,
    // 'progress' => $data->progress,
  // ))
  // ->execute();
}

And here is my AJAX

//Data
    var post = plnzVideoTracker.progress

    //Begin Ajax
    $.ajax({
          url: '/audiophreak/callback/%',
          contentType: "application/json; charset=utf-8",
          type: 'GET',
          dataType: 'json',
          data: JSON.stringify(post),
          success: function(data) {
            if(data == "success")
            {
            $('.status').attr("innerHTML","Name submitted successfully!");
            }
            else
            {
              $('.status').attr("innerHTML","Name submit failed!");
            }
            },
            beforeSend: function() {
              $(document).ready(function () {
              $('.status').attr("innerHTML","Loading....");
            });
            },
            'error': function(data) {
              $(document).ready(function () {
              $('.status').attr("innerHTML","ERROR OCCURRED!");
            });
          }
     });

plnzVideoTracker.progress is an array inside of an object literal if that has anything to do with it?

The % symbol is type of placeholder in hook_menu item. You can read more about it here: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7#sec_path_wildcards.

For you example I suggest to use the following:

function my_db_module_menu() {
  $items['callback'] = array(
    'title' => 'My callback',
    'description' => 'Desc',
    'page callback' => 'mymodule_getinfo',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

  return $items;
}

Simple path  - callback.

And use the following AJAX:

$.ajax({
  url: '/callback',
  type: 'POST',
  dataType: 'json',
  data: {data: post},
  ...

By this way, you can access the data in your webhook more simply:

/**
 * My callback
 */
function mymodule_getinfo() {
  $data = !empty($_POST['data']) ? $_POST['data'] : array();

  // do what you want...
}


Edit message when new user created In configuration>Account settings page, at the bottom of page under E-mails first option Welcome(new user created by administrator), here I want to edit the body section and need to include link for my custom page /unsubscribe. I have gone through the available tokens but I did not fine any clue

You might be looking for [site:url]. Alternatively, there is also [site:url-brief]


Can't locate where Commerce Authnet stores the API and Key I am using Drupal Commerce and the Commerce_authnet module to connected to Authorize.net. I have custom functionality which requires me to make a separate call to the Authorize.net CIM API. I have done so sucessfully by adding a submit handler to the Checkout button, catching the API Login and Key, and used those in my API calls.

$login = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['login'];
$key = $form_state['values']['commerce_payment']['payment_methods']['authnet_aim|rules_authorize_net_aim_credit_card_test_association']['settings']['tran_key'];
define("AUTHORIZENET_API_LOGIN_ID", $login);
define("AUTHORIZENET_TRANSACTION_KEY", $key);

However, I need to create a separate way of users updating their Authorize.net account settings from their user profile form. I have looked in the commerce database tables and in the drupal variable editor to see if I could pull it from the database, but I have not found where its stored.
How can I access this data?

I'm assuming you're using the latest version of Commerce authnet.

Drupal Commerce payment system (as well as discounts, taxes..) is based in rules, you can see here how the settings form are included: http://cgit.drupalcode.org/commerce/tree/modules/payment/commerce_payment.rules.inc#n250 in the rules UI, so it is basically stored by rules in a rules_config object, specifically in the unserialized data column.

So if you want to see the settings in the database, you can go to rules_config table and check the data db field.

Modifying this from outside rules is another story, I've never done this, but I'm quite sure that rules doesn't provide an API to alter this data field, you'll probably need to use the Database API to access rules_config table and unserialize/serialize the data information to alter it.

It is probably advisable to find an alternative way to do this, i.e providing a new module that runs a slightly modified version of the charge callback of authnet (http://cgit.drupalcode.org/commerce_authnet/tree/commerce_authnet.module#n750)


Showing shipping costs in the cart page Hi i'm using the Commerce Shipping Postal Code Weight module. It works fine but I just want to get shipping costs in the cart page.

You are probably wanting something like Commerce Cart Estimate.


Is it okay to edit the webform content type? I want all the static pages on my website to have an image at the top of them. So instead of using Drupal's Basic Page type, I created my own type (Simple Page) that has:

Title
Body
Image

I have enabled Webform module on my site and created a simple Contact Us form.

The problem I have is that the Contact Us page (a Webform) does not have an image at the top, like all my other pages. To fix this, I edited the webform content type and added an Image field, and now my Contact Us page follows the styling of the other pages.

But it feels wrong, editing the Webform type directly. (Its as if I have hacked core!) And now I am worried that I'll have problems when I upgrade the Webform module.

Is there a better way that I could have done this?

I don't think you've necessarily done anything wrong by adding fields to the Webform content type, but if you're interested in strictly keeping your code separate from core code, you can create a new content type,  and enable Webforms to be used on this content type under "Webform-enabled content types" on /admin/config/content/webform.

Then you'll be able to add your own image field to your own content type without problems.  This will then leave you free to export the content type configuration to code with the features module, without really interfering with the Webform content type provided by the Webform module.


date ranges in view filter criteria Drupal 7, Views node to be selected on date range.

I would like to have my view only return nodes that were created last month, no matter when I run the view this month.  So as it's the middle of January, I want all nodes created in December last year, and next month I want all of January's

So the dates would be between first day of last month and the last day of last month.

In php I can use:

echo date('Y m d', strtotime('first day of last month'))

and

echo date('Y m d', strtotime('last day of last month'))

to get the correct date range.

However, in Drupal, the SQL does not create the correct ranges.

Viewing the view and sql logs at 11:55 on Jan 16th 2013 I see :

(node.created >= 1358337264-2678400

which works out as 2012-12-16 11:54:24, so it is a month ago, but not the first day of that month.

Any thoughts.

If possible, it might be beneficial to create a separate Date field for your content type. I often find that if I need to do custom filtering in a view, filtering by the date field instead of node post date is much easier. Being able to collect different granularity such as day and month can be helpful also.


Auto-collapsing fieldsets on user_profile_form I am following these guides:
Customize the User Edit page in Drupal 7: https://www.drupal.org/node/2279959
Collapsing default fieldsets (Drupal 6): https://www.drupal.org/node/733198

Basically, I just want to make all of the fieldsets on the user_profile_form (e.g. /user/1/edit) collapsed by default.

Here is what I've got so far, but it doesn't work - page never finishes loading (I have changed THEMENAME to the name of my theme).  This still doesn't work however...

function THEMENAME_theme() {
  return array(
    // The form ID.
    'user_profile_form' => array(
      // Forms always take the form argument.
      'arguments' => array('form' => NULL),
      'render element' => 'form',
    ),
  );
}

function THEMENAME_user_profile_form($form) {
  //Create array to return
  $form_elements = element_children($form);
  foreach ($form_elements as $element) {
    //Identify fieldsets and collapse them
    if ($form[$element]['#type'] == 'fieldset') {
      $form[$element]['#collapsible'] = TRUE;
      $form[$element]['#collapsed']   = TRUE;
    }
  }
  return drupal_render($form);
}

I have a feeling that there is something that I am missing regarding converting this Drupal 6 code to work with Drupal 7 but I am lost.  I have about 30 tabs open and have searched extensively on stackexchange, drupal.org, etc. to no avail.  Please help!

EDIT: here is the code for a small custom module I wrote to easily test this (no need to clear the cache every time like with template.php)

function collapse_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form['edit-picture']['#collapsible'] = true;
        $form['edit-picture']['#collapsed'] = true;
       $form['edit-timezone']['#collapsible'] = true;
        $form['edit-timezone']['#collapsed'] = true;
        // test to make sure module and hook_form_alter is working
        $form['#attributes']['class'][] = 'foo7';
    }
}

I should add that I've tried dashes and underscores, e.g. edit_picture and edit-picture.

You want to use hook_form_alter here.

THEME_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_profile_form")
    {
        $form["FIELDSET"]["#collapsible"] = true;
        $form["FIELDSET"]["#collapsed"] = true;
    }
}


How to delete duplicate comments using sql? In order to clean up an old large site from spam, I'd like to delete all duplicate comments from mysql. By duplicate I mean, the comments which are posted by the same user across all nodes of a certain type where content of the comments are exactly the same.

For toying things on the backend in SQL. The best place to start would be to look to see how the API does something in Drupal. For this you want to look at comment_delete_multiple which you can call to delete mass comments. You will need to know the comment IDs of the comments that you want to delete.

This is where this gets complicated. You have to find the CIDs you need before you can start deleting. Your criteria for finding the comments is going to depend on what you want to do. If you just want to delete any and all comments that are dupes then you could run a query like this to find dupes and generate the CIDs you want to delete.

Once you ahve the CIDs, it is very easy.You write a delete statement against the comment table.  Using the Drupal API where it would iterate through the list of CIDs

$cids = array( , , , .....)
db_delete('comment')->condition('cid', $cids, 'IN')->execute();

With the amount of comments you are trying to delete doing this strictly in SQL is going to be hard because you will need to write a statement with a gigantic list in a LIKE clause.

In my humble opinion: when I have had to do massive data changes like this in Drupal I write a PHP CLI script to do it so I can handle the data. I've migrated a website that had 150k users, 2000 blogs, and 110k comments, I did it all with PHP CLI scripts.


How can i add text custom field on product detail page? I want to add custom text field on product details page Where user enter some text . Which text will be shown on cart and checkout page. I have added the text field on product but it is not saving .Please guide me what things i am missing?

 function my_module_form_alter(&$form, &$form_state, $form_id)
  {
   if($form_id == 'uc_product_add_to_cart_form_2')
    {

     $form['additional_guests'] = array(
      '#type' => 'textfield',
      '#title' => t("Additional Guest Names"),
    );

}
}

How can i save this custom field and getting on cart/checkout page?

The uc_attributes module, which has been part of Ubercart for 12 years, was specifically designed to handle this situation.

Enable the uc_attributes module. Edit your product, then go to the "Attributes" tab and add a "textfield" type attribute to your product. Your customer will then be able to add text to the purchased product. This textfield will be displayed in the cart, on the checkout page, on the review order page, and in the admin/user view of the completed order.

In short, the correct way to do this is to "Use Attributes and set up a Textfield attribute on your product" as I stated in my previous answer (which was erroneously turned into a "comment" by some unknown user).

The Ubercart project page at https://www.drupal.org/project/ubercart gives links to detailed information about how to do this. Specifically, see:
https://www.drupal.org/docs/7/modules/ubercart/all-about-products/product-attributes-and-options
and the video tutorial at https://www.youtube.com/watch?v=fVDOqI7Gge4


How do you allow a role to assign other users roles - but only specific roles? I'm creating a "level'ing" role system on my page. At a certain role (Full Member) the user must be able to assign someone with the role level 5 the new role level 6 manually once a dialogue is complete.

How can you do this?

I think Role Delegation is what you're looking for.

  For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role.


How to use default taxonomy with a mixture of terms and content? My site has a structure like this, which seems a natural way to use taxonomy:

Food (term)
  - Fruit (term)
  -- Apple (content)
  -- Pear (content)
  - Bread (content)
  - Cheese (content)

The problem arose when I wanted an top-level overview page of Food. Logically (to me) that would mean showing Fruit, Bread and Cheese since these are the direct descendants of Food. But the default taxonomy term page for Food only shows Bread and Cheese, because it only shows content. It doesn't seem like you can show taxonomy terms in views, so overriding the view was not enough and I ended up doing some jiggery-pokery. As a fan of clean logical simple sites I would rather stick close to the defaults. What am I doing wrong?

You probably want to replace the taxonomy/term/## page with a page view of content in that term and "attach" another view to the header that lists the child "taxonomy terms".

That way you them alongside your content as a browsable tree or as a list of "folders" above the content in that folder.


How to associate an image node with taxonomy term? I know this is going to be a very easy answer, but I've been trying to build on someone else's code and am frustrated as hell. I need to link an image type node with a taxonomy term (or a couple terms) for categorizing them. The table is term_node and I just need to know how this table is populated, and how I can link a node (nid) with a term (tid).

When I go to mysite.com/categories/tags/tag_name I can view image nodes linked with that taxonomy term, but there was never a good interface built to add them and I'm not sure how they where added before. His code is a mess. I believe he may have used the Image Assist module, but I'm not sure.

I thought I should just be able to set the taxonomy when adding an image, but there is no such option when adding or editing the node.

why don´t you use the taxonomy image module
then simply get the taxonomy id from the node (use node_load(nid) then identify with var_dump how can you refer to the taxonomy..he might be using the CCK or the taxonomy module ) then get the id(s) of the term, load that term with and see it´s image (again use var_dump to know it´s structure)


Adding JS script, how to format JS I am trying to add this simple script to my block

<script>
    const config = {
      sourceAssetAddress: null,
      sourceAmountDecimal: null,
      destinationAssetAddress: null,
      destinationAmountDecimal: null,
      apiKey: null,
      partnerContractAddress: null,
    };
    const nodeId = "totle-widget";
    !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();
</script>

Problem I have is that I tried to add it as library like this

(function ($) {

    'use strict';

    /**
     * Attaches the behavior to bootstrap carousel view.
     */
    Drupal.behaviors.totle_widget = {
      attach: function (context, settings) {

        const config = {
            sourceAssetAddress: null,
            sourceAmountDecimal: null,
            destinationAssetAddress: null,
            destinationAmountDecimal: null,
            apiKey: null,
            partnerContractAddress: null,
          };
          const nodeId = 'totle-widget';
          !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();
}}}(jQuery));

and somehow script goes beserk after this, loads many times and finaly breaks. It is attached to block in build and should be fine.

$build['#attached'] = array('library' => array('exch/totle'));

So I am not really sure what is wrong here. All I want to is to add this script somewhere in body of my html. Like when I add it directly into html.html.twig template of my theme and it works, but ofcourse I want to do it more in drupal way. What is wrong, how should I add this script to my library?

Using once with proper definition helped.

(function ($) {

    'use strict';

    Drupal.behaviors.totle_widget = {
        attach: function (context, settings) {

          // Using once() so script is loaded only once
          $('#totle-widget', context).once('totle_widget').each(function () {

            const config = {
                sourceAssetAddress: null,
                sourceAmountDecimal: null,
                destinationAssetAddress: null,
                destinationAmountDecimal: null,
                apiKey: null,
                partnerContractAddress: null,
              };
              const nodeId = 'totle-widget';
              !function(){const t=document.createElement("script");t.type="text/javascript";const e=()=>{TotleWidget.default.run(config,document.getElementById(nodeId))};t.readyState?t.onreadystatechange=function(){"loaded"!=t.readyState&&"complete"!=t.readyState||(t.onreadystatechange=null,e())}:t.onload=function(){e()},t.src="https://widget.totle.com/latest/dist.js",document.getElementsByTagName("head")[0].appendChild(t)}();

          });
        }
      };

  }(jQuery));


Exposed filter list by tags I have a view, which is listing nodes. I like to exposed filter it by tags (what is a taxonomy). But I like to show tags, what is relevant (has nodes) for the current view. How can I make it?

You need to add a field in view with name
Content: All taxonomy terms
Display all taxonomy terms associated with a node from specified vocabularies.
That will display all terms associated with a node


is there a way to find out which quicktab tab is active? I would like to know which tab is active so I can set it to default until another tab is active then that will be set to default

my problem is that I cant seem to find a way to see which tab is active at the moment and getActiveTab seems to always return the default tab

any help well be greatly appreciated

thanks in advance

After much consideration and a ton of tries I decided to go with cookies,I added this to my script file from
http://drupal.org/node/1454486

Drupal.behaviors.quicktabsHistory = {
attach: function(context, settings) {
  // enable accordion memory
  $('.quick-accordion', context).each(function() {
    var id = $(this).attr('id');
    var accordion = $.cookie(id);

    if (accordion != '') {
      $(this).find('h3 a[href="' + accordion + '"]').click();
    }
    $(this).find('h3 a').click(function() {
      $.cookie(id, $(this).attr('href'));
    });
  });

  // enable tab memory
  $('.quicktabs-wrapper', context).each(function() {
    var id = $(this).attr('id');
    var tab = $.cookie(id);

    if (tab != '') {
      $(this).find('ul.quicktabs-tabs a#' + tab).click();
    }
    $(this).find('ul.quicktabs-tabs a').click(function() {
      $.cookie(id, $(this).attr('id'));
    });
  });
}
};

thanks for your time and efforts


Why is Drupal with redis slower than mariadb? I've got a big Drupal site running Commerce, with cloudflare caching static resources, maybe 20K users or more per day.

MariaDB caches about 500mb worth of queries, we're running freeBSD with php56 and php fastcgi. I'm using the redis PHP extension.

When I turn on redis for all the cache tables, I see the php-fcgi processes start to spike from 7% CPU up to about 35% and load goes through the roof.

Tried it a couple of times, which would minimize cache stampeding, but still I'm somewhat confused as to why redis is performing so poorly.

I've read through redis.conf and the main change I've made is not to snapshot the db to file.

I can connect with redis-cli monitor and see tons of cache data passing through.

Any ideas about what's happening here?

Thanks!

This topic should probably be closed, as the Drupal Redis module maintainer, I am taking over the issue in the module official issue tracker, specific questions are pending there, and a few micro-optimizations have already been done since this question was opened.

For everyone that would help us or need support, please consider participating to https://www.drupal.org/node/2550275 - this would be great help.

Thanks in advance to everyone that will give us a few minutes to solve this and improve the module.


Get node path for different domain I have a series of nodes which are published on up to 7 different domains on the same single Drupal 7 install. Whilst I can use url('node/12345'); for nodes published to the current domain, I would like to create href links to the these nodes and have them link to the correct domain path.

At the moment, nodes that are not published to the current domain are just giving me href="/12345".

How do I get the URL for nodes that aren't in the current domain?

You could try drupal_get_path_alias('node/12345') (see docs) and then exchange the domain name.


Bakery doesn't pre-sync accounts I want to use the Bakery module to login and synchronize users, but I am not able to synchronize existing accounts. Users that exist only on slave cannot login confirms Bakery doesn't provide pre-sync facility.

May someone help me to synchronize existing user accounts, possibly at database level, for example with drush rsync or sql sync?

I would go with the migrate module, it's no syncing but export and import in two steps. But i cannot tell you if existing users will be replaced, skipped or doubled ..

Maybe account_sync does what you want.

Also have a look here How to sync users profiles and user tables in 2 drupal sites.


How do I set the fixed amount of values to 11? I'm setting up a field with multiple values. The maximum fixed amount of values I can configure is 10.

If I want more I have to set this to unlimited.

Is there a way tho set the fixed amount of values on a field to 11 values?

The cardinality options are hard-coded into the field_ui_field_edit_form() function using these lines of code:

$form['field']['cardinality'] = array(
  '#type' => 'select',
  '#title' => t('Number of values'),
  '#options' => array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + drupal_map_assoc(range(1, 10)),
  '#default_value' => $field['cardinality'],
  '#description' => $description,
);

It's the drupal_map_assoc(range(1, 10)) line which is limiting the number to 10.

It doesn't seem that the maximum cardinality is validated (or further limited) anywhere else, though (at least not by core), so it would be pretty easy to offer more options for that value using a form alter hook:

function MYMODULE_form_field_ui_field_edit_form_alter(&$form, &$form_state, $form_id) {
  // Increase the max cardinality to 20
  $range = drupal_map_assoc(range(1, 20));
  $new_options =  array(FIELD_CARDINALITY_UNLIMITED => t('Unlimited')) + $range;

  // Change the options
  $form['field']['cardinality']['#options'] = $new_options;
}

I've just tried this out and it seems to have no side-effects at all. The field system respects any cardinality you set that's higher than 10, and saves it without problem when you edit the field in the admin UI.


How to change conditions of views filters programmatically? I have a view with a node type filter. I want to change it in some conditions. How do I change this filter in hook_views_query_alter()?

You specifically ask for altering the View programmatically, and that certainly is possible. I will however suggest an easier way. With Views 3, you can group your filters. This way, you can achieve the effect you are asking for by adding two separate groups of filters.

Group 1: Node:type == [type]

OR

Group 2:  User:role == [role] AND Node:type == [other_type]


Can the recently read module show multiple nodes? I am working with the recently read module and it is only showing the last node visited. I want it to show the last 5 nodes visited and that seems like what the module is supposed to do. I have session API enabled so that I can have this available for anonymous users as well. Does anyone know why it is only displaying a single node?

From the content of your question, I have the impression that you misunderstand what the Recently Read module is about. More specifically (from its project page): it keeps track of "... the history of recently read content (nodes) both to anonymous and authenticated users ...".
Anonymous users is a special case, but for logged in users each user has his/her own "history".
Issue #1973526 also confirms that, here is part of what that says:

Since you don't want your database getting forever more massive for no good reason (it is likely you will only ever be showing the last 5 or 10) it would be good to have an option to limit the maximum number of entries in the recently read table for each user.
For example I can set it to 5 and the database would only ever have 5 entries per user at most.

It would be interesting to know, for your environment, how many nodes (more then one?) you visited with the user you are logged in with (if you are logged in). To remove any doubt about that, consider editing your question by adding some scenarios (+ results you get) like "user 1 visited node a, b and c; user 2 visited b, p, q, r, s, z, ..."; anonymous user visited k, l , m ..."


How to change design in comments list I am listing all the comments in a page.

For example, suppose the comments are listed using a design similar to the following one:

  Comment Title 1

  Comment Description 1

  Comment Title 2

  Comment Description 2

  Comment Title 3

  Comment Description 3

If the third comment is the last comment, I should not print the line for that comment.

How can this be done?

EDIT: Updated to use a preprocess function.  This still might not be pretty, but works fine.  In your template.php file in your theme, add this function (replacing YOURTHEME with the name of your current theme):

function YOURTHEME_preprocess_comment(&$variables) {
  $display_order = _comment_get_display_setting('sort', $variables['node']);
  if ($display_order == 1) {
    $variables['end_comment'] = db_result(db_query('SELECT MIN(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
  else if ($display_order == 2) {
    $variables['end_comment'] = db_result(db_query('SELECT MAX(cid) AS cid FROM {comments} WHERE status = 0 AND pid = 0 AND nid = %d', $variables['node']->nid));
  }
}

Now copy comment.tpl.php from modules/comment and place it in your theme folder.  Add this code

print $end_comment == $comment->cid ? ' last' : '';

to the class area of the div html.  It should look something like:

<div class="comment<?php print ($comment->new) ? ' comment-new' : ''; print ' '. $status; print $end_comment == $comment->cid ? ' last' : ''; ?> clear-block">

You now have a class of last on the bottom comment, no matter which way they are sorted.  Now simply add some simple CSS to your stylesheet:

div.comment.last {
  border-bottom: none;
}

You can also use jQuery or CSS to remove the bottom border from the last comment, but they are less reliable depending on a user's browser, browser settings, etc.

jQuery:

// Remove border from last comment
$('#comments div.comment:last').css('borderBottom', 'none');

CSS (Works in IE9, but unfortunately will not work with IE8 and below):

div.comment:last-child {
  border-bottom: none;
}


Trying to display data from a module's table in views I'm trying to show the purl.value value on a view's page.

It seems to be grabbing all of the data, however it isn't showing in the final results. Here's my code:

function mymodule_views_query_alter(&$view, &$query) {
  //watchdog("view information", print_r($view, true));
  if ($view->name == 'project_management') {

    $join = new views_join;
  $join->table ='purl';
  $join->left_table = 'node';
  $join->left_field = 'nid';
  $join->field = 'id';
  $join->type = "LEFT";
  $join->extra_type = 'AND';
  $join->adjusted = 'TRUE';

    $view->query->table_queue['purl'] = array(
    'table' => 'purl',
    'num' => 1,
    'alias' => 'purl',
    'join' => $join,
    'relationship' => 'node',
  );

    $view->query->tables['purl'] = array(
    'count' => 1,
    'alias' => 'purl'
  );

$view->query->add_field('purl', 'value');
  }
}

What exactly am I missing? Do I need a view handler? I was told that maybe using hook_views_data_alter() might be better for my purposes.

How do I add a visible custom piece of data from that column on my view page?

you should map your data to views, so it will be available from views admin UI

check This tutorial where you will find the basics for describe custom data and tables to views.


How to get next valid `product_id` value within Rules for drupal commerce product? I'm using Rules to create drupal commerce products. The problem is that the product_id is not assigned.

Since the Rules settings page for creating products only gives the following options, I assumed that the product_id would be generated automatically:

Entity type, SKU, Type, Title, Creator, Price, Provided variables.

If the product_id has to be added manually (within Rules) how would I obtain the correct value to use? (Or is there a setting I am missing within Rules?)

Cheers!

You cannot set the product ID manually, because it depends on the AUTO_INCREMENT value in your commerce_product database table. What you can do is use "Save an entity" on the product and check the "Force saving immediately" checkbox. The entity will have an ID after that, though I've had scenarios in Rules where for some reason the ID wasn't immediately added to the entity in memory. If this happens to you, you'll just have to use "Fetch an entity by property" after saving and load the product using the SKU or something and use the fetched_entity from then on.


How can I print something conditionally on node.tpl.php depending on what taxonomy term the node is tagged with? For example, I would like to print something only when the currently viewed node is tagged with tid = 100. How can I do this?

Can you try this...

<?php if ($node->taxonomy[100]): ?>
    print anything here
<?php endif; ?>


How to merge multiple fields into one, across multiple content types? I'm updating some old Drupal 7 sites, and I need to merge a number of fields across multiple content types.

For example, I have the field_article_body, field_page_body, and field_event_body fields that needs to be merged into the core body field, or the field_article_image, field_page_image, and field_event_image fields that need to be merged into the field_image field.

I am hoping there is some solution which can assist me in combining these fields, or alternatively some SQL magic which an expert can help me with.

Do you have any idea?

By using Views (to build a list of nodes to be updated) and a combination of Rules and VBO (to mass update such lists) you should be able to perform the merge of those fields.

Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that, which is about a variation of your scenario (ie change the value of an existing field, while you want to "copy" the value of an existing field to the value of a new field).

For your case, this example of a Rules Component (in Rules export format) should be close to one of the Rules Components you'd need for your "field_image":

{ "rules_set_an_initial_value_for_image_field" : {
    "LABEL" : "Set an initial value for image field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_image" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-image" ], "value" : [ "field_article_image" ] } }
    ]
  }
}

Note: by using an approach with modules such as above (instead of SQL magic), you do have the advantage that all possible relatic magic will happen automagically and behind the scenes (eg: create a new revision of such nodes). And it avoids your Drupal database gets corrupted because "you forgot some table".


Set custom timer for Slick slideshow based on field value I have a Slick slideshow. My nodes have a Timer field. Right now, I am setting the time of the slick slide like so:

Drupal.behaviors.mrpeanut = {
  attach: function (context, settings) {
    var $slider = $("#slick-views-slideshow-page-1-slider");
    $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
            slideTime = $('div.slide--' + slick.currentSlide + ' div.field--name-field-timer').text();
            $slider.slick("setOption", "autoplaySpeed", slideTime);
        });
  }
}

However, I had some feedback that I may be better off to preprocess the field then attach a JS settings array with all the timer values. This is what I started piecing together based on some discussion in Slack (thanks, @nikathone).

In mrpeanut.module:

function mrpeanut_preprocess_node(&$variables) {
    $variables['#attached']['library'][] = 'mrpeanut/mrpeanut';
    $node = $variables['node'];
    $slideTime = $node->hasField('field_timer') ? $node->get('field_timer')->value : 20000;
    $slideTime = $slideTime * 1000; // Convert milliseconds to seconds
    $variables['#attached']['drupalSettings']['slideTime'][$node->id()] = $slideTime;
}

In mrpeanut.js:

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var $slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;

            // Get Node ID from the article
            var nodeAbout = $('.slide').find('article').attr('about');
            var nodeID = nodeAbout.substring(6, $('.slide').find('article').attr('about').length);

            $slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                $slider.slick("setOption", "autoplaySpeed", slideTime);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);

However, it's not actually setting the correct timer values. One issue I'm having is that I need to capture all Node IDs from the view (whereas now I am only getting the first). Second, I'm setting the time slide on the afterChange instead of initially all-at-once.

Here's my final mrpeanut.js:

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.mrpeanut = {
        attach: function(context, settings) {
            var slider = $("#slick-views-slideshow-page-1-slider");
            var slideTime = drupalSettings.slideTime;
            var nodeIdArray = []
            $('article').each(function(i){
                var nodeAbout = $(this).attr('about');
                var nodeID = nodeAbout.substring(6, $(this).attr('about').length);
                nodeIdArray.push(nodeID);
            });

            slider.once('mrpeanut').on("afterChange", function(event, slick, currentSlide) {
                slider.slick('slickSetOption', 'autoplaySpeed', slideTime[nodeIdArray[currentSlide]], true);
            });
        }
    }
})(jQuery, Drupal, drupalSettings);


Is it possible to completely hide the admin menu for a role, while still grant it some admin permissions? I need to create a 'Demo' role that can completely hide the admin menu toolbar, but can still access some admin pages to, well, demonstrate stuff.

What would be the best way to do this in drupal 8? Is there some kind of built in functionality to do this?

Uncheck "Use the administration toolbar" for the 'demo' role under Users > Permissions.


How to Bulk delete the document from solr without actually deleting the node? The scenario is to delete bulk documents from apache solr, without deleting the actual node from the database. I am aware that when the node is un-published it will be deleted from solr.

But as my node are very large containing 1000's of terms I don not want to use node-save to un-publish the node.

Is there any hook or function which un-publishes the node and deletes from solr by minimal load (definitely not node save)  ?

UPDATE:

Drupal Version : 7.15
Modules: Apachesolr

I found the answer on exploring the apache solr module,

STEP 1

Select the nodes from the node table alone or by joining the apachesolr index entities table,

// Check for unpublished content that wasn't deleted from the index.
  $table = apachesolr_get_indexer_table('node');

 // Select the nids from the node table
  $query = db_select($table, 'aien')
    ->fields('aien', array('entity_id'))
    ->condition('n.nid', 0);
  $query->leftJoin('node', 'n', 'n.nid = aien.entity_id');
  $nodes = $query->execute()->fetchAllAssoc('nid');

STEP 2

Chunk it to some limit and call the apachesolr_index_nodeapi_mass_delete function

      $node_lists = array_chunk($nodes, '100', TRUE);
  foreach ($node_lists as $nodes) {
    watchdog('Apache Solr', 'On cron running apachesolr_nodeapi_mass_delete() on nids @nids', array('@nids' => implode(',', array_keys($nodes))), WATCHDOG_WARNING);
    if (!apachesolr_index_nodeapi_mass_delete($nodes, $table)) {
      // Solr query failed - so stop trying.
      break;
    }
  }


Embedding a webform inside a node content I need to embed a webform inside content, which is a node. How can this be implemented?

There are several ways to do this.  The method I normally use it to make a custom Panel page for my node.  The content area will contain the "node being viewed" as well as a custom block that renders out my form.

The easiest way, though, is to use the Webform module, and you can build your forms with the UI and easily attach them to a content type.


How add query to EntityListBuilder I want to add a query to filter my entity list table.

class CommandesLignesEntityListBuilder extends EntityListBuilder {

  use LinkGeneratorTrait;

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header['id'] = $this->t('ID');
    $header['produit'] = $this->t('Produit');
    $header['quantite'] = $this->t('Quantité');
    $header['prixHT'] = $this->t('Prix HT');
    $header['TVA'] = $this->t('TVA');
    return $header + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /* @var $entity \Drupal\boutique\Entity\CommandesLignesEntity */
    $row['id'] = $entity->id();
    $row['produit'] =$entity->getProduit();
    $row['quantite'] =$entity->getQTE();
    $row['prixHT'] =$entity->getPrixHT();
    $row['TVA'] =$entity->getTVA();

    return $row + parent::buildRow($entity);
  }

}

This show me all lines. How can I filter this with a query? For example, how can I get only lines with price greater or equal to 100?

i would like a permanent query for this EntityListBuilder sub-class.

Although not exactly a duplicate of How to make EntityListBuilder sortable? it is essentially the same answer as Berdir wrote,

  You'd have to implement the query logic yourself.

For instance, BlockListBuilder overrides getEntityIds to add a condition on the theme key.

However as Berdir also notes,

  For content entities, I would strongly recommend to rely on the views
  integration instead. List builders are limited in functionality and
  mostly useful for config entities only.


XHProf not displaying runs but empty table I'm trying to profile a drupal website using xhprof. I manage to install it and configure drupal to use it (using the devel module) but I have a problem to visualize the result.

First, for some reason I didn't manage to get the access rights to xhprof_html through apache. Instead of using apache I just cd into xhprof_html directory and run php -S myhost:8080. I can then see the main page with all the runs, but when I select a run, it's empty. I can see the table and everything but there is no functions displayed. When I look at the run with a text editor it seems ok.

What am I doing wrong ? Is there another tool to visualize xhprof runs ?

I found the problem, the developper module (used to activate XHProf) use the site name to generate the run. The site name contains the & character which messes up the URL corresponding to run.


Filtering a glossary view I have a glossary view, which is just the one that comes with Views. I want to allow users to filter the results by taxonomy terms (dropdown) and also by title (search field). The problem I'm running into is that when I click on a glossary letter (e.g. X) then I try to type in a search term that begins with something other than X (e.g. Cat) I get no results. The title search filter is basically just searching within the selected letter in the Glossary. So if I'm on the X page and I search for Cat nothing is found. If I would search for X-ray then that would appear.

Is there any way to make the title filter relatable to the entire view result and not just things that begin with the glossary letter than I have selected?

In the attachment of the view I've tried turning on the "Inherit exposed filters" option but that does not help.

This can be solved by changing your Views filters to be connected using an OR instead of an AND. This option can be accessed by through the Views interface using the steps below.

1.

2

3


How do I create different user registration pages? In my project, I need to have two types of user: normal user (who can buy products) and merchant user (who can upload products).

I made the registration page by creating the user_register.tpl.php template file.
I don't have any idea about how to make another registration page which will be used for merchant users.

Is there a contributed module available for this?

Basically you have to create only one registration page. And you have to create two roles.
Normal User and Merchant User
Add these roles field on user registration page using Auto Assign Role module.
Configure permissions for the respective role. Like Normal users can buy product and Merchant users can create product
If you are using Commerce Kickstart then you will have permission for adding product and other permissions.


give value to form element after select event - value should be catched with JQuery I'm pretty new with Drupal & JQuery. I post this question because I was not able to find a solution in the net.

I have a select form element to choose a country. This select displays de country names but keeps the country_code because this is the value to be stored in the DDBB once the form submitted. This select element is linked to ajax because there is a second select field which should show values depending on the selected country.

As soon as the complete address is introduced, JQuery should show a map with the location of the entered address. For that reason I need JQuery to access the country name before the form is submitted.

There is a function that returns the country name for a given country_code but I do not know how to run that function so that the result can be catched by JQuery. One solution would be keep the country_name instead of the country_code (in the select element) but then , into the submit function of the form, I would need a function to get the country code and I would like to avoid this.

$country_list=get_country_list();

$form['c_pais'] = array(
'#title' => t('Address - Country'),
'#type' => 'select',
'#options' => $country_list,
'#required' => TRUE,
'#default_value' => $value_country,
'#ajax' => array(
    'event' => 'change',
    'callback' => 'call_region1_select',
    'wrapper' => 'dropdown_region1',
),
);

function get_country_list()
{
    db_set_active('mydb');
    $result=db_select('country_list')
    ->fields('country_list',array('country_id','country_name'))
    ->orderBy('country_name','ASC')
    ->execute();
    $llista_paisos['0']='--- chosse a country ----';
    while($node = $result->fetchAssoc())
    {
        $llista_paisos[$node['country_id']]=$node['country_name'];
    }
    db_set_active();
    //print_r($llista_paisos);
    return $llista_paisos;
}

Use like this to get form select list element in jQuery.

$("#elementId :selected").text() //the text content of the selected option(country name)
$("#elementId").val() //the value of the selected option(country code)


Unique field value for all nodes and content types I have list integer field in 3 content types and each have same possible values (from 1 to 6) and I need to disable user to choose the same number for two nodes, so each node with this field filled in need to be unique.

I found Unique field module but it is not working for me, because I have field in each content type and I need to look at all nodes from all content types and this module is on content type base.

Basic example of what I need:

Field field_1 from content type type_1 have value 5, so field_2 from content type type_2 and field_3 from content type type_3 can't have value 5.

Any idea how to achieve this?

Check out this example

function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}


Add a map for each node in a view I am building a restaurant application which would have a search functionality, and when somebody searches of restaurants for a zip code, it would return the data. The data would be the name of the restaurant, the description and the map. When a user is adding the restaurant, I am using address field and geofield to get the latitude and longitude, so getting the maps up and running isn't an issue now.

However, I trying to create the search view, but I am unable to create a view which has a path, and which would display the title, description and then the map.

ex: Title | Description
    MAP1(map for first restaurant)

    Title | Description
    MAP2

Can somebody tell me how would I build it?

The modules I am using to build this are geofield, geophp, geocoder, addressfield, openlayers, views, ctools and libraries.

You can add the map into a view in simple way.
Enable the "geofield map" module .Create a view . you can add a field(geofield) and in the settings you can give the "Formatter" as geofield map. You can also add the other fields you needed from that node.

Step 1 :Enable the "geofield map" module in the  geofield module pack. Than create a view with the geofield (latitude and longitude) fields with a contextual filter node id. In the view you can set the "Format" as geofield map(see attachment). . You can also do with the help of "location" module. Now you have a view of map.

Step 2: Enable the views_field_view module. Create another view for the restaurant details. For viewing the map, you can select "Global :view" in the field. There you can select which view you should have to embed in that field and you can give the arguments there(here 'nid') in the field settings(see attachment).

See also the Views Field View module, which may help you.
You can first create a view for the map with a argument as node->nid. Then create another view for your restaurant. In the second view you can embed the first view (for map) as a field.


Content Types with field "clusters". Possible or is there a different solution? My dilemma is this. At the moment I have a content type called "equipment" that I want to have a taxonomy term that will give a type of equipment, based on the selected type I want a new "cluster" of fields and/or taxonomy terms to pop up.

There is likely a different/better way of organizing the data.  Creating a new content type for each type of equipment doesn't seem very elegant, especially if I want to create a view for all of the equipment.

Any leads on where I can find a solution to this? My brain has problems with decorator patterns in SQL as well.

Probably the easiest solution is to have a single content type, add all fields that you need in any possible situation, and use Conditional Fields to hide/show fields based on the chosen equipment type taxonomy term.


Empty View does not display "No results behavior" for admin I have a View content pane with a setup to display "Header" when there is content and "No results behavior" when the view is empty.
The view works fine for authenticated and anonymous users, however it always shows the "Header" instead "No results behavior" for empty view to the admin.

Looking at the html output for the view, I see an empty table with one empty row is being generated for admin, but not for authenticated or anonymous users.

In the view table settings, all empty columns are set to hidden. All fields have hide empty checked with no rewrite. The views has a contextual filter to display no results when filter is missing.

Its baffling that the view works for others except admin.
Any tips will be appreciated.

I had somewhat complex filter criteria that was causing the issue for admin.
One would think that this should not cause an issue, but it seems to.


How to get nodes created on current using Views and Drupal 8 How can I display records that were created on the current date using views. I have used the now value on the created date filter but the records are not showing. I think its because now also includes the the current time. Please Help?

You can use Content: Authored on in views filter criteria and specify offset today.
I was able to achieve event date filter using below code.
I was able to achieve this using custom coding may be it will help you.

function common_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_present_year') {
       // print_r($query->where[1]['conditions'][2]);
        $current_yr_start = strtotime(date('Y-01-01'));
        $current_yr_end = strtotime(date('Y-12-31'));
        $current_yr = 'node_field_data.created BETWEEN ' .$current_yr_start.' AND '.$current_yr_end;
        //$current_yr= 'node_field_data.created = '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        /*print_r($query->where[1]['conditions'][2]);
       kint($query->where[1][3]);
        dpm($query);*/
        }
        if ($view->id() == 'new_page' && $view->getDisplay()->display['id'] == 'news_block') {
        //print_r($query->where[1]['conditions'][2]);
        $current_yr= 'node_field_data.created < '.strtotime(date('Y-01-01'));
        $query->where[1]['conditions'][2]['field']= $current_yr;

        //print_r($query->where[1]['conditions'][2]);
        }
    }


Date #return_value to ordinary time() So I have included a date field in my custom block form and would like to use the date.

However it is saved as an array which I am finding a little difficult to work with:

  The format for "#default_value" and "#return_value" is an
  array with three elements with the keys: 'year', month', and 'day'.
  For example, array('year' => 2007, 'month' => 2, 'day' => 15)

What is the best way of getting this "date array" into something I can use strtotime() on? Am I missing some Drupal way of allowing me to format this nicely into a string?

What I have working seems to be very long winded and static:

$startDate = variable_get('start_date', NULL);
if (isset($startDatea)) {
  $startDate = $startDatea['month'].'/'.$startDatea['day'].'/'.$startDatea['year'];
  $startDate = date('Y-m-d', strtotime($startDate));
}

I am sure there must be a nicer way.

For what it's worth you have a typo in your sample code, $startDate is being referenced as $startDatea - note the extra "a". As for a shorter version, try:

$startDate = variable_get('start_date', NULL);
$startDate = date('Y-m-d', mktime(0,0,0, $startDate['month'], $startDate['day'], $startDate['year']);

I suspect not jumping from numeric to string and then back again might save you a few cycles at the PHP layer.


How can I get the name of the currently logged in user in Drupal 7 in the external file? In an external file I use the following code:

$path = $_SERVER['DOCUMENT_ROOT'];
chdir($path."/drupal");
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

global $user;
print $user->name;

The code doesn't print anything, but this code works:

$account = user_load(2);
print $account->name;

How can I get the name of the current user in Drupal 7?

I advice you to:

create a module
put your script in that module (inside one or more functions)
implement hook_menu() to define the url you can call (eg. example.com/mytuff/ajax) and set your script's (main) function as the 'page callback'
instead of returning stuff (like page callbacks normally do) print your output and exit() at the end


Use field from current node in filter in view I have a content type called 'article_landing' and a content type called 'article'.

They both have an entity reference field called 'field_focus_area'.
I'm attempting to create a view that appears as a block on an article landing node and only displays articles that have the same field_focus_area as the current node. I'm having trouble figuring out how to do this though. I thought this would need to be accomplished with contextual filters but I'm not getting any results.
Below is the method I was using.

I also tried using regular filters and using tokens like [node:field_focus_area] but that didn't work either.

Is there a way I can use fields of the node that a view block appears on inside filters in the view?

Niall Murphy's concept is correct but there are some differences between how it's performed in D8 and D7. Here is the code I ended up using which was successful.

function my_module_views_pre_view(&$view, &$display_id,&$args){
    if($view->id() == 'news'){
        if($view->current_display == 'block_2'){
            $current_node = \Drupal::routeMatch()->getParameter('node');
            if(!empty($current_node)){
                $focus_area = $current_node->field_focus_area->entity->id();
                $args[0] = $focus_area;
                $view->setArguments($args);
            }
        }
    }
}


Mark only event's start date and end date in event calender I want to mark only the start date and end date in the event calendar. For example, if the event starts from 5th of a month and ends on 17th of the same month. I need to show the text event1 opening on 5th  and event1 closing on the 17th.

An event calendar is instead shown as follows.

I'm using FullCalendar for this.

How can I achieve this?

If you're using FullCalendar to dispaly the calendar, you need to register two separate events:

Exhibit opening: Wild & Wonderful (starts end ends on the 5th).
Exhibit closing: Wild & Wonderful (starts end ends on the 17th).

Now, the opening and closing event will appear independent of each other,