How does Views contextual filters work? I'm trying to wrap my head around contextual filters again! I used it a while back but I just got totally stumped again. Here's what I'm trying to do:

Generate a cloned content node page with taxonomy terms inserted into this cloned page.

ex.:  EXAMPLE.com/white-shoes/blue
When a user reaches the /white-shoes page it will show the original node page geared toward the white color. Now if the user lands on /white-shoes/blue it will show the same node page, but this time all of the body content will be rewritten replacing the white color with blue color.
In Views I would have to create a Page display with the path of: %/%
Now I would create a contextual filter to retrieve the nid. I add Content: nid as a contextual filter. I pick PROVIDE A DEFAULT VALUE and I put in this PHP code:

$x = drupal_lookup_path('source', arg(0));
$y = explode('/', $x);
return $y1;

That PHP code basically converts the /white-shoes part of the URL into a NID. But it doesnt work. I tested the code via drush ev via the terminal and I indeed get a returned result, so i know it works.
I do the same for the taxonomy term name and add a contextual filter for that aswell. This time I pick PROVIDE A DEFAULT VALUE and select RAW VALUE FROM URL and select the 2nd argument.

As you can see when I input a PREVIEW VALUE for the contextual filter: AAA/BBB/CCC . My default value gets ignored. It's supposed to be grabbing the 2nd argument, but it's getting the 1st only. Look at the SQL statement WHERE and you'll see it's getting AAA when it should be BBB.

So the question is what am I doing wrong or is there a better solution to what I want to accomplish?

Contextual Filter is used to filter ,output of the view by URL arguments, also u can pass the arguments manually in this format:

<?php print views_embed_view($name,$display_id,$arg1,$arg2,$arg3); ?>

where "$name" is the name of your view (ex. 'example_view') and '$display_id' is the display type of your view (ex. 'default') and "$arg1,$arg2,$arg3" are arguments just like in URL.

URL arguments has the following structure:

http://example.com/arg_1/arg_2/arg_3 (arg_2 has the path component 2 (in view setting page)).

When the filter value is not availabe:

it means drupal can't find any filter.

Provide default value:

when the filter value is not available you can use this option to to creat a filter for views output, this filter can be PHP code (if PHP filter module enabled) or it can get it's value from the URL arguments--> (Raw value from url).
The Exception textbox allows you to cheat the value and display all results.

When the filter value is available

in this case you do a validation as your needs and some other options, when drupal can find the filter value.


String passed to the T function in inline_template not accessible for translation For a custom field I have a formatter:

  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    foreach ($items as $delta => $item) {
      $value = unserialize($item->value);
      $elements[$delta] = [
        '#type' => 'inline_template',
        '#template' => "{{ 'translate_me'|t }} {% for key,value in info %}  {{ key|t }}  : {{ value }} <br/> {% endfor %}",
        '#context' => ['info' => $value],
      ];
    }
    return $elements;
  }

I tried to search for the string "translate_me" on admin/config/regional/translate to translate it but cannot find it. I did clear the cache, run the cron, ensure the module the define the string has a version, and viewed the node in the target language. but to no avail. What am I missing?

Thank

This was caused by the configuration for language detection and selection configuration at admin/config/regional/language/detection.

For the t() function to work, the language detection and selection for the user interface must be set to "Language from the URL (Path prefix or domain)". There is an issue on drupal.org that may address this one.


Adding #ajax to checkboxes and getting selected values in callback I've been trying to use #ajax callbacks on a form. I've got this working with radio buttons, so when I've debugged the form I get the value associated with the radio button as '#value' under 'triggering_element' in $form_state; what I'm struggling with is doing the same thing with a group of checkboxes. The first checkbox checked seems to work correctly, and I can see the correct value, but if I click a second checkbox, the value doesn't come through correctly (triggering element is the field that was returned in the previous #ajax callback for some reason??) and '#value' is a string and not an array as I would have expected. Also $form_state['#values'] doesn't contain the previously selected checkbox or the current checkbox.

How do you correctly add #ajax to an element  of type 'checkboxes' and how is it possible to get the value of all checked checkboxes when the ajax callback is fired?

There is a module that can trigger an ajax callback on a form (content type) maybe that modules solves your issue http://drupal.org/project/conditional_fields.


How to manually check if a username and password is correct? There are a lot of answers on how to log in as a specific user. But I can't find any answer on how to check if the username and password is valid without logging in. I want to be able to do something like this:

$username = "bla@bla.com"
$password = "blablabla"

$valid = checkIfValidDetails($username, $password);

I simply want $valid = true if the username and password is correct, and false if not.

How can I do that?

Drupal 6 and 7

user_authenticate($username, $password);

Drupal 8

// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

Source: How to check logged in user username/password/role using Drupal function for validation


Node/add and node/edit do not display forms I am logged in as an admistrator account and all relevant permissions are enabled for admistrators(some rights to delete a few types are disabled).

When I attempt to edit or create an event I get a page with a bread crumb, a title and no actual form or styling. I checked the html and the form isn't being sent and just not displayed either. I am using drupal 7.14 and this setup was working before moving it to another server.

According to the person who resolved the issue memory_limit on the server was the problem.


Use AJAX on a form with multiple buttons I have a form that has two text areas and three buttons, "Copy", "Reverse" and "Clear". I would like the buttons to, respectively, copy the text from one text area to the other, take the text from the first area and place the reverse of it in the other, and clear both text areas using AJAX.

I know how to do these functions in PHP but I can't seem to get the AJAX to work at all. Here is my existing code, any help  would be appreciated:

<?php

    function produce_form() {
    $form['input'] = array(
        '#type' => 'textarea',
        '#title' => t('Input text'),
        '#prefix' => '
',
        '#value' => '',
        '#attributes' => array(
            'placeholder' => t('Enter some text here... '),
        ),
        '#suffix' => '
',
    );

    $form['buttons'] = array(
        '#type' => 'fieldset',
        '#title_display' => 'invisible',
        '#attributes' => array(
            'style' => 'border: 0px; text-align: right',
            'class' => array('container-inline'),
        ),
    );

    $form['buttons']['copy'] = array(
        '#type' => 'button',
        '#value' => 'Copy text',
        '#ajax' => array(
            'callback' => 'copy_text',
            'wrapper' => 'out-text',
//          'method' => 'replace',
//          'effect' => 'fade',
        ),
    );

    $form['buttons']['reverse'] = array(
        '#type' => 'button',
        '#value' => t('Reverse text'),
    );

    $form['buttons']['clear'] = array(
        '#type' => 'button',
        '#value' => t('Clear text'),
    );

    $form['output'] = array(
        '#type' => 'textarea',
        '#title' => t('Output text:'),
        '#prefix' => '
',
        '#value' => '',
        '#attributes' => array(
            'placeholder' => t('Your text will appear here...'),
        ),
        '#suffix' => '
',
    );

    return $form;
    }
    print render(produce_form());

    function copy_text($form, &$form_state){
        $form['output']['#value'] = $form_state['values']['input'];
        return $return['output'];
    }
?>

Just two problem with your form:

Remove #value element from 'input' element
replace return $return['output']; with return $form['output'];

The problem with #value is that the element gets re-initialised on form render.

Here is the working version(copy button) of your code:

<?php

function playground_menu() {
  $items['playground/form'] = array(
    'title' => 'Form',
    'description' => '',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('playground_demo_form'),
    'access arguments' => array('access content'),
  );
  return $items;
}

function playground_demo_form($form, $form_state) {

  $form['input'] = array(
    '#type' => 'textarea',
    '#title' => t('Input text'),
    '#prefix' => '
',
    '#attributes' => array(
      'placeholder' => t('Enter some text here... '),
    ),
    '#suffix' => '
',
  );

  $form['buttons'] = array(
    '#type' => 'fieldset',
    '#title_display' => 'invisible',
    '#attributes' => array(
      'style' => 'border: 0px; text-align: right',
      'class' => array('container-inline'),
    ),
  );

  $form['buttons']['copy'] = array(
    '#type' => 'button',
    '#value' => 'Copy text',
    '#ajax' => array(
      'callback' => 'copy_text',
      'wrapper' => 'out-text',
//          'method' => 'replace',
//          'effect' => 'fade',
    ),
  );

  $form['buttons']['reverse'] = array(
    '#type' => 'button',
    '#value' => t('Reverse text'),
  );

  $form['buttons']['clear'] = array(
    '#type' => 'button',
    '#value' => t('Clear text'),
  );

  $form['output'] = array(
    '#type' => 'textarea',
    '#title' => t('Output text:'),
    '#prefix' => '
',
    '#value' => '',
    '#attributes' => array(
      'placeholder' => t('Your text will appear here...'),
    ),
    '#suffix' => '
',
  );

  return $form;
}

function copy_text($form, $form_state){
  $form['output']['#value'] = $form_state['values']['input'];
  return $form['output'];
}


Content type 1 to N relation view First of all sorry if this is a basic question.

I have two content types "Category" and "Items"

I used "Entity reference" to link  both content types with each other.

Category contains "Category1, Category2, Categry3" as data.

Items contains 10 items 1 to 10.
Lets say each categoy contains 3 items.

How can I create a view of items grouped by categories?
For example:

Category 1:

Item 1
Item 2
Item 3

Category 2:

Item 4
Item 5
Item 6

Category 3 :

Item 7
Item 8
Item 9
Item 10

Thank you very much in advance for your support

Let's suppose your nodes titles for Category content types are Category N and for Item Content Type are Item N.

Create a view on content filtered by content type = category, then in views advanced section in  Relationships add relation on your entity reference field on category content type, then in the field section again add a title but in Relationship section of the field settings choose your relation created before and then Group Results by Category title field.


How to prevent multiple logins for administrator? I have my Drupal website whose admin account is shared. But I want to limit the multiple logins, that is, only one should be able to login at a time. I have already used Session Limit Module. This works for non-administrator accounts, but not for admin account.

How can I prevent multiple administrators logins?

Session Limit allows to put restriction on session based on user role, it could be admin role also, with an exception that it does not restrict user with uid 1 which is kind of rescue point in case you misconfigure the module.

I would say instead of finding any module or building any custom solution which can put restriction on uid 1, you use different account with admin role which this/any module can handle gracefully.

As a thumb rule I don't put any restriction on uid 1.

If you see the code of session_limit.module line 248

function session_limit_init() {
  global $user;
  if ($user->uid > 1 && !isset($_SESSION['session_limit'])) {

    if (_session_limit_bypass()) {
      // Bypass the session limitation on this page callback.
      return;
    }
    ..

It clearly shows uid 1 is left intentionally.


Does Gmap work with geofield? I know Gmap is designed to work with the location module, but most spatial devs now suggest geofield as the "better" spatial data storage module.

I had to use geofield for an open layers map, and now I want to move away from the location module but I don't want to have to reimplement my other Google maps on the site.

So I can I painlessly switch?

Maybe you should investigate to what extend the IP Geolocation Views & Maps module could help you. Partial quote from its project page:

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

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Its project page contains even more information ...


control the view access permissions by field.tpl.php in D7 I would like to be able to control who can view a field by a custom field.tpl.php for a given field. Basically I would like to set a coditional at the beginning so that is displays nothing if the user does not have a given role (say, "registered-user").
I would think that this amounts to adding an "if" at the very beginning of the the field template, but I do not have much experience.
Is it possible to do it that way?

Never put any business logic into tpl files. They can be cached. So unless it's the "if odd, add class odd" type of logic, it may fail you miserably.
If you need more elaborate rules than Field Permissions give you, you need to implement hook_field_access($op, $field, $entity_type, $entity, $account) in your custom module.

Return value
TRUE if the operation is allowed, and FALSE if the operation is denied.

Field Permissions module is open source. You can see it's source to learn how this hook is supposed to be used. Same with User role field module. Both are pretty well commented in code, and can serve as good examples how to write your own custom logic. Just make sure you are not forking one, this may lead to more complications than it's worth - if they are not sufficient, inspire and even copy parts of code, but use your own name and info file.


Search using external sites Google Search I am creating a Drupal site for a government agency, and we use Google Search for our websites. The problem I'm running into is the domain the site I'm creating is on is foo.com, and the search is supposed to be run through bar.gov.

My question is is there any way to get either the built in Seach module or the Google CSE module to submit the search query on the other domain? And if there isn't how would I go about creating either a block or content pane with the search box I need?

What I need is when you click Search on foo.com it directs you to bar.gov/gsearch?sitesearch=foo.com&q=terms. Specifically getting a form's action to be the bar.gov/gsearch.

It's simple ,, if you know the HTML part so make your form action to the search site and call your GET parameters into the form!

something like this:

        <form  action="bar.gov/gsearch" target="_blank" method="GET" id="search-block-form">
        <input type="hidden" value="q" name="terms">
        <input type="hidden" value="foo.com" name="search">
<button type="submit" value="Search">Search</button>
    </form>

edit: you need to make sure you have HTML tags enabled and not stripped in anyway so the form and any other HTML tags be available .


User with uid=0 in database I had to build a form with a select field populated with all the users registered in database. There are 10 users that I can see in admin>people.

To get all the users, I used entity_load('user').

But in my select, I have one empty option in addition to my 10 users.

I checked in my database, and I found this empty UID=0 record:

I searched the Internet but I didn't find a satisfying answer. I read something about Anonymous user but I didn't get it.

Is this record important?
Does it have to be there?
If yes, I'll do some trick to ignore it in my select.
If not, can I just delete it?

Thank you in advance for this little trivial question.

Is this record important?

Yes, it prevents some queries from failing if it's anonymous user who caused them.

  Does it have to be there?

There is a possibility site would stay browsable you remove it... but it would mess your login functionality and may prevent sessions from persisting.

  If yes, I'll do some trick to ignore it in my select.

Consider using EntityFieldQuery. Omit UIDs lower than 1, or select only users with name, etc.


What Hook to Use to Execute a PHP on Every Page? I'm new to creating module in Drupal 7 and wondering what hook to use to execute a PHP script.

I use this tutorial but it it explain a different approach.

What I want is simply execute this code in every page:

db_insert('ap_visits')
    ->fields(array(
        'id' => NULL,
        'length' => $t,
        'url' => $url,
        'current_ip' => $current_ip,
        'user_agent' => $user_agent,
        'date_start' => date("Y-m-d H:i:s"),
        'is_bot' => $isbot,
        'is_logout' => 0,
    ))
    ->execute();

Note that I have already created .module and .info file. All I need is to know what hook to put the code above.

Thanks for any help.

I would look into hook_init() if you don't require this to be run on cached pages, hook_boot() if you do.


Views: Select nodes having a specific field empty I know how to create a filter to show nodes having a specific field empty, using Is equal to operator, But I want to expose this filter to visitor in form of checkbox. I want a check box for example with title "Show nodes that doesn't have an image".

Is it possible using Views 3?

Have you tried using better exposed filters?


Set a session when page is loaded I want to define a session in contributed module (field collection module) in drupal 7 when the page is loaded.

This session takes a value from the URL and fill one of the field that depend on it. I defined a session in the form_alter function but I need to refresh the page to let the session take the value? So, could anyone tell me where I can define it? In which function of the module?

You can use the session that Drupal creates. Just add your data to an element of the $_SESSION variable:

$_SESSION['my_module']['some_key'] = 'some value';

It will


How to find and remove string in front of URL? We have a url pattern of [node:menu-link:parents:join-path]/[node:title].

We are finding that it is resulting in the following urls and we wanted to see if we could use hook_pathauto_alias_alter to remove the undesired string. We are finding that when doing the preg_replace, that is removing all instances where the "/" is found. We just want to remove the string upto the first "/" character. Need assistance in figuring out why it is not working.

function mymodule_pathauto_alias_alter(&$alias, array &$context) {
       $patt = '.+(\/)';
       $replacement = '';
       preg_replace($patt, $replace);
}

Current results:

some-text/menu-linka/menu-linkb
some-text/menu-linka/menu-linkb/menu-linkc

Desired results:

menu-linka/menu-linkb
menu-linka/menu-linkb/menu-linkc

I see many problems in the code you posted in your question. First of all, you are missing a parameter in preg_replace. Take a look at the PHP documentation.

Second, you have no delimiters in your pattern. The correct pattern should be:

$patt = '/.+\//';

(You don't need the parenthesis, but you do need delimiters such as slash bars. See this).

Third, preg_replace() returns an array with the replacement. You need to assign the result to $alias, as in $alias = preg_replace(...)

I have not use this hook before, but keep in mind (from the description) that this is only invoked before the alias is saved.


How do I make parent taxonomy paths? I installed Pathauto, Tokens and Entity API module in Drupal 8 and I have been unable to create a pattern that would allow parent taxonomies and then the final node for content type pages. In Drupal 7 the entity API module would add the extra tokens I need but it does not seem to work for Drupal 8.

For Drupal 8 the token [term:parents:join-path] works but it is only usable for taxonomy type pages and not content type pages.

If anybody can help me,I would greatly appreciate it.

This is being worked on, see https://www.drupal.org/node/2493559 and https://www.drupal.org/node/2621598.

In the meantime, you need a bit of custom code to connect the dots. You need to implement hook_token_info()to define a token on nodes for your field with type term. You can also switch the type of the generated field token to term. The second part is a hook_tokens() implementation that forwards [node:yourtokenname:...].

It's similar to what node_tokens() does with node:author:name for example, which forwards the part after author to the user token generation:

if ($term_tokens = $token_service->findWithPrefix($tokens, 'yourtokenname')) {
  $replacements += $token_service->generate('term', $term_tokens, array('term' => $node->field_yourfieldname->entity), $options, $bubbleable_metadata);
}


Find top and average value from input field text H i have like 2000 nodes with field type - text field.

Purpose of that field is to be filled with best time that someone had on race. Format is something like 02:43:02 ( keep in mind that is text field and not time picker ).

Now i have been asked to show top 10 times, and average time, and im not sure how to do math here if that is text field?

Can views find top 10 times from text field?

The PHP function strtotime() might help you here:

  strtotime — Parse about any English textual datetime description into a Unix timestamp

For example, you could create a computed field and use that function to convert the text input to a time value.

But as you're using a text field and not a date/time filed, I doubt that you'll be able to get all values correctly (because user input can differ enormously).


Commerce Kickstart and product variations I am relatively new to Drupal and I am trying to build an eShop with Drupal Commerce Kickstart.

One of the good features is the ability to have product variations and attributes in variation type which affect the price of the product.

Unfortunately, I have not managed to make it work correctly.

My main issue is that the "All Products" page show only main products and not the variations and that on this page the facets of the attributes that are in variation type are not show-up. They work only the facets that are for the attributes of the content type of the product.

If I do not find a solution soon, I will forced to give up these two very powerful features of Drupal Commerce and simply have products without variations.

How can I achieve what I want?

TLDR: This is due to how Commerce Kickstart is configured for entering new products. You enter product variations while adding the product.

When you create a product in Commerce Kickstart, you're actually creating the node that the customer will see. Scrolling down the page, you'll see the ability to add the individual product variations (which are the actual product entities) like so:

This is an Inline Entity Form (aka IEF). See, normally when you'd use Drupal Commerce, you'd need to create all of your individual entities and then add them to a product using a product relationship field. But this a Drupal field widget take takes that step out by letting you enter in your product data and relate it to the display node in one step.

If you want to see all of the product variations, there should be a tab at the top of the Products admin page that will take you to a listing:

You can edit products here, but you can't add them directly because of how Kickstart controls the product add process.


Does a module for real-time data plotting exist? There are several Drupal modules that allow to plot /chart data stored in database tables. Is there any module that can chart or plot data in real-time? For a specific example, I have a mobile application that is reading sensor data (say from an accelerometer) and sends that to the Drupal server. I want to plot the data as and when updated in real-time or near real-time. Does any specific module that can do this exist?

Google Chart Tools

  Display live data on your site using Google Chart Tools Google Chart
  Tools module provides a simple API to Build custom interactive SVG
  charts.

  Views integration

  The Google Chart Tools Views module is based on the Views built in
  aggregation function. For basic instructions of using the Views
  integration module check the README.txt file

or

Quant provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.

  Quant API (easily provide your own charts)

  The real power of Quant lies in it's ability to generate these charts
  with very little provided information. Quant offers a simple, yet
  flexible API to allow developers to include quant charts with their
  modules.


print data to twig file from custom form submit via controller I have created a custom form, and I'm passing data to twig file from submitForm function as follows

public function submitForm(array &$form, FormStateInterface $form_state)
{
$form_state->setRebuild();

$data = ['role' => $form_state->getValue('role'),
'date' => $form_state->getValue('date')
];
MyController::Detail($data);

}

and in controller passing data to twig

public static function Detail($data) {

return [
'#theme' => 'my_report',
'#data' => $data,
];

}

but not able to get/print data in twig file.

When you set rebuild in a form submit there is no controller involved. The next page displayed is the rebuilt form, where you can print the my_report twig template by adding it to the build array $form.

You don't need to transfer the values in $form_state, because they are available while rebuilding the form. You can check in the form build function whether these values are present. If not, you are building a new form. If they are, this is a form rebuild, then display the result template:

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

    // build form

    if ($form_state->hasValue('role')) {
      $form['my_report'] = [
        '#theme' => 'my_report',
        '#role' => $form_state->getValue('role'),
      ];
    }
    return $form;
  }


Automated database history save and recovery Drupal 7 I have a site implemented in Drupal 7. I want to make a history database recovery tool, which will recover previously recorded MySQL data. I have tested correctly on non-Drupal content which is used by the site. If I want to recover previous versions of Drupal content (just nodes and the info related), should I use a collaboration module? Which would be recommended? Should I restore the complete database or could I mysqldump and later mysql some selected tables (fields*, node*, etc.). Thanks!!!

Take a look at Backup & Migrate Module:

  Back up and restore your Drupal MySQL database, code, and files or
  migrate a site between environments. Backup and Migrate supports gzip,
  bzip and zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database
  tables to a file download or save to a file on the server or offsite,
  and to restore from an uploaded or previously saved database dump. You
  can choose which tables and what data to backup and cache data is
  excluded by default.


How to load Ajax Site Wide? I am trying to open a webform in a modal window through following link, which works fine when I am logged in, but when I logout it simply stops working

Get a Call Back

It seems like we need to load ajax on pages where we want to use this link, so I want to know how can I load ajax sitewide.

Implement hook_page_attachments_alter() like so:

function MODULE_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'drupal.ajax';
}

The same hook can be implemented in a theme if that makes more sense.


Preventing a menu item from being pressed twice I have a menu item that shows up on one of my nodes and when pressed it will trigger a somewhat long process. I would like to make it so that the user is not tempted to press the menu button again but I can't quite figure out how to do that. Is there a good way to put an overlay over the Drupal window to explain that the process will take some time and prevent another click? If not, would it be possible to show an alert dialog from the menu callback, warning the user this will take some time.

For long tasks you should use Drupal's Batch API. It takes a bit to learn, but has these benefits.

The user will be taken to a separate page with a progress bar.
You can display a custom message explaining what you are doing.
If you can break your task into discrete chunks that can be performed in separate requests that will ensure that you won't run into any php timeout issues and the users will see their progress.

For example, during Drupal setup you see the following batch process:


Taxonomy terms won't arrange themselves by ID but will work alphabetically instead I added a large number of taxonomy terms in the order I want. Their term IDs reflect they are added in the correct order. However, everywhere they are displayed alphabetically. Particularly, inside a hierarchical select widget they are displayed alphabetically - when I see their IDs (856, 847, 843 - not a correct numeric order but correct alphabetic A, B, C) they check out fine so they were added properly. How can I control this?

The order in which you enter the taxonomy terms is not important to how they are displayed. Drupal defaults to alphabetic ordering, but you can adjust this order manually.

Go to Content management > Taxonomy > Your vocabulary: List terms (via admin/content/taxonomy/list) and reorder the terms by dragging the handle on the left. This is also the order Hierarchical Select uses.

You can also try out Taxonomy Manager to see if this provides you with a better interface for reordering large numbers of terms.


How to export custom module form content as PDF file in drupal 7? I have a custom module with some form fields. I want to submit this form and generate pdf file of user filled values in new tab. I am trying with TCPDF but it doesn't display any fieldset ( as border ).

In submit funciton , I am taking $form array and using drupal_render($form) that render form values as html ( if I print ). If I pass this html to WriteHTML($html, true) , it gives pdf but there is no styling left on that form.

TCPDF doesn't support all styling attributes.It only supports some of the features that are given below.it has a very limited CSS support.

font-family
font-size
font-weight
font-style
color
background-color
text-decoration
width
height
text-align

Basically, You can use tables to style your pdf data And styling pdf throught table attributes.like

colspan
rowspan
align
cellpadding
cellspacing
width
border

etc.

And Note That PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.


Switch a language programatically Looking for a way to change between languages on our site, the Drupal 8s LanguageManager doesn't seem to have a straightforward method for this. We cannot use URL-switching, just want to do this through code.

So we want to go from "en" to "fr" for instance. Is there a method like "setCurrentLanguage" available somewhere?

In a custom module, you should use a custom LanguageNegotiator and assign it to your LanguageManager, using LanguageManager->setNegotiator();

1) First, you must define a CustomLanguageNegotiator, which overwrites initializeType() method. That method should return a Language object, which you can externally define using a custom setLanguageCode() method:

<?php

namespace Drupal\custom_module\Language;

/**
 * Class responsible for performing language negotiation.
 */
class CustomLanguageNegotiator extends \Drupal\language\LanguageNegotiator {

    var $languageCode = NULL;

    /**
     * {@inheritdoc}
     */
    public function initializeType($type) {
        $language = NULL;
        $method_id = static::METHOD_ID;
        $availableLanguages = $this->languageManager->getLanguages();

        if ($this->languageCode && isset($availableLanguages[$this->languageCode])) {
            $language = $availableLanguages[$this->languageCode];
        }
        else {
            // If no other language was found use the default one.
            $language = $this->languageManager->getDefaultLanguage();
        }

        return array($method_id => $language);
    }

    /**
     * @param string $languageCode
     */
    public function setLanguageCode($languageCode)
    {
        $this->languageCode = $languageCode;
    }

}

2) Define your CustomLanguageNegotiator as a service, in your custom module service file, "custom_module.services.yml":

custom_module.language_negotiator:
  class: Drupal\custom_module\Language\CustomLanguageNegotiator
  arguments: ['@language_manager', '@plugin.manager.language_negotiation_method', '@config.factory', '@settings', '@request_stack']
  calls:
    - [initLanguageManager]

3) Rebuild your cache and use your CustomLanguageNegotiator like this:

$languageManager = \Drupal::languageManager();
$customLanguageNegotiator = \Drupal::service('custom.language_negotiator');
$languageManager->setNegotiator($customLanguageNegotiator);

// Set new language by its langcode
$languageManager->reset(); // Needed to re-run language negotiation
$languageManager->getNegotiator()->setLanguageCode('fr'); // 'en', 'es', 'fr', etc

// Run any code, and its output will be displayed in french
// ...

$languageManager->reset();
$languageManager->getNegotiator()->setLanguageCode('en');

// Run any code, and its output will be displayed in english
// ...

// Do not forget to set language to its initial value
$languageManager->reset();
$languageManager->getNegotiator()->setLanguageCode('XX');


Create a master or main page I want to know how to do is create a master or main page. I come from an ASP.Net background and am truly trying to learn Drupal, but I am very frustrated with finding where/how to start.

For me, the start has always been creating a main page. I use .Net as my platform but usually do all my work through HTML and CSS, as in creating a 3-column website using CSS. However, I really like the functionality of .Net in that I create this on ONE page as a master, and then just insert my content in a content holder. I know things don't work exactly the same, I don't expect them to, but I would like to know how to create a master page, or basically a template that contains the header, footer, menus and content layout.

How do I create a basic main page template?

You may need to do some research into the way the drupal system works. Here is the documentation page for how to theme drupal. http://drupal.org/documentation/theme

If you are looking to create you own theme. For a beginner, it may be easier to start with a theme framework to mold it into what you want. Here are 3 of some of the more popular frameworks; Zen, Fusion, and Adaptive Theme.

P.S. - You may want to consider doing some basic google research prior to asking questions on here without more supportive information.


Why is there a  tag where I didn't add it? I put the following code into the bock content box and set the input type to Full HTML; then I enabled it on page--front.tpl.php. When I viewed the HTML source, I
saw the  label contained a
 tag.

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test/strong>

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

test

      Fujia Chanpin 01

For example, for the last list item, the output was the following.

tsdet
Fujia Chanpin 01

Why is there a
 tag where I didn't add it?

For not getting the paragraph tags, you need to use an input format that does not include the Lines and paragraphs break automatically setting.

Check to see if Convert line breaks into HTML input format is enabled in admin/config/content/formats/full_html, and disable it. You can still add <p> and <br>, but Drupal will not add them automatically for every line break present in the text.


Print specific page of a paged node I am using Print module to print a Drupal node.
Recently users have asked the ability to print a node in form of individual pages.

For example if a paged 'Drupal' article spans on 5 pages, user wants the ability to print only 2nd page.

I tried to analyze the var_dump of a node (by pro-grammatically loading it) to find any information related to paging but I did not have any luck.

I am thinking to do paging of a node pro-grammatically and load different paged content in an array.

How can I do this ?

Please let me know if I need to provide more information.

I was able to get specific paged content using following code.

  $data = node_load($nid);
  $pages = explode('<!--pagebreak-->' , $data->body['und'][0]['value']);


db_update doesn't work with my code Whith a custom module, I'd like to update some nodes uid whenever a content type is updated.
I triple checked, and my database update function is called, as "changed" field is updated each time, and I send myself a mail to check that the data passed is correct.

I don't know how to call the equivalent of mysql_query() or die(), and don't manage to debug that.

I have only a notice:

  Undefined index: #language dans locale_field_node_form_submit().

function zen_custom_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  switch($form_id){
    case 'lieux_de_pratique_node_form':
      if (in_array('Admin dojos', array_values($user->roles))) {
        // some stuff
        $form['#submit'][]='set_dojos_manager';
        // ...
      }
      // ...
  }
  // ...
}

function set_dojos_manager($form, &$form_state) {
  $dojo_editeur = $form['field_dojo_editeur_web']['und'][0]['uid']['#default_value'];
  $dojo = $form['nid']['#value'];
  $uid_updated = db_update('node')
    ->fields(array(
      'uid' => $dojo_editeur,
    ))
    ->condition('nid', $dojo)
    ->execute();

    mail('my_email', 'test', $dojo_editeur . ' / ' . $dojo);
  }
}

Your form submission handler should take the submitted values from $form_state['values'], not $form. The node object is then available in $form_state['node'].

For such task it would be better to implement hook_node_presave(), which is called right before a node is saved.


Why is my theme library load on every page? I'm beginning with D8, but I work a lot with D7 and Magento. I follow the developer documentation to add a library in my theme, and I don't understand why it's loading it on every page. I only want attach it to a brunch of page with a preprocess hook. Could you help me please?

In my theme.libraries.yml I add this at the end:

hover3d:
  js:
    js/hover3d.js: {}

In my theme.info.yml I add under libraries "theme/hover3d".

Here is specific information:

I deactivated JavaScript/CSS compression in the back office and in my settings.local.php file
My theme is a sub theme of bootstrap_barrio
My Drupal version is 8.6.3
There is no custom / contrib modules yet
I discover it by inspecting my page

I don't really understand how JavaScript parts are loaded, but I suppose it's with lazy builders which are called placeholder and in D8 for rendering JavaScript there are two (or more) which are js-placeholder and js-bottom-placeholder. I see in my HTML structure that in the js-placeholder is only loaded modernizer and in the js-bottom-placeholder all the others. I don't know if this is a correct JavaScript rendering procedure, so I keep it here if it can help you.

In my theme.info.yml i add under libraries "theme/hover3d".

That's why it's loaded on every page. libraries in the theme info file is:

  A list of libraries (which can contain both CSS and JavaScript assets) to add to all pages where the theme is active.

To add it contextually, attach it to a relevant render array. For example:

function MYTHEME_preprocess_node(&$variables) {
  // Library will only be loaded when a node is rendered on the page.
  $variables['#attached']['library'][] = 'theme/hover3d';
}

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme for more information.


Render comment edit form in block I am using following code to render node comment form in a block:

$comment_form = drupal_get_form('comment_node_<node_type>_form', (object) array('nid' => $nid));
print drupal_render($comment_form);

It is working fine.

Now I need to check if a user has already commented on the node. If the user has not commented than I will show him/her this comment add form.

But in case, the user has already placed a comment for the node, I want to show him/her the edit form for his/her comment, where he/she can make changes and save thus updating the existing comment instead of saving new.

Any suggestions?

I found a solution for this case, sharing so that anyone who need similar solution can use it.

Anyone who has similar issue can use the solution below:

<?php
    $comment = comment_load($comment_id); // $comment_id = cid of comment whose edit form need to be open

    module_load_include('inc', 'comment', 'comment.pages');
    $form = drupal_get_form('comment_form', $comment);

    return drupal_render($form);
?>


Heading for comment section I would like to have a heading over my comments that only appears after a comment has been left... I tried the code below but it doesn't seem to be the answer:

<?php if ($comment): ?>

Comments

<?php endif; ?>

This is the default behavior of Garland. Have a look in the themes/garland/template.php file:

function garland_preprocess_comment_wrapper(&$vars) {
  if ($vars['content'] && $vars['node']->type != 'forum') {
    $vars['content'] = '
'. t('Comments') .'
'.  $vars['content'];
  }
}

Where did you put your code? Depending on your theme, you most probably want to theme comment-wrapper.tpl.php, which only gets output when there are comments to be displayed. Which what you want. :-)


Overriding user profile form So I have this function:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  dsm($form);
}

What I want to do is to remove "Language settings" fieldset with all the radio buttons inside it. But for some reason I don't have any array element which is responsible for displaying this data. I've read that this should be $form['locale'] but it's not there for sure. What migght cause this kind of behaviour?

It could be that your form_alter happens before the locale field is added. Make sure your module runs last.


Running drush from a minimal shell My goal is to pipe mail with Postfix into a drush command. I made a simple bash script that redirects stdin to the drush command, and I configured Postfix to pipe mail to the script. But executing drush from the script does not work, as it cannot connect to the database. I assume there is some environment/bootstrapping missing but I cannot figure out what.

Bash script, postfix-filter.sh:

#!/bin/bash

# Enter Drush environment
cd `dirname $0`

# Redirect stdin to Drush command, log any ouput
/usr/local/bin/drush my-command <&0 &> my_command.log

Running the script from terminal works fine:

$ ./postfix-filter.sh < test.eml

But when triggered by Postfix receiving a mail, the following is printed to the log file:

The drush command 'inmail-process' could not be found.  Run `drush       [error]
cache-clear drush` to clear the commandfile cache if you have
installed new extensions.
Drush was not able to start (bootstrap) the Drupal database.             [error]
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version        :  8.0.0-dev
 Site URI              :  http://default
 Database driver       :  mysql
 Database hostname     :  127.0.0.1
 Database port         :
 Database username     :  root
 Database name         :  drupal
 PHP executable        :  /usr/bin/php
 PHP configuration     :  /etc/php.ini
 PHP OS                :  Darwin
 Drush version         :  7.0-dev
 Drush temp            :  /tmp
 directory
 Drush configuration   :
 Drush alias files     :  /Users/mdi/.drush/aliases.drushrc.php
 Drupal root           :  /usr/local/var/www/d8/www
 Site path             :  sites/default
 Active config path    :  sites/default/files/config_FTG0_Sy-OJ0Mco
                      1c4ZlOBwJ3Ia-sMX0PcQiIiaGcsRufMWfFBWwSWLu
                      lhB83nL0hF9Dl9Y24-w/active
 Staging config path   :  sites/default/files/config_FTG0_Sy-OJ0Mco
                      1c4ZlOBwJ3Ia-sMX0PcQiIiaGcsRufMWfFBWwSWLu
                      lhB83nL0hF9Dl9Y24-w/staging

As you can see from the output, I have already tried setting the database host to 127.0.0.1, as suggested by various discussions I found.

Any ideas on what is missing?

Adding the following line to the beginning of the script fixed it:

PATH=/usr/local/bin:$PATH

I assume Drush uses the $PATH in turn to call other commands.


views - remove duplicates based on field value Hi I have an order list created in views with 2 fields: order ID and order payment method. Each order can have multiple payment methods (every payment method gets own incremented id when attached to order).

Example:

order id1 with payment id1
order id2 with payment id2 and payment id3
order id3 with payment id4

This causes duplicate rows in second case.

Problem: How can I show only orders with the last payment method attached to them?

One solution would be to create one view with order id argument, showing only one row and sorted by payment id descending. Then using views field view module and create another view with order list without duplicates.

Question: is there a more simple solution without creating second view? Thank you.

I would use Views Distinct module to filter the duplicates out. The way this works is this:

you select the displayed view field,expand 'Views Distinct Settings' and select 'Filter Repeats'

So, for your particular case, if you want to show only the last payment method, order by payment method (ID ?) DESC, and on the order_id filter repeats. This way, only the last row for every order_id will show.


How to get the actual value of a field in Views? I'm using the Views module and Drupal 7 and want to add a class to all rows of my table that have a certain value for a certain field.

The field is a bit field and is included in my query. I have added a PHP field (a separate Views module that is installed) with the following code:

if ($row->field_kampioen || $row->field_spirit) {
    return 'views-table-highlight';
} else {
    return '';
}

This should allow me to set the row class to [php]. This works, but all rows get the css class. When I output this for debugging:

return $row->field_champion . ' ' . $row->field_spirit . ' ';

I see that the classes are all different numbers, and field_champion is equal to field_spirit. This makes me think I'm seeing the ID.

How can I get a TRUE of FALSE? So, how can I get the actual bit value of this field?

It would be nice if I could do this via the Views module only, but I've seen pages where hooks are used. Maybe I'll have to use that.

I'm assuming you are using Drupal 6, since you mentioned about PHP filed.

below is the code to retrieve value from a field and where ['tid_1'] is the token for a field. I think this is similar for Drupal 7 too.

<?php
$static = $this->view->display_handler->get_handlers('field');

$b=$static['tid_1']->last_render; //$b contains the value of the field
$d=$static['tid_2']->last_render; //$d contains the value of the field
//use your logic
 ?>


D7 Views: content associated with a user via tags I want to display a View of all content relevant to the logged in user based on tags that are defined in a node referenced by the user. Something that follows this relationship:

Logged in User --(references)--> Customer Subscription -(shares tags with)-> Content

The view should show all the Content associated with the user based on this logic.
I prefer to do this via modules and not code.

Any ideas?
Thanks!

Maybe these links could be a good starting point, as they provide a step by step guide of how to configure views with a relationship to the current user:

http://blog.hsl.virginia.edu/drupalpress/show-users-any-content-that-matches-any-taxonomy-term-in-views/

http://blog.ampli.fi/filtering-a-drupal-7-view-based-on-a-user-profile-field/


Getting a list of nodes of a specific type (eg, forum) via REST API I am using Drupal 7, with the Services module. I have the REST API enabled.

I have successfully done a user.login, and have retrieved the session id and session name, and then constructed the Cookie from same.  I can successfully get a list of ALL nodes using this:

curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  http://myserver/rest/node

How do I get the list of nodes of a specific type? Eg, nodes of type=forum ?

I tried

curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  http://myserver/rest/node?type=forum

But that gave me the same list of all nodes.

Edit.  this is what worked for me:

curl -i -X GET \
  -H Cookie:SESS02cbaaadbeeef=Dw8dsijhd9usdkjlb4Plsz_dipuJumGww \
  -H Accept:application/json \
  'http://myserver/rest/node?parameters\[type\]=forum'

Thanks to burnsjeremy.

Services 3.x

You would use the parameters like this:
http://localhost/endpoint/node?parameters[type]=node_type

You can find out more how to use this by looking in the code (going off memory here):
File: services/resources/node_resource.inc
function: _node_resource_index


User cannot view their Orders in Ubercart For Drupal (v7.22) I have a basic install of Ubercart (v7.x-3.4) and have set the permissions to allow an authenticated user to 'View own orders' and View own invoices'. But if an authenticated user visits an order page (for an order they made) they get the error:
page: example.com/user/user_name/orders/1

Access denied
You are not authorized to access this page.

I've been though all of the settings and googled this but cannot see what I've missed. Does anyone know if I've missed a permission/setting somewhere?

Enable the Allow customers to view order invoices from their order history in Order settings, see the below image may be this will be the problem for you and i am not sure because i have drupal 6 installation only.


D7 bug with db_select, 'addExpression' and 'having' conditions? As I asked in the drupal forum http://drupal.org/node/1393748 (no answers..)
I have an issue with a db_select query.

It seems that addExpression "GROUP_CONCAT" and "HAVING" is causing an issue.

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ATTO' in 'having clause': SELECT COUNT(*) AS expression FROM (SELECT 1 AS ...

<?php
$query = db_select("adm_f", "f");
    $query->fields("f", array("F_ID", "F_TIT", "F_TITOR", "F_DES", "F_ANN", "F_PAE", "F_REG", "F_IMG"));
    $query->addExpression("GROUP_CONCAT(t.TAG_DESC separator ', ')", 'ATTO');
    $query->leftJoin('adm_a', 'a', 'a.F_ID = f.F_ID');
    $query->leftJoin('adm_t', 't', 'a.TAG_ID = t.TAG_ID');
    $query->condition('t.TAG_TIP', 'code', '=');
    // other conditions..
    $query->groupBy('f.F_ID');
    $query->groupBy('f.F_TIT');
    $query->groupBy('f.F_TITOR');
    $query->groupBy('f.F_DESC');
    $query->groupBy('f.F_ANN');
    $query->groupBy('f.F_PAE');
    $query->groupBy('f.F_REG');
    $query->groupBy('f.F_IMG');

    // BUG ???
    if(trim($_GET['F_ATTO']) != '')
        $query->havingCondition('ATTO', '%'.trim($_GET['F_ATTO']).'%', 'LIKE');

$query = $query->extend('PagerDefault')->limit(10);
    // echo($query->__toString()); exit;
    // execute
    $rs = $query->execute();
?>

I solved the problem with a workaround, but I would like to use HAVING and not a second query...

Many thanks for your help!!

Sounds like the problem is the paging, because it's the count query that gives you the error. For debugging, try to disable the paging.

If it works without paging, it means that the automatically generated count query doesn't work and you need to create one manually and then set it with $query->setCountQuery() after doing the extend('PagerDefault').

The automatically generated query removes all selected fields, which then causes the error when you are trying to access it in the having condition.


How to properly inject mutable config to the controller? Apparently by default ControllerBase::config() returns \Drupal\Core\Config\ImmutableConfig object. How can I instantiate the controller class to make it use \Drupal\Core\Config\Config instead (which is mutable)?

I know I can do this inside the controller:

$config = \Drupal::service('config.factory')->getEditable('loremipsum');

However this is not the nicest solution. Besides, is there any reason for using ImmutableConfig by default?

There are two other ways to inject dependencies into a controller, and a third alternative.

1. Implement ContainerInjectionInterface

This does technically add a dependency to the container. In a unit test, the container would need to be set with \Drupal::setContainer() with a mock object of the config factory and config object.

`

  public static function create(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
    return new static($container->get('config.factory'));
  }

  public function __construct(\Drupal\Core\Config\ConfigFactoryInterface $config_factory) {
    $config = $this->config_factory->getEditable('loremipsum');
  }

`

2. Make the controller a service.

This is recommended by all of the Symfony developers that I have asked, and none have been concerned by any performance impact of making all of Drupal's routes use services.

This is subjective, and there is some contention about the practice.

3. Use a Form class that extends ConfigFormBase instead.

But, why would a controller want MutableConfig instead of ImmutableConfig? A Form class extending ConfigFormBase instead. A form is probably the best place to modify configuration values such as a class that extends ConfigFormBase.


Suddenly unable to add a field to a new content type When editing a content type I was going to add a simple boolean field to an existing content type. When attempting to add the new field Drupal threw an error. After a few more attempts to add a field to an existing content type I created a new content type to add a field to and was unable to add a field to a new content type.

I get the following error when trying to create a new field on a content type:
There was a problem creating field First Name: Attempt to create a field field_first_name that does not exist on entity type node.

I have the same problem trying to a field to a taxonomy item:
There was a problem creating field IsActive: Attempt to create a field field_isactive that does not exist on entity type taxonomy_term.

It turns out a configuration change is the cause of this error. Disabling APCu caching and using the ChainedFast cache backend was the cause.

More detail can be found: https://www.drupal.org/node/2722615


Taxonomy Term View not showing image field Drupal 7, Views 3

I have created a Taxonomy Term View for a particular vocabulary. If I set the Format Show option to "Fields", and add the Taxonomy name and image fields, then for some reason only the name shows. If I change it to "Rendered entity" then everything works fine. Another weirdness: this is only for some vocabularies - for some other vocabularies, the fields option works just fine (it shows the image). Any thoughts on why this might be? Any ideas how to debug this? Thanks guys.

Heh, well, as said in the comment, be sure to either have the same field or add all image fields :)


Edit the display of view on drupal 8 Currently working on theming with Twig
I created a region called 'Blog Content'
I placed under it a view that i recently created Called 'Blog' with a display Block to display just the 3 last article**

for each field I specified the wrapper around it and the CSS class used by my theme and I have this output:

But i want it to be just like this:

My questions:

How to specify the tag (html) to be used to display my field with specific css class : in my case i want to display the title with
What field should i add to add the date of post

Edit your field on which you want to add an HTML tag to a specific class.(Style settings category)
See screenshot.
You need to add "Authored on" field and configure the display as you want to be shown.


Additional field settings without creating a new field type I'm trying to add 2 options to the field settings of all fields of a particular field type, in this case file field. To add the fields to the form I'm using MYMODULE_form_field_config_edit_form_alter() instead of extending the base class so it will work with other modules and I won't need to use a custom field type.
Using ThirdPartySettings to store the data doesn't add it to the base config for the field therefore the settings won't be automatically available to other modules.
e.g.
function MYMODULE_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $field = $form_state->getFormObject()->getEntity();
  if ($field->getType() == 'file') {

    $settings = $field->getSettings();

    $form['my_checkbox'] = [
      '#type' => 'checkbox',
      '#title' => t('My Checkbox'),
      '#default_value' => isset($settings['my_checkbox']) ? $settings['my_checkbox'] : '',
      '#description' => t('Check to check my checkbox.'),
    ];

    $form['#entity_builders'][] = 'MYMODULE_form_builder';
  }
}

function MYMODULE_form_builder($entity_type, FieldConfig $field, &$form, FormStateInterface $form_state) {
   // What goes here? I can't do $field->set() on properties which don't exists.
}

I've tried setting up a schema file as src/config/scheme/mymodule.schema.yml but I'm not sure how to extend the relevant settings in core/modules/file/config/schema/file/schema.yml.
base_file_field_field_settings seems to have the relevant entries I'm wanting to add to. Do I need to add a class or an install yml file?

This works for me:

$field->setThirdPartySetting('mymodule', 'my_checkbox', $form_state->getValue('my_checkbox'));

After you save your field settings, the new third party setting should be available in your field config:

third_party_settings:
  mymodule:
    my_checkbox: 1

Here is a good article about this: https://www.webomelette.com/drupal-8-custom-data-configuration-entities-using-thirdpartysettingsinterface


With managed file, dynamically set fileName and #upload_location In a form I want to bulk upload jpgs renaming them using exif date information and dynamically setting the #upload_location according to the value of a textfield in the same form.
I have no problem with accessing the exif date information. What I don't know how to do, is dynamically set the file name and file path (actual location on the server) programmatically.
This is my form upload element:
$form['images'] = array(
  '#type' => 'managed_file',
  '#multiple' => TRUE,
  '#upload_validators' => array(
    'file_validate_extensions' => array('jpg'),
  ),
  '#upload_location' => 'public://photos',
  '#required' => TRUE,
);

$form['file'] = [
  '#type' => 'fieldset',
  '#title' => $this->t('File'),
];

$form['file']['name'] = [
  '#type' => 'textfield',
  '#title' => $this->t('File name'),
  '#description' => $this->t(
    'Is suffixed by the exif creation date-time plus fid cleaned for urls. If not set the original file name will be used.'
  ),
];

$form['file']['path'] = [
  '#type' => 'textfield',
  '#title' => $this->t('File path'),
  '#placeholder' => 'path/to/directory',
  '#description' => $this->t(
    'Path to the files sub-directory, default is "photos". Sub-dirs will be create if necessary.'
  ),
];

I've tried using something like this in both validateForm() and submitForm().
$images = $form_state->getValue('images');
$file = File::load( $images[0] );
$file->setFileName("xxx2");
$file->setFileUri("public://photos/test/xxx2.jpg");

Although this changes the values of the $file object, it doesn't change the real path. The jpg files are also still in /sites/default/files/photos/ with their original name plus a unique counter.
So to repeat my question:
How can I set the upload_location and the fileName of a managedFile dynamically and programmatically in a submitForm() or validateForm() function using methods that are not marked deprecated in drupal 8.

Thanks @Clive. I just read your comment, but in the mean time I found the answer myself. This is the essentials of my code in my submitForm() method. It still seems a bit hacky to me but it works.
$images = $form_state->getValue('images');
$file = File::load( $images[0] );

$file->setPermanent();
$file->save();

$new_filename = "photos/test/test-02.jpg";
$stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
$new_filename_uri = "{$stream_wrapper}://{$new_filename}";

file_move($file, $new_filename_uri); // <===== The essential line!

$file = File::load( $images[0] );
dpm($file->getFilename()); // returns test-02.jpg
dpm($file->getFileUri());  // returns public://photos/test/test-02.jpg


Create view with parent taxonomy terms only I have a view of nodes, which are associated with a vocabulary, and it contains both child and their respective parent terms. What I want is in this view, only the parent categories will be coming. I have already tried the parent relationship but it gives me repetitive rows with each parents. I have described the problem and what i want to achieve here :

https://www.drupal.org/node/652234#comment-9422885

Help appreciated...

Create contextual filter with parent taxonomy term id as fixed value 0


Get Users by roles for organic groups drupal7 I have following system roles  set up for users

content publisher
content approver

All my users divided in to 5 organic groups.

I didn't set up any roles for organic groups.I am trying to get content approvers for particular group for approval process.

I tried using this function og_get_users_by_roles.

But the above function uses the organic group roles not system roles.

I am confused now should i setup same roles for organic groups.Please give some direction.

Try this if it works for you.call this function with user_role id and group id as parameter.

    function get_users_on_role_and_group_basis($rid, $gid) {
      $users = entity_load('user');
      foreach($users as $user) {
         if(is_array($user->og_user_node)) {
           if (array_key_exists($rid, $user->roles)) {
             foreach($user->og_user_node['und'] as $key=>$values) {
               if(in_array($gid,$values)) {
                 $get_user[] = $user;
                }
            }
          }
        }
      } if(isset($get_user)) {
          return $get_user;
        }else {
        return 0;
      }
    }


Difference between strongarm, field base, and field instance What is the difference between the following options when using features? What is each of them for and an example of why each would be used.

strongarm
field base
field instance

To make things even more complicated, there are often "field bundle" variables listed for strongarm to use.

A Drupal 7 database contains various structural configuration. Some of these are:

Entity bundles, e.g. node types or taxonomy vocabularies.
Field bases: These are definitions of fields that apply across bundles and entity types, wherever the same field is used.
Field instances: These describe how a field is used for a specific entity bundle.
Field display configuration per entity bundle and view mode. This gets even more with Display suite.
General global key/value settings, stored in the variable table, which can be accessed with variable_get() and variable_set(). These are exported to features with strongarm.

Unfortunately, this entire system is a bit "dirty": Some of the structural configuration for fields and entity bundles is stored in the variable system, and not together with the field or entity type.

Therefore, whenever you export an entity bundle (e.g. node type) with features, you will also see some strongarm stuff. This is annoying and messy, but it is not avoidable.

I would recommend to maintain

One feature containing all field bases.
One feature per node type, with all field instances and field display configuration for this node type. This will also contain a lot of strongarm stuff.
Another feature for general strongarm settings, that are not related to anything else.
And more.

As far as I remember, drush features-export myfeature node:mytype already adds all the field instances and strongarm stuff for this node type.

Ideally you also have a naming pattern such as mysite_ft_* for all features, and mysite_ft_ct_* for all content type features. Also organize your sites/all/modules into contrib/, custom/, features/.

So in conclusion: You don't have a choice to pick either field base or field instance or strongarm. Instead, you usually want to export everything that you want to sync between your local environment and the dev, staging or live environments. The only choice is which of those things should live in the same feature, and which parts should live in different features.


Custom taxonomy; link with two content types I've successfully created a new content type ("my_type") and added a taxonomoy into it.

How can I combine this new taxonomy also with the default content type "post", so that I can select it in the default content type backend?

Drupal 7

Go to Structure > Content types, select "Manage fields" for the post content type. Either add the existing taxonomy field to it or add a new one. For a new one, choose which vocabulary should be used for this field.

Drupal 6

Go to Admin > Content > Taxonomy, edit your vocabulary. Then under content types, select the content types for which this vocabulary should be displayed.


How to save a free text views query entered into an exposed filter by the user? I would like to save the entered exposed filter text by the user possibly into its own content type. Would I have to look at the url path for this via $_GET vars?

Use hook_form_alter and add an extra submit handler:

$form['#submit'][] = 'my_callback';

In your callback function use node_save to save the values you extracted from $form_state['values'];


How to use RegexConstraint with field? I'm defining a base field for my custom content entity:

$fields['machine_name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Machine name'))
  ->addConstraint('UniqueField')
  ->addConstraint('Regex', ['pattern' => '[^a-z0-9_]+'])
  ->setTranslatable(false)
  ->setRequired(true);

However RegexValidator throws UnexpectedTypeException complaining that passed value is of type FieldItemList. This is obvious since in Drupal 8 even single value fields are lists (with one item).

So how can I use Regex validator with entity fields? Or do I have to write my own regex validator that will handle FieldItemLists?

You do not need to create your own Validator. Instead, use setPropertyConstraints instead of addConstraint to attach the Regex validator to the individual property of the field rather than the FieldItemList. For a string field, add the constraint to "value." For a link field, you may want to add it to "URI," etc. Here is an example:
->setPropertyConstraints(
  'value', ['Regex' => [
    'pattern' => '/^[0-9]+$/',
    'message' => t('Please use numbers only in the blah field.'),
  ]]
);


How to use Message Subscribe module? I have installed Message Subscribe module. But I am not sure how to configure this. I also have installed all the required modules. I can see the Message Subscribe UI but there is nothing I can configure.

Does anyone have any experience with this?

The Message Subscribe module is part of the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Just looking at the available documentation it's not obvious to get going with it. But if you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.


Get the raw URL of an image in views-view-table.html.twig In the views-view-table.html.twig template, I can get the raw values of fields by repeating on rows and accessing the view object. For example:

    {{ view.field.title.value(view.result[i]) }}   {# the title of the node in this row #}
    {{ view.field.field_link.value(view.result[i]) }}   {# the URL in the link field #}

With Formatter for an image field set to URL to image in the view, I can test to see if an image exists in the field by doing:

    {% if view.field.field_image.value(view.result[i]) %}

QUESTION: How can I get the raw URL for the image? If I use:

    {{ view.field.field_image.value(view.result[i]) }}

I get a number as output. I have tried:

    {{ view.field.field_image.value(view.result[i]).entity.uri.value }}   {# I get nothing #}

and various combinations of things, but haven't hit the right one.

I know I don't have to use the raw values. For example, I can use

    {{ row.columns.field_image.content|render|striptags|trim }}

to get the URL, but this seems like a lot of processing to get something that must be available in the raw result.

Thanks to all, especially @belltouche and @Jaypan, for taking the time to respond. After all the kind suggestions and lots of reading and trial-and-error, I ended up using the following code in views-view-table.html.twig to display an image URL:

{% for i, row in rows %}
  ...
  {% if view.field.field_image.value(view.result[i]) %}
    {{ row.columns.field_image.content|render|striptags|trim }}
  {% endif %}
  ...
{% endfor %}

Note that I'm using the URL to image formatter for the image field in the view.

To explain, view.field.field_image.value(view.result[i]) gets the raw value of the image field, which turns out to be the entity id for the image. Checking it makes a concise test to see if there is an image in the field (if there's a better way, please say so).

It also turns out that there isn't any other information about the image in the raw value. Just the entity id, which is why I could never find the image URL in the raw value.

There was a suggestion made that I could use Twig Tweak to load the image entity by its id and get the URL from it. I'm sure this would have worked, but since my purpose was to avoid the overhead of render|striptags|trim processing, loading the entity after it had already been loaded to produce the content didn't seem an advantage.


How to change link in a view depending on state of a certain field I have a content type called conference, there are two types of conferences; supported and unsupported.

Supported have their own node inside Drupal, unsupported link out to external websites rather than having their own node. Supported also have the same external link.

There is a field selection for this in the conference content type so the user picks whether a conference is supported or unsupported.

Now I have a view of conferences and their title is a link. However I need to check whether each conference is supported or unsupported, as this link will either be a link to the node or a link externally.

Looking for any suggestions on how to achieve this, I'm guessing views PHP would achieve this, but is this the best option?

You can use the field token of the field which is used to picks whether a conference is supported or unsupported. Then you can link it to a node or external link,


Add location to to profile2 just after the user registers I am trying to force add a location to a user's profile2 just after the user register's an account. The user's are able to add locations to their profile by using flags, but since there are no locations just after the user registers, the rules add fails because the locations list has not been initiated.

The below code is what I currently have:

if (isset($account->is_new) && !empty($account->is_new)) {
  function user_account_presave_user_presave(&$edit, $account, $category) {
    global $user;

    // Load profile2.
    $profile = profile2_load_by_user(array('type' => 'next', 'uid' => $user >uid));

    // Add in the necessary custom fields and values.
    $profile->field_next_destination['und'][] = array(
      'longitude' => '0.0',
      'latitude' => '0.0',
    );

    // Save the profile2 to the user account.
    profile2_save($profile);

  }
}

I am not sure if the IF statement should be in the Function, but if it is not, the Function fails to allow users to register because the CAPTCHA reuse attack function is triggered.

Has anyone ever run into this?

Thank you!

Try using hook_user_insert instead. The $account will have $account->uid set at that stage.

P.S wrapping hook_user_presave in that condition looks wrong and probably won't work with the hook registry cache.


Display a field only when dependee image field has more than three images I have a content type "Product", and on its view node, I want to display a field(which is a select list), only when my other field, which is dependee for this field and is an image field, contains more than three images.

Any suggestion will be appreciated.

You can do this by using Conditional Fields module.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new States
  API, plus the ability to modify fields appearance and behavior on
  certain conditions when viewing content.

How to use ?


How can I create logo for each user I want each user to create their own site-logo. This is not multi-site, this is a single site only. How can I do it?

Add a field to the user profile and use this as a replacement for the logo. Use the page_preprocessor to add the user logo to the page template. Replace the logo by the one the user provided or show a default one.

Read more about this:

template_preprocess_page
Setting up variables to use in a template


Embedded views into another view via twig_tweaks, but the results only update after clearing drupal caches I have a view that needs to embed child views, which I did using the twig_tweaks module to insert the child view as a field in my parent view, by using a custom text field:
{{ drupal_view('my_child_view', 'block_1', arguments.null, tid) }}

The first argument arguments.null is the group id, which the child views get from the URL
example.com/group/58/parent-view
It all works perfectly when i view the results for a given group id. However, when I then open the view for another group id, I get the results for the first queried group id. The results will only change after i delete the Drupal caches. Then I can display the view correctly for any group id, but afterwards, it will again never change the results.
My best guess is that the results of the embedded view are cached? Is there any way to disable this? I tried including {'#cache': {'max-age': 0}} into the custom text embedding the child view, but this did not help either.

Use the Views Field View module instead.

There are a lot of cases in views where you want to embed a list inside each row. One
example could be, you have a list of groups, and for each groups you
want to list the first and last name of all of their members.

Then in the Views UI add view embed as field.


Use product entity field as filter in Views I have a product (type: "lamp") with a text field called "power".
On the Product display node ("showcase") i also want to see a block made with Views. It must show three other products of the same type AND power value. So Views should get a field's value of product rendered on the same node.
I've tried a lot of modules, various relationships combinations, but still can't get a product's entity field value.
Please tell me, what modules do i need and where should i go step by step.
(here are the modules i've installed: References, Entity Reference, Field reference, Node Reference, Field collection)

I recently learned how to do this kind of thing.

You need Page Manager which comes as part of Chaos Tools for d7, and Panels.

In Page Manager, enable and edit the path /node/%node
Set the selection criteria to node-type = showcase
Create a context based on the entity reference field, or if that doesn't work you might need the Relation module.
Create another context based on the power field (you might like to use a taxonomy for that)
Make a view that uses the context to choose the products to display
Back in page manager, under Content, use Panels to determine where and how you want node and the view to display.

Follow the first link ("learned") for a much more thorough tutorial.


The test:run command is missing, but other commands work fine I installed Drupal Console, put it on my path, ran drupal init, and  successfully used Drupal Console to generate a module.

Now I want to run tests with drupal test:run, but I get this error.

  [ERROR] Command "test:run", is not a valid command name.

drupal lists many commands, but it is missing the ones for tests. This is a sample of the list.

 state
  state:delete (std)                      Delete State
  state:override (sto)                    Override a State key.
 taxonomy
  taxonomy:term:delete (ttd)              Delete taxonomy terms from a vocabulary
 theme
  theme:download (thd)                    Download theme in application
  theme:install (thi)                     Install theme or themes in the application
  theme:path (thp)                        Returns the relative path to the theme (or absolute path)
  theme:uninstall (thu)                   Uninstall theme or themes in the application
 update
  update:entities (upe)                   Applying Entity Updates
  update:execute (upex,updb)              Execute a specific Update N function in a module, or execute all
 user
  user:create (uc)                        Create users for the application
  user:delete (ud)                        Delete users from the application

Why are the commands for tests missing?

You need to enable Drupal Test module, then run drupal cache:rebuild, and command test:run will appear.


jQuery only effecting first node in slideshow I have applied a jQuery plugin [textfill][1] to certain elements within my a view and a view-slideshow. I have locally linked the relevant .js file via the .info file.

In the view-slideshow the first node is only effected
However in my other view all nodes are.

Within the views-slideshow i have attached the jQuery targeted class '.textfill' class through the views 'global: custom text field' and have added a div to the corresponding replacement pattern. With the normal view i have attached the class to the desired field via the corresponding field tpl.php file.

Here's what it looks like:
http://imgur.com/a/I4VV4/

This is the plugin:

; (function($) {
$.fn.textfill = function(options) {
var defaults = {
  debug: false,
  maxFontPixels: 40,
  minFontPixels: 4,
  innerTag: 'a',
  widthOnly: false,
  callback: null,
  complete: null,
  explicitWidth: null,
  explicitHeight: null
};
var Opts = jQuery.extend(defaults, options);

function _debug_sizing(prefix, ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels) {
  if (!Opts.debug) {
    return;
  }

  function _m(v1, v2) {
    var marker = ' / ';
    if (v1 > v2) {
      marker = ' > ';
    } else if (v1 == v2) {
      marker = ' = ';
    }
    return marker;
  }

  console.debug(
    prefix +
    'font: ' + ourText.css('font-size') +
    ', H: ' + ourText.height() + _m(ourText.height(), maxHeight) + maxHeight +
    ', W: ' + ourText.width()  + _m(ourText.width() , maxWidth)  + maxWidth +
    ', minFontPixels: ' + minFontPixels +
    ', maxFontPixels: ' + maxFontPixels
  );
}

function _sizing(prefix, ourText, func, max, maxHeight, maxWidth, minFontPixels, maxFontPixels) {
  _debug_sizing(prefix + ': ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  while (minFontPixels < maxFontPixels - 1) {
    var fontSize = Math.floor((minFontPixels + maxFontPixels) / 2)
    ourText.css('font-size', fontSize);
    if (func.call(ourText) <= max) {
      minFontPixels = fontSize;
      if (func.call(ourText) == max) {
        break;
      }
    } else {
      maxFontPixels = fontSize;
    }
    _debug_sizing(prefix + ': ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  ourText.css('font-size', maxFontPixels);
  if (func.call(ourText) <= max) {
    minFontPixels = maxFontPixels;
    _debug_sizing(prefix + '* ', ourText, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  return minFontPixels;
}

this.each(function() {
  var ourText = $(Opts.innerTag + ':visible:first', this);
  // Use explicit dimensions when specified
  var maxHeight = Opts.explicitHeight || $(this).height();
  var maxWidth = Opts.explicitWidth || $(this).width();
  var oldFontSize = ourText.css('font-size');
  var fontSize;

  if (Opts.debug) {
    console.log('Opts: ', Opts);
    console.log('Vars:' +
      ' maxHeight: ' + maxHeight +
      ', maxWidth: ' + maxWidth
    );
  }

  var minFontPixels = Opts.minFontPixels;
  var maxFontPixels = Opts.maxFontPixels <= 0 ? maxHeight : Opts.maxFontPixels;
  var HfontSize = undefined;
  if (!Opts.widthOnly) {
    HfontSize = _sizing('H', ourText, $.fn.height, maxHeight, maxHeight, maxWidth, minFontPixels, maxFontPixels);
  }
  var WfontSize = _sizing('W', ourText, $.fn.width, maxWidth, maxHeight, maxWidth, minFontPixels, maxFontPixels);

  if (Opts.widthOnly) {
    ourText.css('font-size', WfontSize);
  } else {
    ourText.css('font-size', Math.min(HfontSize, WfontSize));
  }
  if (Opts.debug) {
    console.debug('Final: ' + ourText.css('font-size'));
  }

  if (ourText.width() > maxWidth || ourText.height() > maxHeight) {
    ourText.css('font-size', oldFontSize);
  }
  // call callback on each result
  if (Opts.callback) Opts.callback(this);
});

// call complete when all is complete
if (Opts.complete) Opts.complete(this);

return this;
};

})(jQuery);

this is my other .js file

jQuery(function(){
   jQuery('.textfill').textfill({ maxFontPixels: 200 });
});

i also should note that i am a relative beginner to drupal aswell as using stackerexchange

If you are trying to affect all nodes within the view, why not iterate over all the nodes using jQuery to add your class? Ex.: $('selectors for nodes inside view').addClass('textfill'); This is like calling .each(), except the iteration is implicit. Then, after you search the DOM and add the classes you want, call $('.textfill').textfill(); .


Hide fields on the user profile page with preprocess function On the user profile edit page I can do something like this in my theme's template.php file to hide a field:

function MYTHEME_form_user_profile_form_alter(&$form,$form_state,$form_id){
//remove unwanted fields from the form (default value is still saved)
  $form['timezone']['#access'] = FALSE;
}

On the profile view page, I am trying to do a similar thing. I want to hide:

History
Member for 3 months 4 weeks

So I looked up the api function and it's hook_user_view

Based on this I try:

function MYTHEME_user_view($items) {
$items['member_for']['#access'] = FALSE;
}

... however, this does not work after I clear the cache. I'd also like to avoid hiding this using CSS display:none.

You do not need to use any preprocess functions tbh :> its pretty simple
Go to Home » Administration » Configuration » People » Account settings » Manage Display , History -> Format  chose hidden.


Shortened Drush option I am trying to write a shortened Drush option - we want to have an option for both --force as well as -f

I'm searching everywhere and not seeing any documentation, but it seems like something like it is supported based on this page:

https://groups.drupal.org/drush/commands

What I've got so far:

function parsexml_drush_command() {

  $items['parsexml'] = array(
    'description' => 'Parses XML from an XML feed.',
    'aliases' => array('pxml'),
    'arguments' => array(
      'path' => 'Path to the XML file.',
    ),
    'options' => array(
      'force' => 'Flag to force processing of previously processed XML files.',
      'f' => 'Shortened flag to force processing of previously processed XML files.',
    ),
  );

  return $items;
}

But my guess is that that isn't correct.

What is the correct way to have multiple aliases per option? I can only find how to set the alias for a given drush command.

Sorry, Drush reserves all short (-f) options for use exclusively by Drush core.  You cannot define them in contrib extensions.

See the function drush_get_global_options for an example of how to define options that have attributes; the short option is 'short-form', although this does not work right for non-Core commands.


How to know when a node is going to be deleted when using Rules Event "Before saving content"? I'm using a rule with Rules Event "Before saving content", but this rule is also executed when I delete the node.

I'm recalculating some fields, I don't need to do this when the node is going to be deleted.

How can I know when the node is going to be deleted? I'm coding the rule with hook_rules_action_info.

Have a look at this rule (in Rules export format):

{ "rules_before_saving_content_but_not_when_deleting" : {
    "LABEL" : "Before saving content but not when deleting",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "The path of the content being saved = [site:current-page:path]" } }
    ]
  }
}

If you request an edit a node (say with nid=71) your path will be node/71/edit. If you then save the node by hitting the Save button, the above rule will show a Drupal message like so:

The path of the content being saved = node/71/edit

If you request an edit a node (say with nid=72), your path will be node/72/edit. But if you then decide to delete (instead of save) the node by hitting the Delete button, then no Drupal message (similar to the previous scenario above) will be shown.

This (rather basic) Rules debugging scenario, leads me to believe that, out-of-the-Rules-box, Rules Event Before saving content does NOT get triggered when a node is deleted. So whatever problem you are experiencing (when a node is deleted), it must be because of something else happening in your site, in your custom rule, or your custom code of your rule. If I was to further investigate your issue, I'd start "Rules debugging", as explained in the answer to "How can I display the value of a variable inside a condition?".

PS: a quick-and-dirty workaround for whatever issue you're experiencing, might be to check the results you get by adding an extra Rules Condition to check if the (saved) node will still have status "published" (assuming a deleted node is no longer marked as "published").


Some of my Panel content is missing for anonymous users. What went wrong? I've set up a landing page panel with two items in it, a content page with a welcome message and a view showing certain content. It works great, but when I look at it as an anonymous user only the view is showing up, not the welcome page message.

I haven't put any special access conditions and my only variant is the landing page and I can see all the content in the preview, so I don't understand why it isn't visible to everyone. The welcome message is on a published page as well, and caching is disabled for that panel for the moment.

Ok, it was a caching issue after all. >.<

I'm not sure which caches Panels uses, but the very handy Administration menu's flush all caches link seems to have fixed the problem.


How to create a custom text input filter? I am using plain text format. I want to create an input filter for when a user enters #15, it should be converted to a link pointing to the post #15. I want to do this for the Statuses (Social Microblog) module. The link of an individual status is like this: https://www.example.com/statuses/15.

Just for your reference, I found a snippet. It is specifically for nodes though, which was meant to be used with custom filter module.

My question: How to create such filter for statuses?

Take a look at the Custom Filter module.

  This module allows you to create content filter using regular expressions. Instead of creating a new module for each filter you need, now you can easily create and organize your own filters. Your filter will appear in the input format configuration page.

If you want to do it yourself in a custom module, you can implement hook_filter_info


Contact attached to every node of a particular type I am trying to figure out how to attach one form to every node of a particular content type in Drupal.

Each node will be owned by a different user and the form will be sent to the user who created that node.

The closest I have got is with Webform and Webform Templates. However, It makes the user choose the template to use. I don't want that I want it to be set automatically and I can't see how it can be?

Any suggestions would be greatly appreciated.

Try installing Form Block module which give you possibility to expose a form as a block. And you can configure appearance of that block on every node of a particular content type.

  To enable adding of a form to a node, select the option "Enable data
  entry from a block" in the admin configuration page for a given
  content type. Visit the block administration page and enable/configure
  the block for the form.


Is it okay to expose .yml or .install files to public? As per my knowledge the static files like css/js inside core/modules etc should be read by http server user. So normally I give read permission recursively to http user for directories like core, theme, modules etc. But these directory contains some .yml or .install files e.g drupal/web/core/modules/user/user.install which gets downloaded automatically when someone visits my site example.com/core/modules/user/user.install .

So is it okay to expose those files to public ? and what steps can be taken to avoid it ? I checked some popular sites they also expose those files. So bit confused.

Note: Drupal default .htaccess may take  care of these thing for Apache server only but what about other servers like nginx ? However I think Drupal is hard coded to be used with Apache server only.

No.

The web server (e.g. via apache's  directive) needs to be able to read (not write) the index.php file (and occasionally others such as update.php), and also static files such as .css/.js, pdfs and images.

The php interpreter is not limited by  directives and so most other files required by php do not have to be visible.

As Hudri said, leave the .htaccess files as they are, configure the server to notice them (AllowOverrides) and refer to an appropriate guide, such as:
https://www.drupal.org/docs/develop/local-server-setup/linux-development-environments/installing-php-mysql-and-apache-under


How to set the language to Swedish when users visit example.se and to French when visiting example.fr? I have a Drupal 7 website in 18 languages. The main URL is example.com and 18 other international domains are domain aliases of the main URL (example.de, example.fr, example.se, ...).

The Language detection and selection feature in Configuration currently selects the language based on the path of the URL (example.com/de, example.com/se, ...) but not based on the actual URL extention (example.de, example.se, ...).

How can I set the language to Swedish when users visit example.se and to French when visiting example.fr?

Thanks in advance!

Kind regards, Jan

On admin/config/regional/language/configure/url change the Part of the URL that determines language to Domain.

Then set up domains to all languagues: admin/config/regional/language/edit/LANGCODE


How do I create a variable that my page.tpl.php file can access? In Drupal 7, I have a module that implements hook_node_load. It creates a variable that I'd like to make use of in my page.tpl.php file. Let's pretend it is the count of nodes that are of the same type as the currently loaded node. As of now, I'm just making the variable global, like so:

global $node_count;
$node_count = db_query("SELECT count FROM {node} WHERE type = :type", array(":type" => $node->type"))->fetchAll()[0]->count;

Then, within my page.tpl.php file, I have to do something like the following:

global $node_count;
echo "<p>$node_count</p>";

I know that there is a way to make my $node_count variable in scope, in the same way that $node or $user are. The tutorials I find on the subject seem to involve rewriting the entire theme function - I'm not trying to do anything that complicated. Is there a simple way to just make this variable in scope in my .tpl.php files? Something like a function?

In Drupal theming, template preprocess functions are the functions that prepare the variables that can be used in a certain template. Template preprocess functions are executed one after another and they pass around an array with all variables. You can add your own in your theme's template.php, in the form of function THEMENAME_preprocess_TEMPLATENAME(&$variables) { // Your code here. }.

If you're adding a value to a node object in a hook_node_load implementation, that probably looks something like this:

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->myvariable = 'somevalue';
  }
}

Now you want to access $node->myvariable in your page.tpl.php. For this, you don't even need to write a preprocess function, because Drupal already adds the current node object to the variables by default. (This happens in template_prepocess_page.) This means that you can simply add this to your page.tpl.php:

<?php if ($node->myvariable): ?>
  <div class="myvariable">
    <?php print $node->myvariable; ?>
  </div>
<?php endif; ?>


Select on which page a view has to be display I am new to the Views module in Drupal 7. I enable the Taxonomy Term view and customize it a bit. For now the view is displayed in the default page of my theme in the main content region. But I would like this view to be displayed in a custom page defined by my theme on a particular region.
It seems to be an easy task but I can't figure how to do that.

It is easy, Edit your View and Click on Add (A popup near upper left) and choose Block

This newly created block will inherit all the settings from your existing view display.

You can Override any setting for your block display.

Choose appropriate template relevant to block following Theme: Information

Save your view and head on to block listing page to adjust your newly created block.