Problems with active-trails I have played with Menu Trail by Path and Menu Position, but none worked well with a Views-generated listing acting as a navigation menu.

Imagine the following scenario:

On the left side there is Views generated block of linked taxonomy terms.
When clicked, the link fills the main content area with a listing of nodes tagged with the given taxonomy term. The activated term link gets active-trail class - so far so good.
When you click a node link though, the node opens, but now - the active-trail is gone.

The complicating factor might be that my taxonomy is localized (each term has a translation within same vocabulary). But I believe there is a solution to that... Anyone?

It's important to understand that taxonomy is not a menu system, the menu system is.  There are ways to make the menu system mirror taxonomy, but they are separate systems.  Taxonomy_menu might be able to help.


Drupal 8 translation for routing titles In Drupal 8, I installed all translation modules (Configuration Translation, Content Translation, Interface Translation, Language) and cleared all caches and run cron again.

But the titles defined in routing YML files are still missing from the User interface translation configuration page (/admin/config/regional/translate)

Any idea?

Just figured it out.

After installing all above modules, we still have to visit the page defined by the routing and switch it to another language (non-English).

Then system would automatically pick up all strings in the page needed to translate, including the title.

The source string is case sensitive.


Where is Update translation? In admin/config/regional/translate/update I found the following message:

If there are available updates you can click on "Update
translation" for them to be downloaded and imported now or you can
edit the configuration for them to be updated automatically on the
Update settings page

The following screenshot reveals more:

I could not able to find Update translation anywhere. What is missing?

I suggest you the installation of Localization update module.

From the module's page:

  Automatically downloads and updates your translations by fetching them
  from localize.drupal.org or any other Localization server.

I use this module in all my projects, you can also have the .po files in the local server.


I want to send a confirmation mail on event of submit button in webform? I have a webform and a E-mail field in it Is it possible to have a confirmation mailed out to the person registering? (as in, is it possible to have the functionality also worked in?)

The webform module comes with an option to send e-mails after submission. Check the webform e-mail tab when you are editing a webform


Robots.txt and language exclusion I want to add a language on my drupal 6 site but I want that Google doesn't index every page in this language (fr).

Can I use robots.txt and and add something like this?

Disallow: /fr/*

Drupal by default comes with robots.txt file. You can find the file in Drupal Root.

Yes, you can go ahead and change. Below code also should work.

Disallow: /fr/

But, if you use

Disallow: /fr/*

As per wikipedia

  Universal * match The Robot Exclusion Standard does not mention
  anything about the * character in the Disallow: statement. Some
  crawlers like Googlebot and Slurp recognize strings containing *,
  while MSNbot and Teoma interpret it in different ways.


Disable click event on Next button on checkout form's first step if all cart products are removed I am new to learning jQuery and JavaScript. I have small task that is becoming hard to solve.

On step one of a checkout form #ps-cart-checkout-form, I have to disable
Next
 when cart table is empty or emptied by clicking an "X" image in cart table row So that user does not go forward. Button's location and HTML is:

Side 1/2

Next

Cart table (.table-cart) when having one or more products it contains
 tag but when empty the
 becomes
 with one row  in it.

My approach:

I have tried to create a module that add js on hook_form_alter. and in js file. I have created :

(function ($) {
Drupal.behaviors.myModule = {
  attach: function (context, settings) {
      var $form = $("#cart-checkout-form");
      if($($form.find("thead").lenght == 0) {
        $(".button").unbind( "click" );
        }

      });
   }
}(jQuery));

With above code I am trying to find out if there is no
 that means table is empty and therefore above code should disable the click next button.
There already having a jQuery code that handles click event on Next div.

What module are you using for the cart?

you can also use preventDefault() function to stop the page from loading to the next page.


how to export views in batch Is there a module to automate exporting/importing a batch of Views (for import onto another site?)

I have a Commerce Kickstart site with demo data. I can't figure out how to remove the demo data without resetting the site, so I'm going to start over.

I want to take some Views I created myself with me. (Unless someone has the magic trick to remove all Commerce Demo data...including Product Types without using Reset() of course. :D )

TIA.

I have often been advised to just save my Views as a Feature. Any reason this won't do the required?


Rendering a CCK Date field exaclty I am having an interesting problem with some birthdate data in my profile nodes. I am using Drupal 6.

There are two people:
Ann has the following UNIX timestamp value stored in the db: 353026800
Her profile page renders it as '1981. March 10'. When I edit the node I see also this value.

Bete has the timestamp in the db: 484696800
His profile page renders it as '1985. May 11' but when I open the node for edit then I see 1985. May 12.' in the date edit box.

The profiles are rendered in a custom tpl.php and the according piece is as follows:

format_date($p->field_szuldat[0]['value'], 'custom', 'Y. F. d.');

When I dpm the loaded node then I see that both fields have the same Europe/Budapest timezone. I see that Bete's birthdate is (not counting the days) is 1 hour before Ann's. But I see that Drupal somehow handles it and renders the values in the edit boxes properly. It might be related to DST because Bete was born in DST and Ann wasn't.

My question is: how could I make my template's date rendering also handle it properly?

I have read all the related comments to the topic, but they do not match my case because here an extra hour is being added to one of my dates.

UPDATE:

The field I am talking about is a "Datestamp" with the following configuration: "No timezone correction" is set, the granularity is only year-month-date.

Solution:

$birthdate_object = date_make_date(
   $p->field_szuldat[0]['value'],
   $p->field_szuldat[0]['timezone'],
   $p->field_szuldat[0]['date_type'],
   $granularity = array('year', 'month', 'day'));

$birthdate_formatted = date_format_date($birthdate_object, 'custom', 'Y. F j.');

This yields incorrect value in the DST period of the year (1 day difference), so very dangerous:

$wrong_birthdate = format_date($p->field_szuldat[0]['value'], 'custom', 'Y. F. d.');


How obtain the uid of the logged user as a related field in a view? I have a view showing the nodes of a content type, and I want to show the user ID of the currently logged-in user as a field in view, but I can't find how to add the user ID of the currently logged-in user. I know that I can achieve this with the Views PHP module but I want to know if there is another way.

I have Views 3.11.

There is no relation between the content being shown, and the currently logged-in user; I just want to show the user ID of the user who is currently seeing the view.

You can't without some custom module providing such a data field (such as views php as you've seen).

Unless the uid has some relations to the content type you're displaying (e.g. a user reference field, the node uid, etc.), there's no way to retrieve the current UID. Views is designed to pull in data from a base table (e.g. nodes, users, taxonomy, etc.) and display the fields directly attached to it or related to it through a relationship.


Any good CDN integration with Drupal? I'd like to set up a simple gallery for users to upload pictures onto my D7 site, but uploading a bunch of images is sure to make my site run slower and my hosting costs go up. So I'm looking at a CDN (specifically, blob or object storage).

Both of the Azure modules (1 and 2) are not actively maintained, and the Amazon S3 module is still in beta, so I'd be hesitant to use it on a production site.

Here's my question: Is there any good Druapl module that will let me bypass the filesystem on the webserver so that users can upload images directly to a CDN? I know there are hooks in D7 that make this possible, but has anyone actually managed to do it yet? I can't believe there isn't better support for CDNs for Drupal. :(

Drupal 7 has robust CDN integration with a number of options. You can consider the Storage API module for S3 integration among others.

  Storage API is a low-level framework for managed file storage and serving.

Also consider the CDN module.

  This module provides easy Content Delivery Network integration for Drupal sites. It alters file URLs, so that files are downloaded from a CDN instead of your web server.


How do I get a parent-group alias as token for the Pathauto module? When a user sets his groups alias to lets say "mynewgroup" you can view the group at www.example.com/mynewgroup.

How to set pathauto presets to create www.example.com/mynewgroup/mynewgroupcontent as a path for a newly created group-content?

I can not find a token for parent's group alias.
I can only find [group_content:gid:entity:url] - but this provides full path and not only the alias.

Not possible at the moment (unless you make it yourself), there is an issue in the module's issue queue though that also has a patch that might work:

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


Finding the code generating the menu with links Where is the code that generates the menu and links shown in the following photo?

Have you tried this: http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_link/7#comment-24463


Custom login form with signin button -- POSTing registration I have added a "register" button to the login form which is shown as a block on my homepage. I want the button to simply redirect to the registration page but it's POSTing to login and error'ing -- any ideas?

  function MYMODULE_form_user_login_alter(&$form, &$form_state) {
    $form['actions']['register'] = array(
      '#type' => 'submit',
      '#value' => t('Sign Up'),
      '#submit' => array('_user_login_register_submit')
    );
  }

  function _user_login_register_submit($form, &$form_state) {
    drupal_goto('user/register');
  }

It's not working because the login form validate handler is executed, and fails, before the function you call with the #submit attribute.

You can use #validate like a workaround probably, but there's a cleaner way to achieve what you are after.

I wouldn't create a button element at all. Make it a link to user/register instead and style it to look like a button if needed.


Loading fully themed node with Ajax - Drupal 7 I am loading node content to a specific div with Ajax. Is it possible to load a fully themed and rendered node (themed via page--node--1.tpl.php) with Ajax?

I have a custom module controlling my Ajax functions. From what I understand, the code below should be returning a fully themed node - but it is not doing so:

function ajax_reader_init() {
    drupal_add_js('misc/jquery.form.js');
    drupal_add_library('system','drupal.ajax');
}

/**
 * Implements hook_menu()
 */
function ajax_reader_menu() {
    $items['ajax-reader'] = array (
        'page callback' => 'ajax_link_response',
        'access callback' => 'user_access',
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

function ajax_link_response($type = 'ajax', $nid = 0) {
    $output = _ajax_reader_load_noder($nid);
    if ($type == 'ajax'){
        $commands = array();
        $commands[] = ajax_command_replace('.main', '
'.$output.'
');
        $page = array(
            '#type' => 'ajax',
            '#commands' => $commands
        );
        ajax_deliver($page);
    } else {
        $output = '
'.$output.'
';
        return $output;
    }
}

function _ajax_reader_load_noder($nid = 0) {
    $node = node_load($nid);
    if($node) {
        $vnode = node_view($nid);
        return theme("node", $vnode);
    }
}

There is a contributed module Ajaxify Drupal with JQuery Ajax available for this. You can load any pages, nodes or anything to a div by using ajax without loosing css and ajax behaviour of loading content.

  Ajax links API module help you to load any content to a specified DIV or ajaxify whole drupal site, using JQuery Ajax. This module will also load JS for Ajax-loaded content by using Drupal.attachBehaviors(). In case you dont want to load js or css, you can alter tpl for path/node type.


jQuery transition not run on anon page I am running Drupal 8.5.5 and am running into a problem. It seems for anonymous users jQuery is not loading a library that it would when I am logged in as admin. I tried to understand why that is but I am stumped. So far I disabled js caching, I have the following in my libraries.yml:

leadership:
   version: 1.x
   css:
     theme:
        css/leadership.css: {}
   js:
      js/leadership.js: {}
   dependencies:
      - core/jquery: {}

and it loads on the page, and runs this javascript which calls:

$content.toggleClass("whole-body", 800);

In the admin, I see the transitional effect of 800 seconds, but anonymous users don't see that.

I have figured it out, by just adding a bunch of jquery dependencies in my

  theme.libraries.yml

   js:
      js/leadership.js: {}
   dependencies:
    - core/jquery
    - core/jquery.once
    - core/jquery.ui
    - core/jquery.ui.widget
    - core/jquery.ui.draggable
    - core/jquery.ui.mouse
    - core/jquery.ui.position
    - core/jquery.ui.resizable

once of the jquery ui was missing.


Remove field-collection-view and field-collection-container fromt field output I am using the following modules:

Paragraphs
Field Collection

I am trying to Foundation 5 classes to re-create the zurb foundation orbit slider with unlimited slides. Initially my problem was limiting what seems to be unnecessary Drupal
 tags and classes so I could control the HTML output as much as possible. My workaround was simply installing Fences which gave me great results. I have the debugging turned on in the settings.php file to just make sure my naming conventions are correct and to make sure my code is outputting correctly. So far it is but with one slight problem.

So far I have spent days trying to nut out why the output of my field collection "field_add_image" is rendering a containing div of
, nested within that is another containing div which the field collection out is located. Each item is nested within another div tag like so
. This has an unlimited field which can be added to a paragraph item.

I went into the field collection module to identify where the classes to these containing div's were added which seem to be using the field_collection_field_formatter_view() which I found in the function within the module file.

I have installed Fences as well, which may be conflicting. the settings of Fences is set to:

Override the default wrapper markup with Fences lean markup (single
div wrapper)
Use Drupal's default classes" set as the default classes

All the fields are outputting the correct HTML output which is great, but for the life of me I cannot remove those two containing divs.

Here is the folder structure of the files I have copied from the systems folder within Drupal core and placed in templates folder. Below is the naming conventions I used with the machine names.

Theme name

jacob_d7_theme

Field collection name

field_add_image

Paragraph Bundle

paragraphs-item--scrolling_image.tpl.php code below

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

Fields in field_add_image

Banner Image: field_3_col_img1
Caption:  field_caption

Templates folder includes

Paragraphs

paragraphs-item--scrolling_image.tpl.php

All code in document

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

Fields

field--field_add_image.tpl.php
field--field_caption.tpl.php

Both of these field files have the same code in them to remove any unneccesary div containers for fields.

<?php foreach ($items as $delta => $item): ?>
<?php print render($item); ?>
<?php endforeach; ?>

I have also experimented with but with no avail.

field--field_add_image--scrolling_image.tpl.php
field--field-add-image--scrolling-image.tpl.php

I am not sure what I am missing as all the custom template files that I have made work they just keep getting contained by those two divs.

I managed to find the answer.

Through adding this function I replaced the containing
 with nothing "".

function jacob_d7_theme_field_attach_view_alter(&$output, $context) {

  // First check we're dealing with a field collection field.
  if(!empty($output['field_add_image'])) {
    // Now check for our specific field collection field.
    if ($output['field_add_image']['#field_name'] === 'field_add_image' ) {

      // Alter the prefix.
      $output['field_add_image']['#prefix'] = '';
    }
  }

}

then to remove the containing div for each field item I created a file called field-collection-view.tpl.php with only the following code. to remove the
.

<?php
  print $element['#children'];
?>


Which is the best form builder? I'm pretty unsure which form builder I should use (Webform, Form Builder etc.)

Which one are you using? Which one is still updated and so on? I want to build a form and edit entries and show them on a drupal site.

Webform responses are NOT content! Responses from the webform module cannot be placed into pages on your site; only administrator users can see results (or specific user roles). You can put answers into Views. (Maybe now that is possible.)

What you want to consider is either webform_entity or the EntityForms module. When to use 1 of these modules is talked about on this docs page. These 2 modules make responses into entity content you can place as content on your site.

Also, webform_entity or entity_forms responses are NOT Drupal nodes; they are custom entities. You cannot moderate their content with say the Workbench module. Good luck auditing submissions before they are made live on your site.


Address field module autofill city and state when zip code is entered In the United States, cities are split up by a unique 5 digit zip codes (postal code). This postal code in turn tells what city and state it is from. Therefore it is redundant to type the city and state.

Is there a way, with the Address Field module, to autofill the city and state if a postal code is submited?

This then leads to the second question, how to force a correct postal code entry. By default a user can type any text and it will be accepted.

Here is Javascript code that uses zipcodeapi.com API:

<script type="text/javascript">//<![CDATA[
$(function() {
    // IMPORTANT: Fill in your client key
    var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";

    var cache = {};
    var container = $("#example1");
    var errorDiv = container.find("div.text-error");

    /** Handle successful response */
    function handleResp(data)
    {
        // Check for error
        if (data.error_msg)
            errorDiv.text(data.error_msg);
        else if ("city" in data)
        {
            // Set city and state
            container.find("input[name='city']").val(data.city);
            container.find("input[name='state']").val(data.state);
        }
    }

    // Set up event handlers
    container.find("input[name='zipcode']").on("keyup change", function() {
        // Get zip code
        var zipcode = $(this).val().substring(0, 5);
        if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
        {
            // Clear error
            errorDiv.empty();

            // Check cache
            if (zipcode in cache)
            {
                handleResp(cache[zipcode]);
            }
            else
            {
                // Build url
                var url = "http://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";

                // Make AJAX request
                $.ajax({
                    "url": url,
                    "dataType": "json"
                }).done(function(data) {
                    handleResp(data);

                    // Store in cache
                    cache[zipcode] = data;
                }).fail(function(data) {
                    if (data.responseText && (json = $.parseJSON(data.responseText)))
                    {
                        // Store in cache
                        cache[zipcode] = json;

                        // Check for error
                        if (json.error_msg)
                            errorDiv.text(json.error_msg);
                    }
                    else
                        errorDiv.text('Request failed.');
                });
            }
        }
    }).trigger("change");
});

//]]>

You can see an example here - http://www.zipcodeapi.com/Examples#example1

Since the question is how to autofill a valid city and state based on the user entering a zipcode first, the above Javascript code does that. Click on the example above to see how it works.


How to get entity type from entity_metadata_wrapper I can use

$entity = entity_metadata_wrapper('node', 1);
$entity->getBundle();

to get the node type of an entity. However, entity-wrappers can wrap other types of entities, e.g. users. When calling getBundle() on a user entity, 'user' is returned. What should I call to return the type of entity (should return 'node' in the example above)? I can see when I print_r($entity) that $entity->type is a protected field of the wrapper object.

Hmmm, I seem to have found a way (unsure if this is the 'correct' way...)

$entity = entity_metadata_wrapper('node', 1);
$info = $entity->info();  // entity info as an array
$entity_type = $info['type']; // returns 'node' for node entities


Views REST Export and Multi-Value Fields I'm having trouble getting the Views REST export to work nicely with multi-value fields.
I have an image field that can have multiple images. I have added the field to my REST export View, however all values are being output on the same line. Like this:

[
    {
        "nid": "11",
        "image": "http://example.com/sites/default/files/2016-02/mobile-1.jpg\n,   http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
    }
]

What I would like to achieve is something like this:

[
   {
      "nid":"11",
      "image":{
         "0":"http://example.com/sites/default/files/2016-02/mobile-1.jpg\n",
         "1":"http://example.com/sites/default/files/2016-02/mobile-2.jpg\n"
      }
   }
]

Is this possible?
Perhaps using HOOK_views_pre_render() to change the returned value?

This looks like it's a plain bug. Please report it to the views.module issue queue in Drupal core: https://drupal.org/project/issues/drupal?component=views.module.


Custom 'required' field message ignored for file uploads File upload fields in the D8 Webform module don't show my custom 'required' message when they fail validation.

Here's the YAML source of a simple Webform:

cv:
  '#type': managed_file
  '#title': CV
  '#required': true
  '#required_error': 'Please upload a copy of your CV.'
  '#file_extensions': 'doc docx pdf odt rtf'
test_document:
  '#type': document_file
  '#title': 'Test document'
  '#required': true
  '#required_error': 'Custom missing document file message.'
  '#format_items': comma

Instead of Please upload a copy of your CV etc., I get the default:

  CV field is required.
  Test document field is required.

I've run drush webform:repair
I've tested this on an otherwise empty form.
I've also cleared Drupal's cache.

Site setup:

Drupal 8.5.4.
No custom code yet.
(edit: we've since established it's nothing to do with contrib modules)

The error message for managed_file fields is added by  ManagedFile::validateManagedFile - it does not support #required_error - the 'file missing' message (and others) are hardcoded:

  $form_state
      ->setError($element, t('@name field is required.', [
      '@name' => $element['#title'],
    ]));

This is presumably because of the multiple types of error possible:

file does not exist
file is "not referenced" (it exists but is "unmanaged" - i.e. orphaned as far as DB concerned - see function docs linked above)
or, in our case, a file has not been uploaded at all

Workaround:

I bypassed this by adding my own validation to the form.

The Webform module has hook_webform_submission_form_alter - you can use this to append your own validation method:

function mymodule_webform_submission_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ( $form['#webform_id'] != 'application' ) {
        // only do this for the specified form
        return;
    }

    $form['#validate'][] = 'mymodule_fix_webform_validation';
}

function mymodule_fix_webform_validation($form, &$form_state) {

    // grab all the existing errors
    $errors = $form_state->getErrors();

    if ( isset( $errors['cv'] ) &&
         $errors['cv']->getUntranslatedString() == '@name field is required.' ) {
         // if (a) there's an error for this field, and
         // (b) it's the correct TYPE of error

         // reconstruct the error message
         // (you might add translatable strings if you need them)
         $errors['cv']->__construct( 'Please upload a copy of your CV.' );
    }

}

(Decided to use the constructor from reading this answer to a similar question.)

Things I tried first:

The standard approach is to use $form_state->setError() or setErrorByName() - but neither appeared to have any effect on the error array - don't understand why.

On the actual form, the field was nested in a Webform "section"…

$form['elements']['uploads_section']['cv']

…so assumed I should supply the full array to setError(), for it to pull out the value of #parents and use that to construct the key.  Except the error is actually stored as a flat 'cv' key, without the parent.  Trying to set the 'cv' error using ByName didn't work either.

Overriding strings:

An alternative would be override the string (at time of writing, needs to be done programmatically: the string overrides module is not yet ready for D8). Add the following to settings.php:

$settings['locale_custom_strings_en'][''] = array(
    '@name field is required.' => 'Hello world!',
);

But this is a very broad brush and will apply to every file input on every form (plus anywhere else the phrase "@name field is required." is used - you can't specify the @name placeholder).


How are links rendered? In Drupal 8, what code determines if a link is output as text, or an anchor tag with text?

I have entered a route:<nolink> item in the menu, but the output is this:

<span target="" data-highlight="0" data-icon="" title="Description of wris." data-drupal-link-system-path="<front>">wris

Instead, I want an anchor tag with just # for the href.

Is there a reason why it only outputs a span? Where can I adjust this? Or, should I do this?

TL:DR; you need to overwrite the link_generator to change this behavior.
Drupal 8 uses the link generator for this. You can take a look at
Drupal\Core\Utility\LinkGenerator::generate if you want to know the code behind it all.
The key part is this:
elseif ($url->isRouted() && $url->getRouteName() === '<nolink>') {
  $generated_link = new GeneratedNoLink();
  unset($attributes['href']);
}

If you take a look at GeneratedNoLink you will see
/**
 * This class holds a <span> generated from the <nolink> route.
 */
class GeneratedNoLink extends GeneratedLink {

  /**
   * {@inheritdoc}
   */
  const TAG = 'span';

}

So you need to implement your own no link class and not unset the href and everything should be fine. Doing so you more or less need to copy most of the logic in Drupal\Core\Utility\LinkGenerator::generate to determine when no link should be used.
Note
Links/urls can be generated in various ways, some use link_generator, some use url_generator, some use the link RenderElement. In your case it looks like  the link_generator is used, but that could be changed by custom theme/module.


How to sanitize filename in D6? Is there a native function to sanitize filenames in Drupal 6?  Alternatively, does someone have a function they use that they'd like to share?

Well it depends on what you want to allow in your filenames.  There is a similar question here where you will find how to sanitize filenames in PHP.

From the above link, I had used following function to sanitize filenames in my one of the modules:

function mymodule_sanitize_string($string) {
    $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $string);
    $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace(array('~[^0-9a-z_-]~i', '~[ ]+~'), ' ', $string);

    return trim($string, ' -');
}

If you want to sanitize user input then Drupal has many input filtering functions  e.g. check_plain(), filter_xss(), check_url() etc. There is a good tutorial on Drupal security essentials here.


Exposed Taxonomy field in views filters I have a taxonomy field in my view in filters and I have made it exposed to the users with selection type "dropdown" along with "Show hierarchy in dropdown" as checked.

I'm also using Better Exposed Filters (BEF) module where in its settings I have selected the option to display the exposed filter as "nested checkboxes/radio buttons".

Also under more options in BEF's settings I have selected "Add nested all/none selection" so that if the parent taxonomy term is selected then all the child taxonomy terms should also get selected and vice versa. But this thing is not working properly, after selecting the parent term all the child terms are not getting selected neither after selecting all the child terms the parent term by default is getting selected.

Can anyone suggest ideas to make this work properly. Thanks In advance!!

Solved out with following jQuery code:-

$('.bef-tree input:checkbox').click(function() {
            var $this = $(this);
            if ($this.is(':checked')) {
            // Check all child checkboxes
            $this.closest('li').find('input:checkbox').prop('checked', true).change();

            // If all siblings are checked, the also check the parent term
                if ($this.closest('li').siblings('li').find('input:checkbox[checked="true"]').length
                == $this.closest('li').siblings('li').find('input:checkbox').length
                ) {
                    $this.closest('li').parent().closest('li').find('input:checkbox').prop('checked', true).change();
                }
            }
            else {
            // Uncheck all child checkboxes
                $this.closest('li').find('input:checkbox').prop('checked', false).change();

            // Uncheck all parent checkboxes of this element
                $this.parentsUntil('ul.bef-tree').filter('li').each(function() {
            // NOTE: "this" is no longer the closure variable, but the filtered
            //       li elements we selected and are iterating through.
                $(this).find('input:checkbox:first').prop('checked', false).change();
                });
            }
        });


Path alias creates redirect loop or redirects to the front page When I call our sit "www.example.com/contact-us" I'm getting the following error:

  Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

If I call the site with "www.example.com/node/5" the contact page is displayed just fine.

When I check the path alias on /admin/config/search/path/edit/6, system path and alias are set correctly.

Another problem exists for another alias, when I call "www.example.com/staff" I'm getting redirected to the landing page "www.example.com". Once again the alias is set correctly.

We're using Drupal 7, and the i18n_redirect and redirect modules.

Edit your page and go to URL redirects. Find the redirect path with the most number of count and delete it. Click save then view the page.

Let me know if that fixed your problem


How to remove "All Products" item in main menu of Commerce Kickstart 2? I checked vocabulary collection, no "All Products" there.

Is it created programmatically? How can I remove/change this item?

I don't know why I couldn't find it, But I got it in admin/structure/menu/manage/main-menu eventually. This question is a pseudo-question.


Using commerce module for online payment for just 4 product/services? I starting a website which is offering 4 Apartaments to rent. The visitor will be able to make online payments. My question: Should I use the  Drupal Commerce module for this ?

Will I be able to treat each Apartment as a product? I need to include a map and a calendar for each one. Can I accomplish this with the commerce module.

There is no much documentation about this module and it seems complicated....

If all you'd do was display the rooms and manage their bookings, then I would say
Commerce was not only excessive, but perhaps even entirely wrong.

However, since you mention online payments, I think it could be a good fit, for managing of those. No other contrib module is likely to have as many "out of the box" solutions for payment today, or developed tomorrow.


View to display the comments of the curent user nodes Please how to create a simple view to display the comments of the curent user nodes, only comments,
Thank you.

When you add a new view (/admin/structure/views/add), you have the possibility to select Comments.
It will list all comments.

Then you need to set a Contextual Filter and a Relation in order to get the comments of the current logged in user.


Comment permission by role and content type I have different roles (e.g. A, B, C) and I have different contents in a menu (e.g. A, B, C).

I want that only the user A can post/edit comments on content A,  and not on B and C.

So I don't know what module can help me with that.

What you looking for is Comment Permission module.
Some description of this module

  The Comment Permissions module enables control of commenting by user
  role and by node type. Additional user permissions for selected node
  types are added to the user access system so you can configure
  commenting with more control than Drupal core provides.


Is there a way for Forena to restrict the debugging messages to selected roles? The Forena data source has the option of displaying the generated queries on the screen via the Debug option.

The problem here is that the messages are displayed for all users or reports while this debug option is enabled, which is undesirable as it means a developer cannot be designing new queries during normal working hours.

Is there a way to restrict the debug messages to select roles only?

1. About the debug option

The debug option for a Forena data source is one of the options you enter when defining a data source. If enabled (value = TRUE), it'll actually trigger logic as shown in this logic:

  public static function debug($short_message='', $log='') {
    if ($log) {
      watchdog('forena debug', $log, NULL);
    }
    if ($short_message) {
      drupal_set_message(check_markup($short_message));
    }
  }

2. Restrict debugging messages to selected roles.

Defining the options for a data source (such as the debug option) can be done as described in the tutorial that comes with Forena (i.e. within the Data Sources Settings):

Defined using Forena's configuration data tab (within the admin UI).
Defined within settings.php files which allows for including PHP logic.
Defined by a module using a forena_alter_repos hook.

So the actual answer to your question depends on how you define the data source, as further detailed below.

a) Using Forena's configuration data tab (within the admin UI).

Using this option there is no way to answer your question, except if you would want to hack the logic shown above (which I do not recommend).

However by using the Disable Messages module you should be able to  restrict the debug messages to select roles only (though it'd still write the watchdog messages). Refer to "Option 1" in my answer to "How to show messages starting with "Debug : " to an administrator only?" for more details on that (not sure if "Option 2" of that answer would make sense in this case also).

b) Using a settings.php file

Include the desired PHP logic to assign a value (TRUE or FALSE) to $conf['debug']. Have a look at the repos/sample/settings.php file that comes with Forena for an example to start from.

c) Using a custom module

Using hook forena_alter_repos (documented within Available Hooks in the Development Guide).

3. Alternative solution

From your question, it seems that your developer is designing new queries (during normal business hours) in your production environment ... There must be good reasons to do (allow) that.

However, as an alternative, you could also define an additional data source that points to the same database, and for which you enable the debug option. If you combine this with "Access [data source] Data" (as described in Forena's Permissions) you could easily limit access to this data source to developers only. And after the data blocks (SQL queries) that they created are finish (approved), just MOVE the file containing that SQL query to the regular data source.

Disclosure: I'm a co-maintainer of Forena.


print html entities in link drupal l('Visit Website &raquo;', 'http://' . $site->purl_prefix . '.' . $base)

I have a link I want to print like this the » is not getting parse properly it is still showing up as the character code in the link.

Just pass html => TRUE as an option:

$options = array('html' => TRUE);
l('Visit Website &raquo;', 'http://' . $site->purl_prefix . '.' . $base, $options);

From the docs:

  'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.


How to compare current year with an integer field in Rules? I would like to compare the current year with an integer field (let's say a "year of subscription" field) using Rules (if the field value is lower than the current year, the user has no access to a specific action on the website).

I have tried many different things, data comparison, text comparison, PHP custom etc. but I did not manage to create this "apparently" simple condition.

I guess I am missing something (a date/time comparison somewhere? the right PHP code to extract the year of the current date? echo date('YY')? strtotime? mktime?).

Could anyone help me?
Thanks in advance.

Add the rule as follows:

Event

Your event
Conditions:

a. Entity has field

-> Data Selector = node

-> Field Value = your date field (mine is field_bp_year)

b. Execute custom PHP code

-> Value =

return intval([node:field-bp-year]) < intval(date("Y"));

where you add the replacement pattern for your date field (mine was field-bp-year)
Actions:

Your action

NOTE: I treated my year as four digits. If you only want 2 digits then use date("y").


How can I display a WebForm in a Modal Window I am using Webform (4.11).  I have a 'simple' form with 2 fields that I would like to display in a modal dialog when the 'Apply' button is pressed.

So imagine I have a page with an apply button, and when the user selects this button, I need to know if they are an existing client (they are not logged in), and some other 'meta data' (second field).

Bottom line - I would just like to display the webform that has these questions, in a modal dialog.

I know I can create a custom module, to create a custom form, and use CTools to show the form in a modal window, but then I lose all the functionality that comes with the Webform module.

Use modal form module to load into modal window. Create link using modules custom method after check user is loggedin.

$links[] = ctools_modal_text_button(t('webform'), 'modal_forms/nojs/webform-path', t('Webform via modal'),  'ctools-modal-modal-popup-small');


Adding geo location content to node I'm looking for a maintained module that allows to add a geo location to a node of a custom content type. I am looking for something that has integration with Google Map API so that it's possible to query the location using an address, ZIP, or name.

If your are using drupal 7, then my favorite option is openlayers with address field and geofield.

The advantage of openlayers is that you are not tight to one particular map provider, but you can switch just by changing your options.

You can set geofield to take the value of the address field, geocode it and store the lon/lat value of the address. You can then draw the locations on the map.
The geofield works with google or yahoo for geocoding.


How to add a menu tab programmatically to a views page? I have a view page showing fields of an entity. The pages URL set in Views is

entity/%

Now I would like to add some tabs to this views pages that I can't generate with views it self, but have to do it programmatically. Si I tried:

function MY_MOODULE_menu() {
  $items['entity/%eid/edit'] = array(
    'title' => 'Edit',
    'page callback'   => 'MY_MODULE_entity_edit_callback',
    'access callback' => true,
    'page arguments' => array('eid'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );
  return $items;
}

As a menu of the type is MENU_NORMAL_ITEM with the base path entity/% is created by the mentioned view, I thought this should simply work, but it does not: The tab does not show up. (Of course I cleared all caches). Did I got something wrong?

Path hierarchy is based on string matching; so entity/%eid/edit doesn't come under entity/% (because '%' != '%eid')

There are a couple of other issues, reading between the lines I reckon this is what you're going for:

function MY_MOODULE_menu() {
  $items['entity/%/edit'] = array(
    'title' => 'Edit',
    'page callback'   => 'MY_MODULE_entity_edit_callback',
    'access callback' => true,
    'page arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 100,
  );
  return $items;
}

function MY_MODULE_entity_edit_callback($eid) {
  // ...
}


Domain and URL variables I have inherited some bad code in a Drupal 7.x site and it needs to be cleaned up.  Several places in the code the URL is hard-coded and I want to change that.  For example, in many of my javascript (.js) files I have something like this:

var url= 'http://dev3.ws.mysite.com/index.php/api/alerts_mix/x-api-key/blahhhhhhhhhzBkfqPTq4SWuCiLONePNfschNft';

In the PHP code I have the following:

     $url="http://dev3.ws.mysite.com/api/checkin/x-api-key/blahhhhhhhhhuRCMIWM0Nw0rM2cDK7tTJTPW?uid=11&lt="

First question...is it OK to have the entire URL for the API (including the key) hard-coded or should we be calling this some other way?

Second...for both the js and PHP, what can I use in place of the HTTP and domain (http://dev3.ws.mysite.com) so it is a variable and gets those values from the config files so I don't need to change this every time when making a new dev site?

For configuration, like an API server URL, I'd suggest using Drupal variables. There are several ways to set the variable:

In the settings.php:

$conf['api_server'] = 'http://example.com';

With Drush:

drush vset api_server 'http://example.com'

Build an admin screen where you can set the value. (Probably overkill in this case.)

In your code where you need the URL, use variable_get():

$url = variable_get('api_server');

To access the value in JavaScript see: How to pass PHP variables to Javascript/jQuery?


What is the difference between Microdata or Schema.org (or can I use both)? I am building a community site in Drupal 7.

I am using the SEO checklist, which suggest to use the microdata module.

Other places I read are suggesting to use Schema.org module.

what is difference between them? Can I use both modules?

They are different things:

Microdata is a syntax.
Schema.org is a vocabulary.

If you want to use the Schema.org vocabulary, you can use the syntax Microdata, or RDFa (Lite), or JSON-LD (or any other RDF serialization, but the three mentioned syntaxes are supported by the big search engines that sponsor Schema.org).

The schemaorg module integrates the Schema.org vocabulary into Drupal 7 by using RDFa 1.0, which is the syntax used by Drupal 7 for other vocabularies, too.

The microdata integrates the Schema.org vocabulary by using Microdata (without this module, Drupal 7 does not output any Microdata).

If you can’t decide between these two modules: Go with schemaorg, because Drupal 7 already uses RDFa, RDFa is more powerful than Microdata, and parts of this module were ported into the Drupal 8 core.


General error: 1366 Incorrect integer value while uploading image I am using Drupal 7 and I got the following error while uploading an image.
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'field_third_section_image_width' at row 1:
INSERT INTO {field_data_field_third_section_image} (entity_type, entity_id, revision_id, bundle, delta, language, field_third_section_image_fid, field_third_section_image_alt, field_third_section_image_title, field_third_section_image_width,
field_third_section_image_height) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4,
 :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7,
 :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10);
     Array ( [:db_insert_placeholder_0] => node
    [:db_insert_placeholder_1] => 107
    [:db_insert_placeholder_2] => 107
    [:db_insert_placeholder_3] => page
    [:db_insert_placeholder_4] => 0
    [:db_insert_placeholder_5] => und
    [:db_insert_placeholder_6] => 12464
    [:db_insert_placeholder_7] =>
    [:db_insert_placeholder_8] =>
    [:db_insert_placeholder_9] =>
    [:db_insert_placeholder_10] => )

    in field_sql_storage_field_storage_write() (line 514 of /mysite/modules/field/modules/field_sql_storage/field_sql_storage.module).

Its also give some image related error on recent logs
Unable to generate the derived image located at public://styles/thumbnail/public/imac1.png.
Whenever I trying to upload the image and save the node then it gives the following error.
I have already given the writable permission to files directory and tmp directory.
Any Idea?

You don't have any values for these columns in the SQL query: field_third_section_image_alt, field_third_section_image_title, field_third_section_image_width,
field_third_section_image_height
So there must have something for these fields in order for the query to work. Have a look at the code and see why they are not set.


How to filter for a Field Collection in a View I have a View of Field Collection fields. The Field Collection is composed of field 1and field 2. The Field Collection is associated, as a single field, to a content type. If I filter the View by a combination of values for field 1 and field 2, and I have established a relationship with the associated content type, I can filter combinations of values, which come as 2-tuples; for example: Music and Great Britain, Sports and USA, etc.

However, if the View is a view of the content type, of the nodes, I don't know how to group filters in such a way that I can look for the specific combinations above. If I put two filters, and search by Music and USA, I will retrieve results even if the correct value is the 2-tuple Music and Great Britain. The view filters in ALL the Field Collections instead of just looking in one each time.

How can achieve the result with a View of content (products)? Or the way is to do it with the Field Collections, as I have done?

I answered over in How to filter groups of paired values in Views which appears to be essentially the same question.


Blank row when adding field collection item I have a Content Type with a Field Collection that can have multiple entries.
Whenever i click on "insert new element" i get instead a blank row with a "delete" button but no fields to fill. (site is in italian, Elimina means "Delete" and "Aggiungi un altro elemento" is the "add new item" button)

Things worth mentioning:
1) This happens when i'm in the frontend template (the node can be edited by anonymous users) but not when i'm in the administration pages, it works fine there
2) This field collection has some special fields: 1 Simple Hierarchical select, 2 computed fields and 1 Geofield. Apart from the SHS field the other fields are not editable by users (and even if they were, those fields are automatically generated so there won't be a widget)
I have tried to change the SHS widget with other widgets but it didn't work.
3) There are other field collections in this content type and adding a new item there works fine and shows me the form
4) I have checked through Firebug the json returned by the ajax call used to add a new item and it contains the HTML for the new form, but it looks like it's not appended to the page
5) Another thing that may be an issue is that on the frontend i'm using jquery 1.9 while in the administration pages i'm using jquery 1.7 (the site uses a bootstrap template) and i have noticed that in the ajax response it says jquery_version: 1.7, but this won't explain why other fields work.
6) i have tried changing the fields order putting the fields that work over this one  but that didn't work either. Those field collections that worked kept working and this one that doesn't work was still not working

At first i thought it was a javascript problem or something like that but as Geoff pointed out it was a permissions problem:

The permissions on the field collection itself were public, the permissions on the fields inside allowed anonymous users to edit existing items but not create new values for those fields so that gave me an empty form when creating a new item of that field collection.


How do you customise the Group subscription format I have assigned user profiles the field Group Type and set it to default as "is group type" so that users can subscribe to each others profiles. This is all fine but i would like to customise the link that allows the users to subscribe, i.e. the display format 'Group subscription'. It currently says: "Subscribe to group", "Unsubscribe from group" or "You are the group manager". Is it possible to customise this text?

You can make use of the string override module

  Provides a quick and easy way to replace any text on the site.


Adaptive theme css which stylesheet to use? In the adaptive theme in the sass folder and it has following files, I understand about some stylesheets and for what purpose they are. But I am confuse about global.base.scss, global.style.scss, responsive.desktop.scss, responsive.custom.scss and print.scss. Now which one shall I use specific purpose.

e.g. global.base.scss and global.style.scss, both has html and body now if we want to use font-size: 62.5% in root for using rem as unit so in which html shall I have to put?

The AdaptiveTheme site has a lot of great documentation to help explain this.

In general, you should use global.styles.scss to style elements that will look the same across all devices, and the individual responsive stylesheets (e.g. responsive.desktop.scss) for device-specific styles. If you want to override something in global.base.scss, you're probably best off doing it in global.styles.scss, depending on how fundamental the change is.


How to change URL alias when importing books? I am importing some books and would like the url to reflect the category name i.e. sample.com/fishing-books/booktitle where fishing-books is the product category.

There is a field on the URL alias page (patterns): Default path pattern (which applies to all content types with blank patterns below) which I'm trying to make it work, but I haven't been successful. I want something like [cat]/[node:title], but it doesn't work.

Have you created a vocabulary for these books?

If not:

Create a vocabulary, e.g. "books_category"
Add to your content type field, e.g. "books_category" (field type: Term reference), choosing the vocabulary you previously created as reference

After that, click at replacement patterns (admin/config/search/path/patterns); choose group "Tokens related to individual content items," or "nodes"; you will find a group of patterns related to your "books_category" field.

I assume you installed the Pathauto module.


Does the LDAP module encrypt directory queries? I'm using the LDAP module and do not have the Start-TLS box checked. Does this mean my directory queries are running over an insecure connection? Or are queries to the directory server always ran over SSL/TLS?

As configured in your screenshot -- yes your queries are running in plaintext over the wire. This is similar to running MySQL on the default port and not running MySQL connections under SSL (which is also possible by sharing certs).

Securing network connections between Drupal and LDAP is dependant on your LDAP vendor. For instance your LDAP vendor may support ldaps:// (ldap using SSL) connection strings to connect to your server and a secure port (such as 636) and not require Start-TLS.

For some gritty details see details from the Open LDAP FAQ:
http://www.openldap.org/faq/data/cache/605.html

  The StartTLS extended operation [RFC 2830] is LDAPv3's standard
  mechanism for enabling TLS (SSL) data confidentiality protection. The
  mechanism uses an LDAPv3 extended operation to establish an encrypted
  SSL/TLS connection within an already established LDAP connection.
  While the mechanism is designed for use with TLSv1, most
  implementations will fallback to SSLv3 (and SSLv2) if necessary.

  ldaps:// is a mechanism for establishing an encrypted SSL/TLS
  connection for LDAP. It requires use of separate port, commonly 636.
  Though originally designed for use with LDAPv2 and SSLv2, many
  implementations support its use with LDAPv3 and TLSv1. Although there
  is no technical specification for ldaps:// it is widely used.

  ldaps:// is deprecated in favor of Start TLS [RFC2830]. OpenLDAP 2.0
  supports both.

  For security reasons the server should be configured
  not to accept SSLv2.

For example at my job they say to use ldaps:// and a secure port when connecting to our LDAP server. They say not to use start-tls. The configuration depends on your LDAP vendor and the version of LDAP you're using.


URL to access a private file within Drupal 7 I want to be able to have my Drupal 7 site allow both public and private downloads (see below configuration screen shot).

It appears that the private directory at: sites/default/files/private is preventing direct access to the files which is what I want and is allowing direct public access to the files within: sites/default/files which is also what I want.

My question is what URL do I use to call the private files so that my function hook_file_download($url) it called and then can decide based on a combination of the directory within the /private directory and the requesting users role whether they have access to view this file?

The function you want to use is file_create_url().

You pass a stream wrapper path to your file, in this case it starts with 'private://'.

The value that you pass to the function is 'private://relative/path/to/file.txt'.

The relative path is based on the private files folder.


Issue with Contextual Filters I have a pretty particular issue that I'm running into with setting up an Administration View using Contextual Filters.

I've set up a view to handle /admin/content.

Basically, what I would like is for users in a particular role to see the content that they are authors of, and one specific other content type, for which nodes are submitted by anonymous users through a webform.

So, to recap, users in this role need to see:

Nodes that they are the author of
Nodes submitted by anonymous users, of a specific content type

Any thoughts?

You shouldn't need contextual filters for this as nothing needs to be passed in via the URL.

It should work like this using regular filters:

Create a node view
Add a relationship for "Content: Author"
Add a filter for "Content: Type" and restrict to the specific content type you refer to.
Add a filter for "User: Current" and set it to "Yes".  This will be using the relationship you defined in step 2.
Click the drop down next to the filter criteria heading and click "And/Or, Rearrange".
Change the operator for your 2 filters to "Or". Then you will see on the right it says current user or content type. Then click apply. - Note that if you have other filters set you may have to click the "Create new filter group" button then add these 2 filters to the new group then use "Or" within that group and "And" for the rest.


hook_menu access argument returns 3 instead of data I am trying to access an api that I wrote, with an access that is limited to administrators only.

My code is:

mymodule_menu() {
/**
 * Create api callback to return list of users in a give site
*/
  $items['api/v1/userslist'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'mymodule_api_userslist',
    'access arguments' => array('administer permissions'),
    'delivery callback' => 'mymodule_json',
  );

  return $items;

this just return the value "3" for no reason.

If I remove access argument and put         'access callback'   => TRUE,
everything is working. So it is a problem with the permission.

Any ideas?

function mymodule_json($data) {
  if (isset($data['error'])) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}

Your delivery callback is not right. The default delivery callback is drupal_deliver_html_page($page_callback_result).

From that page:

  $page_callback_result: The result of a page callback. Can be one of:

  NULL: to indicate no content.
  An integer menu status constant: to indicate an error condition.
  A string of HTML content.
  A renderable array of content.

So there is no such thing as $data['error']. You are probably encoding the error code 3.

In the default callback they catch integers as errors:

// Menu status constants are integers; page content is a string or array.
if (is_int($page_callback_result)) {
  ...
}

You might want to do the same:

function mymodule_json($data) {
  if (is_int($data)) {
    drupal_add_http_header('Status', '400 Bad Request');
  }

  echo drupal_json_output($data);
}


Is Sweaver module compatible with Domain Access module? I'm configuring a Domain Access website and having some issues on making Sweaver module working as it suppose to be. I see that Sweaver back end is configurable based on domain. What about the switch theme feature? Is there any known compatibility issue between these two modules?

It doesn't work because it saves all the data files in the same place and all the sites will have your same changes. The admin settings maybe able to be changed based on the domain but code that controls your CSS changes doesn't change based on the current domain.

This is with Drupal 6.


How to get Node Title and description when nid is avaiable? In Drupal 7 I am using following code in Global: PHP.

$data = message_load($row->mid);

if (isset($data->field_related_flag)){
  $fid = $data->field_related_flag['und'][0]['target_id'];
  $ftype = $data->field_flagged_node_type['und'][0]['value'];
  $flag = db_query('SELECT f.entity_id content_id, f.fid flag_id, flag.title type FROM flagging f INNER JOIN flag ON flag.fid = f.fid WHERE flagging_id = :val_fid', array(':val_fid' => $fid))-> fetchAssoc();
  $flag['content_type'] = $ftype;
  return json_encode($flag);
}

And from this code, I get the following output:

'related_flag' => '{"content_id":"410","flag_id":"1","type":"like","content_type":"event"}',

Here "content_id":"410" is the node ID.

Now I need to get the node title, description, and other fields. Can anyone please tell me what code I should write to get the desired result?

You can easily load the node using $node = node_load($nid);

Hoever it can be a bit tricky to get the values you want, so I recommend Entity metadata wrappers. They are part of the Entity API module and they allow you to access node variables like this:

$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->title->value();
$node_wrapper->field_description->value();

At the bottom of the linked Entity metadata wrapper page is a section on Debugging or introspecting wrappers, you can use that to find all available fields and their names.


Accesslog functionality? Accesslog was removed from the Statistics module in Drupal 8: https://www.drupal.org/node/1446956. Does this functionality now exist somewhere else in core?

As reported in Accesslog removed from the Statistics module, the module with that functionality is the Better Statistics module, which (at the moment I am writing this answer) doesn't have a Drupal 8 version.

  The accesslog and all associated reports have been removed from the core Statistics module. This functionality exists in contrib at http://drupal.org/project/better_statistics.

There is a issue open for porting the module to Drupal 8, Port Better Statistics to Drupal 8, which was created after the change record.

The History module in Drupal core doesn't keep a log for the access to all the pages, but it keeps a log for the access to nodes. If you are interesting just to the users who accessed a node, that could help you.


Export JSON sitemap of views I have a Drupal 8 site that is using a bunch of custom views with REST endpoints. These views contain a bunch of content nodes on them which make up a single page.

I have been able to generate an XML sitemap of the views by using Simple XML Sitemap module but I am wanting to know if (and how) it's possible to generate a JSON sitemap of all the views and the paths that are associated with REST but dynamically?

Create a simple custom REST resource in a custom module and within the resource you can return a list of views and other relevant information

Here is a get() function that returns views that are enabled and their displays

/**
 * Responds to entity GET requests.
 * @return \Drupal\rest\ResourceResponse
 */
public function get() {

    $entity_ids = \Drupal::service('entity.query')
        ->get('view')
        ->condition('status', TRUE)
        ->execute();

    $views = [];
    foreach (\Drupal::entityManager()
        ->getStorage('view')
        ->loadMultiple($entity_ids) as $view) {

        $displays = [];
        // Check each display to see if it meets the criteria and is enabled.
        foreach ($view->get('display') as $id => $display) {

            // If the key doesn't exist, enabled is assumed.
            $enabled = !empty($display['display_options']['enabled']) || !array_key_exists('enabled', $display['display_options']);
            if ($enabled ) {
                $displays[] = [
                    'id' => $display['id'],
                ];
            }
        }
        $views[] = [
            'view_id' => $view->id(),
            'displays' => $displays,
        ];
    }

    $response = new ResourceResponse($views);
    return $response;
}

You can modify the views array using the for loops to display any information that you find relevant to your task.

Here is a working demo module that I did for the sake of this exercise


Subtheme install settings in config but not showing In a brand new site installation, I created a subtheme of the Bootstrap theme. In the subtheme (let's call "mytheme") config/install/mytheme.settings.yml file, I have the following settings.

settings:
  navbar_position: 'fixed-top'
  onelab_footer_type: Fat
  cdn_provider: custom
  cdn_custom_css: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css'
  cdn_custom_css_min: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
  cdn_custom_js: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js'
  cdn_custom_js_min: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'

I have verified that the database config table shows these settings. However, these settings are not getting applied. I have cleared the cache and that doesn't seem to do anything either. So, if they are correctly in the config table, how do I get Drupal to apply them?

Although the documentation shows to place the settings under the "settings" key, I was then told to put it at the top level without the settings key. That is working.


How can I create a display in views with different filter criteria Can I have a view with different displays? I.e. I would like to have the same display twice but in the second one, I just want to have an additional filter criteria. How can I do this?

edit 1

I cloned my initial display and added a new filter to the new one. I selected "This page (override)" and selected "Content: Title (contains Brunch)" but, I hit save but it doesn't seem to apply the filter:http://www.quaaoutlodge.com/restaurant-specials (new display) vs.
http://www.quaaoutlodge.com/special-events (generic display)
Why is this, what did I do wrong?
The query looks correct:

SELECT node.nid AS nid, node.title AS node_title, 'node' AS field_data_field_eventdate_node_entity_type, 'node' AS field_data_field_table_description_node_entity_type, 'node' AS field_data_field_link_to_page_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_eventdate} field_data_field_eventdate ON node.nid = field_data_field_eventdate.entity_id AND (field_data_field_eventdate.entity_type = 'node' AND field_data_field_eventdate.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN  ('event')) AND (node.title LIKE '%Brunch%' ESCAPE '\\') ))
ORDER BY field_data_field_eventdate.field_eventdate_value ASC

but doesn't seem to get applied...for the new display - and yes, I hot "save"!

edit 2

It seems like the "This page (override)" feature doesn't work properly, I changed the title of my restaurant display and it doesn't geta pplied either.. any idea what I might be doing wrong?

You can clone your first display. In your second display you can add additional filters. Be sure when you add filters to choose to override from the dropdown menu, located at the top-left of your filter modal. This way, the additional filters are applied only to your second display.


Import your own interface translations automatically during profile or module installation I have been trying to import my custom interface translation during profile installation using a .po file that is put inside the translations folder in my custom module. After running:

  drush locale-update && drush cr

All I get is community translations which are not accurate sometimes (no translation is imported from my .po file).

How can I import translations only from my local .po file?

Thank you.

To import your own translations you should use the interface translation properties on your module.

I'm using a folder translations in my modules where my language files like de.po or fr.po can be found. To load the translations you have to insert the following lines into your example_module.info.yml:

'interface translation project': example_module
'interface translation server pattern': modules/custom/example_module/translations/%language.po

And to update your translations use this:

drush locale-check && drush locale-update && drush cr

EDIT:
To update existent translations you should take a look at the settings page (/admin/config/regional/translate/settings):

You can try to use local translation files only or to overwrite any existing translation.


How to re-publish nodes after unpublishing with hook_cron? Good morning,

I'm running some tests with hook_cron in Drupal 8. My goal is to unpublish nodes of a specific content type ('event'), and once I enabled my module, I was able to accomplish this. However, after setting $node->setPublished to 'true,' I was unable to accomplish publishing said nodes again after running cron, running Drush CR, and restarting Apache.

Anyone know of any good hooks to resolve this?

function scheduler_publish_cron() {
  $nids = \Drupal::entityQuery("node")
    ->condition('type', 'event')
    ->execute();
$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$nodes = $storage_handler->loadMultiple($nids);
foreach ($nodes as $node) {
// Unpublish nodes
// $node->setPublished(false);
 // Publish nodes
$node->setPublished(true);
    $node->save();
  }
}

Try to disable access checking in the second run, because after unpublishing the node you might no longer have access to them (depending on the user account the code runs with):

$nids = \Drupal::entityQuery('node')
  ->condition('type', 'event')
  ->accessCheck(FALSE)
  ->execute();


How do I programmatically render a custom entity? I created a custom entity (submenu) in Drupal 8. I need to render this custom entity in my custom module. This is the code I am using.

$entity_type = 'submenu';
$entity_id = '1'; // static for example purpose
$view_mode = 'full';

$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
$view_builder = \Drupal::entityTypeManager()->getViewBuilder('submenu');
$pre_render = $view_builder->view($entity, $view_mode);
$render_output = render($pre_render);

I keep getting the following error.

  TypeError: Argument 1 passed to Drupal\Core\Entity\EntityViewBuilder::view() must implement interface Drupal\Core\Entity\EntityInterface, null given

Why do I get this error?

Make sure the entity id exists and the error disappears.


Is there a way to log changes to module settings for better long-term administration and debugging? We run quite a complicated Drupal 6 site with a lot of custom modules which was already migrated from D5. There are a few site administrators and we have had situations where a change in the settings of one module (usually something conflicting with Boost) has caused a problem with the site that is only detected later. We have no way to quickly tell which settings have been changed recently and what their previous values were.

Is there an additional module that hooks into to all variable_set() calls (for example) and logs the old and new values so that we can have an admin view listing all changes over time and which user made the change? It would be great to have an option to add a note to each item to explain why the change was made?

We try and share notes in our wiki on such changes but I think it would be much better if such data was available from inside Drupal itself.

Here is our workflow.

First of all you code base should use a versioning system as Git or Subversion, doesn't matter which you like or want use, but the main point its to use a versioning system.

Then you should give a look to Features module and all his modules relatives. This will allow you to create a set of module that include standard configuration and etc.

So, mostly popular modules are using either variables or ctools to manage their configuration, for those who sue CTools, Featues will help you export their configuration, for the others you've Strongarm.

I think just with this, you will covers at least 80% of your configuration, for the rest your should either move it to features or use hook_update_N with a module.

Here what is important its that all your configuration must be inside files and committed to the versioning system.

Like that, you will which configuration has been changed and see the historic through the versioning system.

I think the most important part its to move the already existing into Features and force people to use Features when they are doing changes in the configuration.


How do I set a variable in the install profile to enable users to sign up for the website I am trying to understand about how setting variables works in install profiles. As an example, how would I set the option to enable people to create a website for the account in the install profile? Here is the page on variable_set https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable_set but how do I retrieve the value.

Variables in install profiles work no differently to variables in a 'normal' bootstrap.

To set a variable use variable_set():

variable_set('var_name', 'value');

To retrieve it, use variable_get():

$var = variable_get('var_name', 'default');

To find the names of variables, the easiest method is to install the Devel module and visit the variable editor at /devel/variable


How to clear page cache without rebuilding other caches I have a large site which uses Drupal cores 'page caching for anonymous users'.  I have made some javascript changes which I need to deploy.  Since pages are currently cached I will need to clear the page cache.

I am wondering if there is a way of only clearing the page cache?  If possible I don't want to have to rebuild any other caches (e.g. menu).

I know Drush provides a certain level of granularity when it comes to caching; however, it would appear that Drush is not capable of only clearing the page cache

$ drush cc

Enter a number to choose which cache to clear.
 [0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  registry
 [10]  :  metatag
 [11]  :  token
 [12]  :  views

You can use Flush Page Cache or Cache Actions module.
See if either of them solves your problem.
Flush Page Cache:

Easing the pain when you need to flush...Drupal's cache.
Flushing Drupal's cache on a large site can feel like you're waiting to takeoff on the tarmac at JFK. The delay comes from the fact that when you clear Drupal's cache, it clears everything. Most of time you just want to flush the cache for specific object on a page.
The Flush page cache module solves this problem by flushing only the cached objects for a single page. Additionally, you can define custom objects and cache tables to be cleared on specific pages.

Cache Actions:

Cache actions provides rules actions for clearing drupal caches.
It currently provides actions for:

Clearing Drupal cache bins
Clearing CSS/JS cache
Clearing The cache of specific views
Clearing The cache of specific panel pages
Clearing The cache of specific mini panels


Mismatched entity and/or field definitions for comment field I have been receiving this message

  ENTITY/FIELD DEFINITIONS Mismatched entity and/or field definitions
  The following changes were detected in the entity type and field
  definitions. Comment The Entity type field needs to be updated. The
  Comment field name field needs to be updated.

I have tried quite a lot of things including running entup (apparently depreciated) and adding some lines on entity update to index.php. Nothing has worked, I don't really use comments on my site, but would like to resolve it, any ideas?

drush entity-updates (aka drush entup) has been deprecated as of Drupal 8.7.0. You either need to write an update script using hook_update_N(), or you can use the Devel Entity Updates module, which does the same thing as drush entup did previous to 8.7.0.


Drupal for a portfolio- Images as nodes or something else? I am creating a portfolio using Drupal. I was wondering about best practice for handling images.
Would it be best for me to have each image as a node and then create a view and display in a slideshow, or is there a different way that images can be handled - e.g. have a collection of images attached to a node of 'gallery'?

I'd go with the image-per-node option if you think you may at any point want to add additional information per image.  You can call the content type 'Project' or something like that and put an image field on the content type.  You can have an 'unlimited' checked as the number of images allowed in that field or only allow for a single sample image.  Up to you.

The point is - imagine that down the road you want to add extra information about that particular screenshot/project, such as the date you worked on it, or who your client was, or a link to the live site or something like that.  If you make a separate node for each project, you have the flexibility to add fields in the future.

If your entire portfolio is a single node with a bunch of images, you don't have the option to add extra information to explain those images later without re-doing the entire setup.

You can always just display them as a slideshow with no extra information, regardless of which option you choose, but I'd go with the one that allows for flexibility in the long term.  :-)


Wrapping embedded images with a div When embedding an image in CKEditor on Drupal 7 any styles or alignment are applied directly to the image itself e.g.

However this doesn't allow for a great deal of CSS control over the appearance for the image because the inline styles override CSS.

How can I do the following 2 things:

Automatically wrap the image in a div and apply classes to this instead of the img element
For alignment use classes (e.g. 'image-left', 'image-right' etc.) instead of inline styles

So the above example would instead be rendered as:

Instead of adding a wrapper div, you could use !important.

img {
    float: left !important;
    height: 150px !important;
    width: 90px !important;
}

This would override the style added in CKEDITOR. You could do the same for alignment using classes, adding them directly to the image through CKEDITOR.


hook_entity_field_access - trying to check if there's a value I am trying to check if a given FieldItemListInterface is empty or not (and if not, grab the entity)

Using the example in https://www.drupal.org/project/examples - the team I'm on was able to get an access function written that should theoretically work only if there are items with an entity in them.

However whenever we have the correct field definition name, and check for items, they're all empty:

if ($items) {
// Code does not execute here - $items value is always NULL.
}

I'm not quite sure why but for some reason the value is always NULL, even if I would think it should be full.

Why exactly would this value be NULL if the field definition exists on a given entity, and has a value?

What am I missing?

Further code example:

function MY_MODULE_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {

if ($field_definition->getName() != 'field_attendee_only_content') {
    return AccessResult::neutral();
  }

// Code gets to here.

  if ($items) {
// Code here is never executed. $items is ALWAYS NULL.
    $entity = $items->getEntity();
  }
}

For additional information, the field in question is a file field.

In the documentation for EntityAccessControlHandler::fieldAccess(), the method that invokes the hook you are implementing, $items is defined as follows.

  \Drupal\Core\Field\FieldItemListInterface $items: (optional) The field values for which to check access, or NULL if access is checked for the field definition, without any specific value available. Defaults to NULL.

This could also happen if the entity containing the field is being created, and not modified. That is the reason why Drupal core implementations of that hook always check the value of $items before using it.

  // language_entity_field_access()
  // Only allow edit access on a langcode field if the entity it is attached to
  // is configured to have an alterable language. Also without items we can not
  // decide whether or not to allow access.
  if ($items && $operation == 'edit') {
    // Omissis.
  }

  // views_entity_test_entity_field_access()
  if ($field_definition->getName() == 'test_text_access') {
    if ($items) {
      if ($items->value == 'no access value') {
        return AccessResult::forbidden()->addCacheableDependency($items->getEntity());
      }
    }
  }


How do I get rid of "Body:" as highlighted bellow? what can be done to get rid of highlighted section from the top of content?

Login as Administrator
Go to admin/structure/types
Click on Manage Fields next to above content content type..

Click on Mange Display
Hide Body label like shown below..


Notify Module Truncate Eroor I received an error from the Notify Module when attempting to "truncate" the queue.

The error was:

Warning: Invalid argument supplied for foreach() in notify_admin_queue_submit() (line 956 of /var/www/html/sites/all/modules/notify/notify.module).

Essentially, the queue was not cleared because of this.

Any ideas?

After hunting through notify.module, I saw what the issue was.

The line that the error was occuring at was:

foreach ($res_nopub as $row) {
  db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
}

The array $res_nopub is constructed by the function _notify_select_content by:

// Get published nodes in unpublished queue
$res_nopub = db_query('SELECT q.nid
FROM {notify_unpublished_queue} q
INNER JOIN {node} n
ON q.nid = n.nid
WHERE q.cid = :cid AND n.status = :status
ORDER BY q.nid asc',
array(':cid' => 0, ':status' => NODE_PUBLISHED));

The issue that occurred was that the only node within the queue of notifications was an unpublished page. There were no published pages within the unpublished table, and the unpublished table was not empty. Because of this, the array $res_nopub is constructed, but is empty. This throws an error at line 956 due to attempting to iterate over an empty array with a for each.

I fixed this error by first checking the length of the array at line 956 before iterating.

if (sizeof($res_nopub) > 0)//check size of array before iterating
{
    foreach ($res_nopub as $row) {
      db_query('DELETE FROM {notify_unpublished_queue} WHERE cid = :cid AND nid = :nid', array(':cid' => 0, ':nid' => $row->nid));
    }
}

I've tested this very simple fix and yes, it does work.


How to tell what filename to select when using twig debugging in drupal 8 theming this is my second week with drupal 8 (or drupal in general). I want to be a drupal developer and contributer to the modules and themes community. However, I am a little lost with the file name suggestions shown in this image.

When reading books and tutorials, i see the author suggesting we use one of the filename suggestions shown, but how do you know which one to select?
So like in that list, the author switched from the default selected which is the last one, to the second from top. What criteria did he use to determine which is best? Thanks in advance.

It depends on how specific you want to get. If you made a template for block.html.twig it would effect every block. block--system.html.twig would effect all of the system blocks, and block--system-branding-block.html.twig would effect the every branding-block subset of the system-block. And block--octo-branding.html.twig could possibly be every block that is using the octo-branding block plugin.

I'm not positive what template is what in your case since I don't know what is named what in your theme and plugins, but that's my best guess. Regardless the rule of thumb is it goes from most specific to most broad in order. And Drupal will use whatever template is most specific that applies in every case. For example.

I have a basic page located at /node/18.
Near the top it says

<!-- FILE NAME SUGGESTIONS:
   * page--node--18.html.twig
   * page--node.html.twig
   x page.html.twig-->

If I made a template for page.html.twig, it would load that template for every page. If I made a template for page--node.html.twig it would use that template for every page for nodes. If I made a page--node--18.html.twig it would use that template only for that specific node. If I've already made any combination of those templates Drupal will use the most specific one.


How to filter a view with another view? Let me explain my situation. I have in D7

4 different taxonomy list. Each taxonomy list is connected to other data in the system
A content type cFoo
2 different roles : contentmanager (CM) and user. hhahaha what else is new :-)

The CM is creating a entityque based on taxonomy terms which will result in let's say: tlist.

The user should select for an cFoo a term from tlist but if he used a term already in another cFoo he may not select it again.

I did testing and research but do not get the complete puzzle complete... I thought about the following solution for the user.

Build a webform with a selectbox with values of tlist. Contextual reference to this form will be cFoo.nid. Before loading this list in the webform it should already be filtered. Let say we have another view with terms already used named tListUsed. After the webform I will implement a rule to submit the selected term to the cFoo.

So now I have two views. tList, tListUsed.
The basic question was: How to filter tList with view tListUsed?

UPDATED QUESTION
With the help of flags modules and views_exclude_previous modules i do not got this problem working. There is a approach on:
https://www.youtube.com/watch?v=cQrw7Ydo1to
which I now try to implement.

The strategy is now as follows:
Load the list of tListused into a global var. Use this var as a contextual filter with multi values to exclude.

On which hook should I execute the building of tListUsed. It cannot be in the view itself as it is a filter to the view.

ps: question edited as setting up the tList for the CM is working and after trying some modules.

For those who need to implement this as well. I solved this by the following code. However in this code $tid_to_remove is not a view but generated on the view itself.

function MODULENAME_views_post_execute(&$view){

  switch ($view->name){
  case "VIEW_MACHINE_NAAM";

    GLOBAL $user;

    // Go through the view and build a list of items which should be removed
    $data = $view->result;
    $tid_to_remove = array();
    foreach ($data as $row => $rowinfo) {
      if ($rowinfo->users_node_uid == $user->uid ){     // if the current row belongs to the current user
        $tid_to_remove[] = $rowinfo->tid;  // added to the array
      }
    }

    // Optimize the array to unique values
    $tid_to_remove = array_unique($tid_to_remove);

    // Go through the view again en remove all values which are stored in $tid_to_remove
    $data = $view->result;
    foreach ($data as $row => $rowinfo) {
      if (in_array($rowinfo->tid,$tid_to_remove)){
        unset ($data[$row]);
      }
    }

    // place the values back into the view
    $view->result = $data;

  break;
  }
}


Why can't i get simple form theming to work? I've got this implementation of hook_theme in a theme :

function uncoated_theme($existing, $type, $theme, $path) {

  return array(
    'uncoated_user_register_form' => array(
      'render element' => 'element',
    ),
  );

}

Furthermore, I've got the following function:

function uncoated_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = array('uncoated_user_register_form');
}

function theme_uncoated_user_register_form($element) {
  return '

";
}

However, the function theme_uncoated_user_register_form is never invoked. I've also tried to replace $form['#theme'] with $form['#theme_wrapper'] to see if I could at least wrap the form in additional markup; but that does not work either.

I can't really see what I'm doing wrong? Drupal seems to be totally ignoring the theme function I'm trying to run the form through.

I think it's the simplest of things...

$form['#theme'] needs to be a string, not an array, so change

$form['#theme'] = array('uncoated_user_register_form');

to

$form['#theme'] = 'uncoated_user_register_form';


Store Drupal files outside of the root My website is running on Windows and it sits on drive C:/, however I'd like to keep all my files on drive D:/.
How can I do it?
I know that I can move the whole site to drive D:/ but I was wondering if it's achievable at all.

On linux, you could create a symlink to the other folder, or mount it over NFS etc..

On Windows you can actually create a symlink as well.

Something like this should work:

# Open a windows terminal and
mklink /J "C:\Webroot\Drupal\Mysite\sites\default\files" "D:\Data\Drupal\Mysite\"

That should create a hard link connecting the files folder across the two drives, with the data being stored on D:

More info:

http://en.wikipedia.org/wiki/NTFS_symbolic_link
http://en.wikipedia.org/wiki/NTFS_junction_point


Intercept data of a field of a node Drupal 8 How can I intercept the data of a field when the user add's a node?

Below is the use case:

The user can input a address in a field, when the user submits the node.
Drupal should make a rest request to the google maps distance matrix api. Then the returning value should be posted in that node. I can find enough example modules to export data from drupal through rest but not the other way around.

That sounds like a job for hook_node_presave(NodeInterface $node) to me.

That is always called before a node is saved. To optimize it, you probably want to limit your call to only do it for new nodes or when the value changed (compare your field value with the value of $node->original, note that that only exits when updating, so you want to check something like this:

if (!empty($node->field_yourfield->value) && ($node->isNew() || $node->field_yourfield->value != $node->original->field_yourfield->value)) {
  // do your call here, change $node in any way you want and it will be saved with those updated values
}

The same works for any entity type. You could also limit it to running on form submissions, but this has the advantage that it also works in case nodes are updated or created through other ways.


How to override aggregator_block_view() in the aggregator module? Can anyone tell me how to override aggregator_block_view in the aggregator module?

I have a feed I need to alter the html for and at the moment aggregator just turns the output into an unordered list.

I tried altering it in hook_item_list() but there was nothing for me to lock onto to identify the list as coming from the aggregator module.

IF you want to alter the block view you can try hook_block_view_alter

Refer to menu block alter example for an example

http://api.drupal.org/api/drupal/modules%21menu%21menu.module/function/menu_block_view_alter/7

---UPDATE---

  function hook_aggregator_process($feed) {
      foreach ($feed->items as $item) {
        mymodule_save($item);
      }
    }

Check out the docs at http://api.drupal.org/api/drupal/modules%21aggregator%21aggregator.api.php/function/hook_aggregator_process/7

Also enable the aggregator settings at admin/config/services/aggregator/settings

----UPDATE-----

Also if you just want to override the item list then you should use themename_preprocess_aggregator_summary_items(&$variables) and check for 'summary_list' this holds the items list. For more details refer to template_preprocess_aggregator_summary_items in the aggregator.pages.inc file.


Webform Custom element option values validate Can anyone please suggest how to validate the custom element option values ( select). This validate should work, once we add new element to the form and fill the option value and then click save / save and add element.

due to explaining in comment i am thinking you are making a custom
Plugin\WebformElement;
aka
namespace Drupal\YOURMODULE\Plugin\WebformElement;
use Drupal\webform\Plugin\WebformElementBase;
...
if this is the case look at this example
( '#element_validate' => [[get_class($this), 'validateOptions']] )
 public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);
  $form['general']['mycustom'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('mycustom Settings'),
  ];

  $form['general']['mycustom']['some_question_text'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Some Question title '),
    '#required' => TRUE,
    '#default_value' => $this->getDefaultProperty('hello'),
    '#element_validate' => [[get_class($this), 'validateOptions']], //HERE <----
  ];

........
later on in the same class ...
.......
 /**
  * Example validate
  */
 public static function validateOptions(array &$element, FormStateInterface $form_state) {
   $name = $element['#name'];
   // EG ... $options = $element['#options']
   $form_state->setErrorByName($name, t('@m', ['@m' => 'HELLO']));
 }


Edit tabs missing on Views block I'm new to Drupal and despite making progress over the last few days I've hit a problem.

I've got two custom content types linked with an entity reference. I'm using the Views module to create a relationship between them and output the results as a block. The block also uses a contextual filter.

All of this is working ok, I add the block to a page and the content is shown exactly as expected, except I don't get the edit/view tabs that I usually see above nodes.

If I navigate to the node by itself via the 'find content' page the edit tabs are there, but once inside the block they're missing.

I found one post mentioning that edit tabs don't appear as standard when contextual filters are used, but the post was three years old, had no solution or discussion, and and nothing to confirm whether it was actually true.

I know I can add an edit link from the Fields menu in Views but it makes the UI look inconsistent.

I'd appreciate if someone could let me know:

What exactly stops them from appearing.
What to read up on to get them working again.

Thanks.

You found the answer already. The contextual links you're looking for are just not provided by the views module when using fields (except when you add them explicitly). If you use the node row style in views they're provided through the node system of drupal. For convenience and many more options there's a module for it: Custom Contextual Links


Workflow / Views: Specific state date I need a column (field) in a view where you can see the date of a specific state (Workflow state).

For example:
A content type news has three workflow states: new, reviewed, published.
Now I need a view where you can see each news (also ones that haven't entered that state!) with a field where the date is shown when it was new, reviewed and published (sortable).
The Workflow module only provides "Previous time", but that's not specific to a state.

Any ideas?

I know how to program a views handler for custom table/fields but my problem is that the node -> workflow_node_history has an 1:n relation.

drupal 6, workflow 1.5, views 2.x

Example:

Title   | Date new     | Date Reviewed | published
---------------------------------------------------
Title1  | 01.03.2012   | 13.03.2012    | pending
Title2  | 02.05.2012   | 16.05.2012    | 20.05.2012
Title3  | 20.05.2012   | pending       | pending

The Views PHP Module provides a custome field that is click sort enabled

Value code example:

....
$result = db_fetch_object(db_query("SELECT stamp FROM {workflow_node_history} WHERE nid = %d AND sid = %d", $row->nid, $sid));
if(isset($result->stamp)) {
   return $result->stamp;
}
return 0;

Output code:

<?php
print date('d.m.Y', $value);
?>

Enable click sort: sort numerically


What to name field collection theme file? There are several articles here that address theming field collections but none that specifically cover the naming conventions required to actually get them recognized by Drupal.

field--field-field-collection-name.tpl.php does not work for me. Perhaps because I am theming the edit page of my field collection, but field--field-collection-name--edit.tpl.php doesn't work either. I have tried every permeation and order of names I can think of with no success.

Surely there is a way to theme a page whose URL is domain-name/field-collection/field-field-collection-name/*/edit.

Any help?

Theme hook suggestions typically work off of content type (or in this case bundle type), field name, or other variables. URL is not one of the defaults.

However you can create a custom template suggestion and use the URL to create that suggestion. If you want to theme the edit page you'll want to make sure you're putting the template and template suggestion in the administration theme.

Here's a good page on theming suggestions:
https://drupal.org/node/1089656


Trying to get files from the old site So I am currently trying to access our old website which was set up using Drupal. I re-downloaded all of the databases as well as the site files and set it up on a localhost.

The problem I am having is the only page shown is basically a white version of the old site with just the text of what was on it (without any of the CSS styles). When I try to click on a page it directs me to an "Access denied* page, unless I use the search box which just redirects me to a white page.

Does anyone know why I cannot get this site to work? I am just trying to access the articles that were published (which are located in the databases).

(I am running this on a local host version thru MAMP)

This is how the site appears.

Assuming your site is a Drupal 7 site

Make sure you have .htaccess in your project root. You can get it here - this should fix the access denied errors
If you have drush, run: drush cc all - this should fix the missing CSS (Drupal doesn't really serve pages directly, it makes cached versions of them. I'd say you caches are empty to they need to be rebuilt.

(If you aren't able to clear / rebuild the cache with drush, please try some of the alternative steps outlined here)


How does one see the specific structure of some variable? I'd normally use dpm($variableName), to drill down to the desired data, but I'm currently working on the webform-mail.tpl.php template file, which doesn't exactly allow that.

Most of the Drupal devs I've met seem to have this magical knowledge of how variable structures work, and I want to figure out how they found these things in the first place.

For example, I see people talk about structures like this: $node->webform['components'][$key]['form_key'] all the time.

How do they find out what's contained inside $node->webform? Is it some functionality in the devel module, or is there an amazing piece of Drupal's documentation that I'm missing somewhere?

You can use kint in a template. Enable the devel and kint modules and you can call it right from your template: {{ kint(node) }}