How to add page argument in hook_menu for dynamic callback function? I'm using groups for my website and I would like to create functions that will work for every group.
I've created a tab configuration for every group like this.

$groups = group_load_by_type('community');
foreach($groups as $key => $value) {
  $items[CONFIG_GLOBAL_ADMIN_PATH . '/groups/' . $key] = array(
    'title' => $value->title,
    'description' => 'Group ' . $value->title,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('myModule_group_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'myModule_group.admin.inc',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1,
  );
}

It's working pretty well this way, I have the config for all the groups at the path/groups/groupID which is what I want.

But I would like to add an argument to my function myModule_group_setting_form($form, &$form_state) and do something like this:

'page arguments' => array('myModule_group_settings_form', $key->title),

and change my function to this :

myModule_group_setting_form($form, &$form_state, $groupName)

In my function, I'm using variables so the groups can hide some informations if they want.
Actually if I want to do this, I have to create a function for every group and do something like this :

'page arguments' => array('myModule_group_' . $key->title . '_settings_form'

And I have to create a new function every time I have a new group. Since I don't have static groups, and I may have to create others in the future, this way doesn't suits me.

Thanks for your help :)

You are creating a new menu for new group. It will be better to use dynamic arguments.

$items[CONFIG_GLOBAL_ADMIN_PATH . '/groups/%'] = array(
  'description' => 'Some Group Description',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('myModule_group_settings_form', 3),
  'access arguments' => array('administer site configuration'),
  'file' => 'myModule_group.admin.inc',
  'type' => MENU_LOCAL_TASK,
  'weight' => 1,
);

and In your function :

function myModule_group_setting_form($form, &$form_state, $key) {
  $groups = group_load_by_type('community');
  $value = (isset($groups[$key])) ? $groups[$key] : NULL;
  if (!$value) {
    drupal_set_title($value->title);
    // Whatever you do with $value->title;
  }
  else {
    drupal_not_found(); exit();
  }
}


What happened to the og-list view in organic groups? The new version of Organic Groups (7.2) does not have a the view og-list, which used to display a list of all the groups. Any idea why it was removed and how to get the list of all groups?

I don't know why it was removed, but here's a sample view you can import and tweak as needed. To import, go to /admin/structure/views/import.

$view = new view();
$view->name = 'og_list';
$view->description = 'A list of all Organic Groups';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'og list';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'All Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
$handler->display->display_options['row_options']['links'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group' => 'group',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'og-list';
$translatables['og_list'] = array(
  t('Master'),
  t('All Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Page'),
);


admin content filter is there a way in Drupal-7 to add form search in the content page filter
or add text box in the filter form for filter the nodes by node title
beside the type of node and publishing property

The Admin menu module has a nice sub-module called 'Administration views" which replaces Drupal core content management page with a view. It also adds extra filters and a search function.


How do I use a token to set the default value of a date field to the current date? When I go to the build tab of the webform and click edit on the date element, I can find the default value setting under the advanced tab in the element editor. The help text says I can use tokens, but I'm having trouble making a token work there. (I'm trying to use the [current-date:html_date] token).

If I click "set default value", another dialog opens with a text input and a button that says "update default value". But when I click that button after putting the token into the input, it goes back to the advanced tab and the default value input is empty. If I enter the token before clicking "set default value", the "update default value" dialog opens with an empty input. I've tried various combinations/orders and can't get the token to stay there. It doesn't matter if I type it in, copy/paste it, or fill it using the "browse available tokens" tool.

Leave the "set default value" button alone. Something about it makes it seem like a really good button to click for setting a default value, but you don't need it. Just enter the token in the default value input on the advanced tab and click save.

This seems simple enough in hindsight, and I'm not sure why it took so long for it to occur to me to try it. Hopefully if someone else has the same problem, this answer can help save them a few minutes, or perhaps even a longer period of time we won't mention here.


How to transfer field location inside a div? I am looking for a way to transfer the location of the field created programmatically inside a div created by field_group module.

Can anyone help me to achieve this?

Thank you.

I was able to achieve this using javascript:

<script>
$("#edit-field-date").appendTo("#detail-wrap");
</script>

But I am still looking for a way to do it under form_alter.


How to add Attributes to the input tag of a field I am trying to find out how to modify a text input for one field of a quiz so that I can disable spellcheck.

Can I create a .tpl.php and add it to my theme folder to override it?

At the moment, it looks like the following:

<input autocomplete="off" type="text" id="edit-question-832-answer" name="question[832][answer]" value="" size="60" maxlength="256" class="form-text">

I simply with to add the following attributes to just that one field.

<input autocomplete="off" autocorrect="off" autocapitalize="off"  spellcheck="false"/>

I have looked inside modules/field/theme/field.tpl.php but do not see a way to modify the way text input fields are handled.

Which file am I supposed to edit to make this happen for a specific field?

Thank you.

If you can write your own module, you can implement the hook_form_alter:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_form_i_want_to_change') {
    $form['the_field']['#attributes']['autocorrect'] = 'off';
    $form['the_field']['#attributes']['autocapitalize'] = 'off';
    $form['the_field']['#attributes']['spellcheck'] = 'false';
  }
}


How to handle URLs like node/%.atom? I am writing a module to generate a custom Atom feed, and I want to create URLs like http://drupalsite/node/20.atom or http://drupalsite/content/nodealias.atom.

I was trying to implement it as follows, but of course it is not correct.

$items['node/%.atom'] = array(
        'title' => 'atom node feed',
        'page callback' => 'atom_node_feed',
        'page arguments' => array(1),
        'access callback' => 'user_access',
        'access arguments' => array('generate atom feed'),
        'type' => MENU_CALLBACK
    );

Is it at all possible to create URLs like this in Drupal?

The code you wrote doesn't work because you are using a placeholder in the definition of the menu callback; such placeholders can be of two types:

anonymous placeholder. The placeholder is just %, which matches any string.
named placeholder. In this case, the placeholder is similar to %node, %user, used from Drupal core modules. If the placeholder is, for example, %node, Drupal will look for the node_load() function, and will pass it the string that in the path replaces the placeholder; when the function returns FALSE, then Drupal will return a 404 error page to the user. As the string following the % is used as name of the load function, to which the string "_load" is appended, characters that are not allowed in a function name are discarded (PHP cannot have a function with a name like .atom_load().

If your purpose is to define a menu callback for your module that returns an atom feed for the node, then I would define the callback as the following:

$items['node/%node/atom'] = array(
  'title' => 'atom node feed',
  'page callback' => 'atom_node_feed',
  'page arguments' => array(1),
  'access callback' => 'user_access',
  'access arguments' => array('generate atom feed'),
  'type' => MENU_CALLBACK,
);

The page callback will get the node object as first argument, not the node ID.

To create a path like http://drupalsite/node/20.atom, you need to create a path alias.
You can assign path aliases using the administrative page at admin/config/search/path (Drupal 7) or admin/build/path (Drupal 6).
Using Drupal 7, a module can create a path alias calling path_save().
You can also use Pathauto to automatically set path aliases for nodes. The module uses tokens that allows to dynamically create path aliases that follows a defined schema. As far as I know, node path aliases are just set for paths like node/1; the path alias is not set for a path like node/1/edit, or node/1/atom.


This form was missing from the server cache on Drupal 8 On my site I do this:

I got a form with this field:

'myfile' => [
  '#title' => $this->t('MyTitle'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://myfolder',
],

And MyController:

$myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myclassform]');

This variable I pass to Twig template.

On my template:

{{ myform }}

Every is ok.

But when the page is cached I got this error when i upload a file:

An unrecoverable error occurred. Use of this form has expired. Try reloading the page and submitting again.

I dont use memcache or CacheRoute, only drupal cache for anonymous user.

How I fix that?
Is possible not cached the form?

I fixed that prevent that drupal cached the page, this way, because the forms can't be cached:

// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

EDIT:

Recently was commited Add #cache[max-age] to disable caching and bubble the max-age

When $build['#cache']['max-age'] is not set, permanent cacheability (Cache::PERMANENT) is assumed.

To indicate that a render array is not cacheable at all, set $build['#cache']['max-age'] = 0 (i.e. zero seconds).

And to indicate that a render array is cacheable only for a limited amount of time, e.g. 5 minutes, set $build['#cache']['max-age'] = 300; // 5 * 60 = 300.


How to re-write/rename HTML output of a View Block wrapper ID? Drupal newbie here. Would like to know how do I change the HTML wrapper ID of a View Block?

Currently I have a view that has two blocks.

The first block is the "Do's" block.
HTML output:

The second one is a "Don'ts" block.
HTML output:

I would like to rename the "id" of the second block to make it more intuitive.

Screenshot: https://img.skitch.com/20120430-p8dtxdx7h8qa5augidx9gudjbn.jpg

How to do that? Thanks!

Go to you view select block display "Do's" then Advanced -> OTHER -> Machine Name change this and it''ll change the id of your block.


How to make custom end user text in a form available for editing for a e.g. editor role? Within a form build in a custom module trough the form api I'm using pieces of text (eula, help, hints) of which some of them need to be editable by my client (editor role).

For example:

$form['eula'] = array(
  '#type' => 'radios',
  '#title' => t('This text need to be editable. I agree to be bound by bla bla bla.'),
  '#options' => array('Ja'=>'Ja / Yes'),
  '#required' => TRUE,
);

I want to facilitate a central point where those text strings (like #title) can be edited and a way I can retrieve them in this custom module.

What's best practice for this scenario to do so?
Create a content type for this or perhaps use variable_set/get?

Basically I want one location where my client can edit all those text strings.
To use a content type for this and node_load() everytime feels a bit too much.

Thanks in advance

As long as the string or text is passed via t() function you can override it using String Overrides module. Here is a quote from module's project page:

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

UPDATE
You can also use Variable module. Quote from project page:

... provides a registry for meta-data about Drupal variables and some extended Variable API and administration interface.
This is an API module so it must be installed only when other modules require it.


Drupal 8 and jQuery 3 support I'm trying to implement the jquery chosen library with the image-select plugin in Drupal, but i can't get the element to render correctly. The example page uses jquery 3 and Drupal 8 does not.

Did some reading but i still wonder about:

At what point will Drupal 8 support jQuery 3?

There is an ongoing discussion in Drupal.org forums:

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

According to the latest answer on that thread: to be expected in 8.4

Best regards,

Oleg


Override theme template from module without implementing a theme I have a project on D8 where I don't use any custom themes, I use default seven theme for everything because there is no need of any visual theming.

So My question: Is it possible to override theme template using module? without implementing theme at all?

I have a case where I want to add custom third party generated value in node's template.

This is what I have done:

Implemented custom template:

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'video_teaser' => [
      'template' => 'video_teaser',
      'variables' => NULL,
    ]
  );
}

Implemented hook_theme_suggestions_alter:

function MY_MODULE_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if(in_array('node__teaser', $suggestions)){
    $suggestions[] = 'video_teaser';
  }
}

And this, works, instead of default template, my video_teser template is used.

BUT: I have a problem passing default node variables to my custom template, they aren't passed automatically and I couldn't find the way to do this using current approach.

You can do this in hook_theme() with the base hook 'node':

function MY_MODULE_theme($existing, $type, $theme, $path) {
  return [
    'node__video_teaser' => [
      'template' => 'node--video-teaser',
      'base hook' => 'node',
    ],
  ];
}

You don't need to define the base hook. Drupal can discover this automatically. What's important is that you use the double underscore, because this works exactly like the theme suggestions. After Drupal found the base hook it will clone the preprocess functions of this hook and will provide the variables for the node.


taxonomy cck pathauto Can anyone tell me how to set the taxonomy in the following order

super Category---eg(Area)
Category--- eg(food)
sub category --- eg(fruits)

if a visitor chooses a super category area, then the fruits in that area should be shown
 And the path should be http://www.example.com/supercategory/category/subcategory/apple.php

It seems that you're asking more than one question, but let me try and address the paths one. If you organise your taxonomy to be hierarchical then using the token [catpath-raw] will give you the path you require.


Need Module for Images/Video in Node, works with Views I'm using d7.2. I have been searching and working on this all day- can't figure it out. So I'm posting here for some help...

I have a Node that I want the users to be able to upload images and/or video to. They can upload either or BOTH if needs be. They can upload a single image, multiple images, single or multiple videos (3rd party hosted- you tube, vimeo, etc), or a combination of images and video.

I'd like for it to be displayed in a nice looking format- kind of like gallery formatter does (can't seem to get that to work for me)  with a larger image on top/middle, and thumbnails of the others on the side or bottom.  When the user clicks on the larger image, it'll open in lightbox.

I need it to work with views, as I'll be attaching a voting module to it, as well as others that will implement with Views.

I am really stuck and frustrated on this one. There doesn't seem to be any solid modules that can handle this- unless I'm just not seeing it.

I sincerely appreciate any/all help!

For handling the video, check out the Media module or the Video module.  These will allow you upload, manage, and reuse video files.

For images, these features have been put into Drupal core, so you shouldn't need an extra module for uploading, managing, and displaying images.

Once set up with that, you can theme the display of the fields and if you choose, add other modules (such as Lightbox2) to enhance the user's experience).


MySQL dump file installation I am working on replication, and I am stuck on MySQL dump. I want to know if there is the need of installing MySQL dump (I just have mysql community ed: version 5.5 on both servers)
because I am stuck on executing dump command. On Google I did't find any solution.

mysqldump should just come bundled with MySQL. Have you tried running it from the command line? If you don't have/can't find mysqldump you should be able to use phpmyadmin to do export/import.


Unable to save content language configuration My Drupal 8 website is multilingual and has many entity type bundles for nodes, taxonomy terms, paragraphs, media et cetera. This leads to a content language settings form (admin/config/regional/content-language) with more than thousand translatable-checkboxes.

Currently I'm not able to save this form. In the first place the form seemed to be successful submitted but changes have not been saved. This was caused by insufficient php setting value for max_input_vars, which could be solved by setting it to 6000. Now I'm struggling with a timeout. After submitting the form the request fails after some minutes.

Here are the php settings of my Drupal VM:

php_version: "5.6"
php_memory_limit: "1024M"
php_realpath_cache_size: "1024K"
php_opcache_enabled_in_ini: true
php_opcache_memory_consumption: "192"
php_opcache_max_accelerated_files: 4096
php_max_input_vars: "6000"
php_max_execution_time: "720"
php_post_max_size: '64M'

How can I get around this issue? Which resource bottleneck could cause this?

I tried the max_input_vars fix and that didnt work (i have alot of custom entities on the page and was hoping this would work).
I had to check the entity, pretend it was called MyCustomEntity in 'Custom language settings' at the top... but also scroll down to the individual MyCustomEntity settings further down on the page, and also check that checkbox. When I saved, now it worked


Get a single date value from a date field on a node with entity_metadata_wrapper() I want to retrieve a date value from a date field attached to a node with entity_metadata_wrapper.

So far:

$node_wrapper->field_tournament_date->value();

Provides an array. Not many other methods work. So, I have to do:

$date = $node_wrapper->field_tournament_date->value();
$start_date = format_date($date['value'], 'short');

Is there a cleaner way of getting the value of a date field without breaking it up like that?

In these situations with meta_data_wrapper you could put the array-value before the value function, like this:

$date = $node_wrapper->field_tournament_date->value->value();


Zend Optimizer+ error Can an anyone help me.I am getting the following error while running my drupal 7 application

Fatal error: Cannot redeclare function views_views_plugins() (previously declared in /var/www/vhosts/cibi.hq.k.grp/newsite/sites/all/modules/views/includes/plugins.inc:15). If this code worked without the Zend Optimizer+, please set zend_optimizerplus.dups_fix=1 in your ini file in /var/www/vhosts/cibi.hq.k.grp/newsite/sites/all/modules/ctools/ctools.module on line 113

The very same thing happened to me after transferring my website to another hosting company.

You must run update.php.

Since I was logged out, the way I resolved this is as follows: I typed in the url box www.example.com/update.php (www.example.com being your site's name. If it's on your local machine, I guess it is something like localhost/update.php.)

If your settings.php file is properly configured, you should get an access denied message.

In that case, go to the directory (sites/default) and open the settings.php file. Look for the line $update_free_access = FALSE; and change it to TRUE.

Run update.php again. You will find a link at the bottom of the result page sending you to the front page. Click on it and your site is back in business. :)

CAUTION. Very important: Go to your settings.php file again and change the TRUE back to FALSE.


Views display 0 items I got to be missing something obvious. I want to display in my view 0 items until they use the Filter Criteria exposed filter with a search parameter.

Under Pager Use Pager I can't see how to display 0 items?

Is it possible?

There is a setting for this.

Advanced > Exposed form > "Basic"

If the view is still on default, it will be set to Basic, click basic and change it to "Input Required"


How to create an list in Drupal 7 I am creating a form and I would like to create an unordered list of links. My problem is that I don't know how to go about this. I didn't see anything in the forms API about accomplishing this. What is the correct procedure to produce an unordered list?

Thanks.

There's no single correct procedure to output HTML - as Ankit mentioned in his answer, one way is to add the raw HTML to the #markup property of an element in the form. Nothing wrong with that at all.

You could also use theme_item_list() which produces a simple HTML list with configurable attributes, and a bunch of default classes so you can target certain elements easily (see the docs for full details).

$items = array('First item', 'Second item', '...');
$form['some_element'] = array(
  '#theme' => 'item_list',
  '#items' => $items,
);

will output

First item

Second item

...

it will probably inherit some of Drupal's core or your custom styles because of "item-list" class on the wrapper. That may or may not be what you want, so for this case I guess what you use will likely depend on that styling.


Specify ids for a migration yml file from nested json array Given following jsons file

{
  "data": {
    "uuid": {
      "value": "ed64784-cjjhd6",
      "patient": false
    },
    "name": {
      "value": "Name",
      "patient": false
    },

how to select the uuid value and set it as ids in the migratin definition yml file?

here is my migration yml file:
I really don't know how to select the value of the uuid as ids

id: migrate_json_file
label: Migrate content from local json file
source:
  plugin: source_url
  data_fetcher_plugin: file
  data_parser_plugin: json
  urls: data/data.json

  ids:
    value:
      selector: uuid/value
      type: string
  item_selector: /data
  fields:
  - name: uuid
    label: 'uuid'
    selector: uuid

  - name: title
    label: 'title'
    selector: name

destination:
  plugin: entity:node

  process:
    type:
      plugin: default_value
      bundle: produkt

    title: name
    field_uuid: uuid

  sticky:
    plugin: default_value
    default_value: 0
    uid:
      plugin: default_value
      default_value: 0

    migration_dependencies:
      required: {}
      optional: {}

    dependencies:
      enforced:
        module:
        - migration_json_file

Thank you in advance

Sincerely

Hermann

The migration template should include top level source, process and destination sections

It appears in this case you are missing the process section for the field value assignment there.

More info: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview#etl


How to disable default site? I used Drupal multisite approach. When I go to mydomain.com the default site is loaded and if I deleted sites/default/settings.php file, it is creating again.

How do I disable the default site so that, not even the installation page is shown?

Create a directory under the sites directory besides default with the exact name as your domain and place the settings.php file in it. You can delete the default/settings.php after this.


How to use field variable (a term) from node in field.html.twig for page title When viewing a node I want to display an associated vocab term field inline with the node. The vocab is called "field_related". If I add {{ node.field_related.entity.label }} to node.html.twig and view the node it outputs the term, but if I add the same print tag to my custom twig template field--node--title--topic.html.twig ("topic" is the content type name) it doesn't output anything.
What do I need to do to get it so I can print node.field_related.entity.label in field--node--title--topic.html.twig?

I've been trying various combinations of how to write the tag and fiddling with theme_preprocess_field but so far all I've gotten is a headache.

In a field template the parent entity of the field is stored in element['#object'], so you can access the taxonomy field of the node like this:

{{ element['#object'].field_related.entity.label }}


What can cause form API to ignore the weight of an element that is a collection of buttons? I have two form elements on a node form I'm trying to order unsuccessfully. One is a standard collection of form buttons (submit, delete, etc) and another is a fieldset add by CCK. I am trying to order the submit button (one of the buttons in the collection) above the fieldset. I've set the #weight on the button collection (the parent form element of the submit) to a number lower than the #weight of the fieldset.

I've verified that after the #pre_render calls in drupal_render() the weight values I set earlier in my hook_form_alter persist. So nothing has changed them up to this point. I can confirm that changing the weight on the fieldset does it move it around, so I am having some impact on positioning.

Why does FAPI ignore the weights and still position the submit button at the bottom of the form? Or is there another point after drupal_render() that allows other modules to change form element weights?

I've discovered this is expected behavior. The solution is to copy the buttons into new form elements, position them where desired, and remove the default buttons. Here are step by step instructions on how to do this.


Finding the host node of a paragraph I'm trying to find all the absolute URLs in a site (in wysiwyg content, url fields, config) to convert them into relative URLs later via manual administration. All the URLs in question are within the same Drupal site. I've managed to use PHPMyAdmin to find and record readily-accessible entities that contain absolute urls (nodes - /node/NID/edit, menu items - /admin/structure/menu/item/MLID/edit, etc.). However, I'm having a difficult time with Paragraphs.

The id of a paragraph field row is for a specific instance of the paragraph.
Without knowledge of the field hosting the paragraph, the instance could be anywhere.
The paragraph could be nested in another paragraph.

How would one go about solving this issue? How do I find the host node of paragraphs containing an absolute link?

It might be a bit easier to use the API rather than SQL for this. I'd be tempted to load all nodes, loop through all their fields and check values that way. If you hit a paragraph field, recurse and check its fields too.

This is a very rough example function, but it should get you going:

function entityHasFieldWithAbsUrl(\Drupal\Core\Entity\ContentEntityInterface $entity, array $types) {
  foreach ($entity->getFields() as $key => $field) {
    $field_type = $field->getFieldDefinition()->getType();
    $field_settings = $field->getSettings();
    if ($field_type == 'entity_reference_revisions' && $field_settings['target_type'] == 'paragraph') {
      foreach ($field as $item) {
        if ($item->entity instanceof \Drupal\paragraphs\ParagraphInterface) {
          if (entityHasFieldWithAbsUrl($item->entity, $types)) {
            return TRUE;
          }
        }
      }
    }
    elseif (in_array($field_type, $types)) {
      foreach ($field as $item) {
        // Change this to something better...
        if (strpos($item->value, 'https://www.example.com/') !== FALSE) {
          return TRUE;
        }
      }
    }
  }

  return FALSE;
}

And you'd use it something like this:

$nodes_with_abs_urls = [];
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple();
$types = ['text', 'text_long', 'text_with_summary', 'string'];
foreach ($nodes as $node) {
  if (entityHasFieldWithAbsUrl($node, $types)) {
    $nodes_with_abs_urls[] = $node->id();
  }
}

You probably need to tweak the types to suit your installation, but it should work at a basic level.


What is the menaing of print t(); in following code? I was referring the html.tpl.php to learn the theming guide for drupal 7, and found following code line in html.tpl.php,

<a href="<?php print $skip_link_target; ?>" class="element-invisible element-focusable"><?php print t('Skip to main content'); ?>

Can anybody let me know what is the print t() in <?php print t('Skip to main content'); ?>.
Is it translation function or something else?

Yes, it's Drupal's string translation function.

t()

  Translates a string to the current language or to a given language.


Getting empty error message when install Drupal using Windows server 2012 I'm attempting to set up a Drupal 8.3.6 site on Windows Server 2012. I have been following this guide: http://www.drupalonwindows.com/en/blog/installing-drupal-8-windows

I'm at the point of running the Drupal installation, but am running into a road block at the Database configuration step. When attempting to save my database settings, it takes a very long time to attempt to save, and then I get an error message that simply says "Failed to connect to your database server. The server reports the following message: ." Just a blank error message.

Some info about my configuration:

I'm using SQL Server Express and maintaining it with SSMS 2017
My SQL Server setup uses Windows authentication and I am logged in as the Administrator account when working with it (I am not sure if this is different from the credentials Drupal tries to use)
Windows Firewall on my server is configured to allow connections to port 1433 as well as to sqlserver.exe
According to SQL Server Configuration Manager, SQL Server is running (SQL Server Agent and SQL Server Browser cannot be started however)
I created a database called "drupal" in MSSQL owned by the Administrator account, however I get the same error whether or not I specify this database name in the "Database name" field or if I define a new one. I am leaving the username/password blank as instructed by the installation page.
In the comments section of the install guide, one of the maintainers of the sqlsrv drivers says to use the 8.x-1.x branch if not purchasing Phpmssql, so these are the drivers I am using.
My server has 2 IP addresses, and the IP address of my Drupal site is different from the primary IP address of my server (my primary IP is used for a different site). My bindings in IIS are correct and I'm accessing the site via its designated IP. I feel like this is causing the problem with a connection issue, however if I change the host under "Advanced Options" from "localhost" to my server IP, the problem still persists.
Before using 8.x-1.x drivers, I was trying 8.x-2.x and getting the error message "The PhpMssql library is not available.", so maybe it's not an IP connection issue?

I feel like I've missed something in my configuration, but can't tell what that is from the install guide. Can anyone please shed some insight?

I figured it out, I think that trying to connect to "localhost" was failing because I should have been specifying {servername}\SQLEXPRESS instead.


Update migrations to import new content I'm using migrate upgrade drush command to generate migrations from a live DB of website.
So content is created during my migrations. How can I do an update of these migrations to import new content when re-run migrations ?

Thanks

You could use the track_changes option, ex.

source:
   plugin: d7_node
   node_type: article
   # Allows to import changed as well as new records from the source.
   track_changes: true

https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/overview-of-migrate-source-plugins#track_changes


How can I render my form? I create a module and I create a template for that .

I use this code in mymodule.module :

function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'moduletheme' => [
      'render element' => 'form',
      'variables' => array('test_var' => NULL),
    ],
  ];
}

And I use this code in mymodule/src/Form/MymoduleForm.php :

public function buildForm(array $form, FormStateInterface $form_state) {
    $forms['#theme'] = [
        '#theme' => 'moduletheme',
        '#test_var' => $this->t('Test Value'),
    ];
    return $forms;
}

And I use this code in mymodule/templates/moduletheme.html.twig :

Test twig template!

test_var: {{ test_var }}

But when I clear cache and refresh my module page , I just see :

Test twig template!
test_var:

How can I fix this problem in drupal 8 ?

Remove the '#' from the form field key and clear cache. $forms['theme'] instead of $forms['#theme'].

$forms['theme'] = [
    '#theme' => 'moduletheme',
    '#test_var' => $this->t('Test Value'),
];


Refresh View in block using js I have two different blocks.
One has a form and the other one is a view with some files uploaded from the form above.

On submit of the form I need to update the view results.
I thought I could do it using js but I can't make it work.

Please check my code. Any advice would be helpful!

Drupal.behaviors.myViewsRefresh = {
    attach: function( context , settings) {
        var viewName = 'application_documents';

        // Your views should be Ajax enabled
        var instances = Drupal.views.instances;
        var myViews;

        // then simply need to iterate through the various
        // views instances name to find the view
        $.each( instances , function getInstance( index, element){
            if(element.settings.view_name == viewName ){
                myViews = '.view-dom-id-' + element.settings.view_dom_id;
            }
        });

        $(document).once('mysubmitbutton').ajaxComplete(function(event, xhr, settings){
            if(typeof myViews !== 'undefined'){
                $(myViews).trigger('RefreshView');
            }
        });

    }
}

I can get into the ajaxComplete but the view doesn't reload. The view id is correct.

Thank you in advance.

The way you construct your myViews variable seems to be the reason this doesn't work for you.

What worked for me was changing this:

            myViews = '.view-dom-id-' + element.settings.view_dom_id;

to

            myViews = '.js-view-dom-id-' + element.settings.view_dom_id;

I just tried a simple version of that without any form submiting, simply calling this from my browser's console:

jQuery('.js-view-dom-id-c58e9660da223aaf7c1645b2746e0b2e16f6a2f3e1de74c8533e6ad6117613db').trigger('RefreshView')

and it worked as expected. As a final remark and as is commented in the code you provided, your views should be Ajax enabled, otherwise, this will not work.

Good luck!

P.S.: The most relevant piece of information from the codebase (this comment says it all):

// Add a trigger to update this view specifically. In order to trigger a
// refresh use the following code.
//
// @code
// $('.view-name').trigger('RefreshView');
// @endcode

(http://cgit.drupalcode.org/drupal/tree/core/modules/views/js/ajax_view.es6.js#n94)


Adding Poll to Blog Content Type I'm using D7, and I've created the Content Type 'Poll'. That said, I want to add a specific Poll I've created to a published Blog Entry. Is this possible? I thought about creating a poll block, but this would just publish the same poll on all of my Blog Entries? I also can't seem to add a specific Poll field to my Content Type 'Blog'...

You need to install Entity reference module

Then in your blogs content type, add a new field

Name: [what ever you like] I named mine aaaa
Type: entity reference
Widget: auto complete.
Then on the settings page for Target Bundle select poll.

Then edit your block, and in entity reference field (aaaa), type your poll name and save changes.

In Views, create a block view of poll.

Under Advanced, RELATIONSHIPS add Entity Reference: Referecing entity NOT referenced.

Checkmark require this relationship.

Then add a CONTEXTUAL FILTER of Content: Nid

For Relationship, select your referecing

Provide default value, Content ID from URL.

Note: your view preview will be blank, but it will show up when you view the blog.

Lastly, in blocks, assign your view block to a region.

Now this will automatically show the poll that you reference in your blog.


Adding Ajax to Book navigation block I am using book navigation block which contains links to content of BOOK.I would like add ajax functionality to this links.

I tried adding use-ajax class to this links.But i was unsuccessful.

Please let me know how to ajaxify links of book navigation block

Thanks a lot for the help.

If you are using drupal6(you haven't specified) then try the AdvancedBookBlocks module. It is built on the ideas of the jquery menu module and could help you.

If you are on drupal7 there is a port of the drupal 6 module though still a sandbox project. I have tried it out and it works. You can find it here


create table with sticky head how can I create table with sticky head.
I try theme_table but it output a simple table without floating head.

In drupal 6, table will have sticky header by default. I did not see this because my table has few rows and my site has not any scroll :). its described on API: theme_table


Appears the same orders in the admin/commerce/orders and in the admin/commerce/orders/carts In admin/commerce/orders appears the orders that order status is: Checkout:Payment,Checkout:Checkout,Shopping cart (these orders that appear in admin/commerce/orders/carts).Ι would like to appear only orders tha order status is:pending.
How could I do it?

Thank you very much.

In views list, there is one view named "Orders". In this view two pages are available:

"Orders"
"Shopping carts"

In "Shopping carts" page, click on Commerce Order: Order state from filter criteria and select states for which you want to display records.

Let me know if you face any future query with this.

Thanks!


Migrate data from CSV column header row I have a client CSV file that has Stores in the first column and Tasks in the cells across the header row. In each Task column, there is either an X, R, or blank (NULL). This is supposed to identify whether the Task is assigned to the Store in the first column, or a "rollover" task, or the task is not assigned to the store. Admittedly, this is a strange CSV format, but I am stuck with it.

The Tasks and Stores are already migrated. I am having a hard time trying to figure out how to tell my migrate class to iterate through the Tasks in the header row, and assign them (or not) to the Store(s) in the first column.

Any directions at this point is extremely appreciated.

See the image attached for reference.

I highly recommend looking into Feeds. It has a CSV importer where you can map the fields and headers to anything you want.


Set active trail in hook_preprocess_node For some content type, I need to attach my node to a parent menu item. I don't want to do that with UI (because too many nodes).
I saw something like that for Drupal 7 (works in a preprocess):

menu_tree_set_path('main-menu', 'my/parent/path');

Do you know a way to do that with Drupal 8 (menu_tree_set_path seems undefined) ?

The menu active trail is defined by the menu.active_trail service. Unfortunately it doesn't use a tag based extension like breadcrumbs.

You can replace that service and in case you detect that you're on a patch displaying a certain content type, return your desired structure.

You could also try out the https://www.drupal.org/project/menu_trail_by_path module, which defines the active trail based on the aliased path, like breadcrumbs do by default.


Form redirect with posted data How to transfer the submitted data too when redirecting a form through $form_data['#redirect']?

Like :

hook_menu declares : page-1, page-2

page-1 having a form that when submitted triggers page_1_form_submit() (in which I does the redirection)

but I'd like that once redirected to page-2, page_2_page() (registered as render function in hook_menu) can access the previously submitted data!

:)

In the form submission of the first page you can copy the values in $form_state['values'] into the session for the current user; the page callback of the other page can then access them.

function mymodule_page1_form_submit($form, &$form_state){
  $_SESSION['mymodule_page1_submission_timestamp'] = time();
  $_SESSION['mymodule_page1_submitted_values'] = $form_state['values'];

  $form_state['redirect'] = 'The path for the second page';
}

function mymodule_page2_view() {
  $delay = 300;
  if (!empty($_SESSION['mymodule_page1_submitted_values']) && !empty($_SESSION['mymodule_page1_submission_timestamp'])) {
    $submitted_data = ($_SESSION['mymodule_page1_submission_timestamp'] > time() - $delay) ? $_SESSION['mymodule_page1_submitted_values'] : array();
    unset($_SESSION['mymodule_page1_submission_timestamp']);
    unset($_SESSION['mymodule_page1_submitted_values']);
  }

  // ...
}

I use $_SESSION['mymodule_page1_submission_timestamp'] just to avoid the second page gets the values submitted on the form present in the first page more than 5 minutes before. If you don't want such restriction, then remove any reference to $delay.

You could also pass the values through the URL, but there is a restriction on the URL length the browsers can handle, and that restriction depends on the browser, as long as I know.


Can I use the Migrate module to sync a site database with a Filemaker Pro database? Is it possible to get data from a Filemaker Pro database and insert it into the database for a Drupal site?

Ideally, I'd like to set this up so that Drupal would periodically check the Filemaker database and import any new (or updated) data into its database.

Yes, it's possible.

You can use the Migrate module from Drupal 8. This module allows you to import data from an SQL source. You have to create a custom module to configure the migration. In that module, you should create a migrate source plugin class extending the abstract SqlBase class provided by the core Migrate module.

The SQL source plugin must implement three methods:

query(): Returns the query that selects the data from the source
database.
fields(): Returns available fields on the source.
getIds(): Defines the source fields uniquely identifying a source
row.

Plus, you'll have to declare the connection to the source database in the settings.php or settings.local.php file. So, you'll have the Drupal 8 connection configuration and your migrate source database:

$databases['migrate']['default'] = array (
  'database'  => 'source-database-name',
  'username'  => 'source-database-username',
  'password'  => 'source-database-password',
  'host'      => 'source-database-server',
  'port'      => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'    => 'mysql',
);

Finally, you need you define the migration that uses your created plugin and the database:

id: filemakerpro
label: 'Filemaker Pro'
source:
  plugin: filemakerpro
  key: migrate
process:
  title: title
  field_datetime: datetime
  field_place: place
destination:
  plugin: 'entity:node'
  default_bundle: yourbundle

Once you have done this, you need to execute the migration. You can execute it periodically and migrate will add the content.

You can have more information in the Migrating data from a SQL source (the info I posted here is a briefing from that link).


Web services for specific node I know you can enable Web services for content in Drupal8. You also need to set permissions to make a GET request to content.

But I was wondering if it's possible to set for each node if it can be accessed by GET request or NOT. How can I do this? Because now they can access all nodes ... .

You need to implement a route subscriber and an access handler. Assuming that that should be able to see the nodes via HTML but not via json. If they shouldn't be able to see via HTML either, swap out the node access controller by implementing an alter hook to modify the entity type info. If they should be able to see HTML, go the route subscriber path and alter the rest resource routes to add a new access requirement. Then implement your logic in an the access handler.


Changing block content based on user input I need to change the content of a block on the landing page based on user input.
Basically, I have a few links and a search form; if the user clicks on a link, I want the block to display some text, based on which link was clicked, and if the user uses the search form then to display information from an external database.

Edit
I left this site for a while & now am coming back to it.
I thought about it and if it's too hard to do in a module, then I could just make different pages for the texts & link them. And displaying data from the database is trivial.


View inside a node with content from a relationship I have two content types: Artist and Artwork.
An Artwork has a field called field_artist which relates to the relevant Artist node.
I want to add a view to the Artist node page, so that all artworks of that artist are displayed.
I tried using EVA, but I can't figure out what relationship and contextual filters to choose. I looked for tutorials but I find this very confusing.
Is there a way to do this with EVA OR in some other easy way? The only crucial thing is that the entity reference field from Artwork to Artist must be used to filter the artworks in the view.
Thanks!

You can build it in Views without EVA.
Here's a great article about different cases of how to build Relational lists in Views (I'm not affiliated): Relationships and Contextual Filters in Views 3 for Drupal
In your particular case you need to look at the 'Pulling fields of “Child” nodes by node reference' section.
You build a list of Artwork, then add the Contextual filter for the Artist ER field, configure it to default to "Content ID from URL", add the Validation that limits it only to the Artist type so it appears only on Artist nodes, adjust the other settings to your particular needs.


How to get a term from the translated term name? I have a translated taxonomy term whose name is Autos Y Motores (Spanish). How can I get the taxonomy term object from it?

If the term name were in English, I would use taxonomy_get_term_by_name('Vehicles & Motors') to get the taxonomy term object.

How can I do with a translated taxonomy term name?

You can try to translate it before pass it to taxonomy_get_term_by_name function, try some thing like

$string= 'De Lema'; // string in not default site language I suppose in French
$default_lang_short = 'un'; // I supposes you default site language is english change it to your default
$en_value = t($string, array(), array('langcode' => $default_lang_short));
taxonomy_get_term_by_name($en_value);


Feeds module and feed that includes external files as nodes I have a feed that includes item content in external xml files. For example, I have a manifest.xml file that has "sections" and each section links to another xml file.. such as:

<rss version="2.0">
<script/>
<channel>
<title>Example</title>
<link>manifest.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
<lastBuildDate>Wed, 05 Dec 2012 17:04:05 GMT</lastBuildDate>
<item>
<title>Page One</title>
<link>Page_One_Section.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
</item>
...
</channel>
</rss>

Then in that (section) external file contains lists of nodes whos content is stored in yet another external xml file...such as

<rss version="2.0">
<script/>
<channel>
<title>Page One</title>
<link>Page_One_Section.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
<lastBuildDate>Wed, 05 Dec 2012 17:04:05 GMT</lastBuildDate>
<item>
<title>Example Story</title>
<link>story.xml</link>
<pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate>
</item>
...
</channel>
</rss>

Now my question is, in this multi-file structure, will the feeds module parse this out-of-the-box, or will I need to get some other add on or create a custom parser??

What other solutions are out there for parsing something like this?

Feeds module can be setup to do this with XPath Parser and Feed Tamper. Give feeds tamper a try - https://drupal.org/project/feeds_tamper


block template for node view What should be the template for my block view if the url is

  block/manage/views/guides-block/configure?destination=node/9

I have tried block--block--9.tpl.php but does not work

As per Drupal 7 Template (Theme Hook) Suggestions

block--[region|[module|--delta]].tpl.php
base template: block.tpl.php

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

block--module--delta.tpl.php
block--module.tpl.php
block--region.tpl.php


How do I change the content text programmatically? I have enabled the anonymous comment setting. And its E-mail form appears as shown below.

Now, I want to change the text "The content of this field is kept private and will not be shown publicly." to "E-mail address will not be shown publicly."

How can I change this programmatically.

For information the HTML part I have copied through fire-bug which is as below.

     E-mail *
     <input id="edit-mail" name="mail" value="" size="30" maxlength="64" class="form-text required" type="text">

The content of this field is kept private and will not be shown publicly.

This value is defined in the comment_form function. More specifically, it is the description in this section:

  // Add author e-mail and homepage fields depending on the current user.
  $form['author']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail'),
    '#default_value' => $comment->mail,
    '#required' => (!$user->uid && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT),
    '#maxlength' => 64,
    '#size' => 30,
    '#description' => t('The content of this field is kept private and will not be shown publicly.'),
    '#access' => $is_admin || (!$user->uid && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT),
  );

You could create a custom module and implement hook_form_FORM_ID_alter. Your custom module file would contain below lines in a .module file and a basic .info file.

<?php

function MODULENAME_form_comment_form_alter(&$form, &$form_state, $form_id) {
  $form['author']['mail']['#description'] = t('E-mail address will not be shown publicly.');
}

Alternatively there are some options for overriding strings outlined here: Drupal 6 & 7 - Change default strings (text) without using full translation system


Close Fieldset when another is opened I have a form at http://turtle.umbrellamedia.net/build

What I would like is to be able to open each field set group, and close the others. For instance, if I click on "Front Color" the "Type of Phone" field set would close.

Any help would be appreciated.

Edit: I am using the forms API for this and have a custom module built that made these form items.

Sounds like a case for a jquery.ui accordion fieldgroup setup instead.

e.g: If you install https://drupal.org/project/field_group

I believe you can also use those group styles in custom FAPI forms. At least, I've done that for vertical tab, but maybe that's core now...

You could also add the javascript manually with

drupal_add_library('system', 'ui.accordion');

and use it as per: http://jqueryui.com/accordion/


How to print formatted contents of Computed Field and Full HTML Textarea in a custom template? I have used this code to print normal text fields in a print.tpl.php template file:

<?php if(isset($node->field_mytextfield['und'][0]['value'])) {
          print $node->field_mytextfield['und'][0]['value'];
            }
     ?>

But that same code will not work with Computed Fields I have set up in that same content type. The content type has a "Print" display type, and I have tried all of the Format options (Unsanitized, Plain Text, Filtered Markup, and Raw Value No Display Code) for the computed fields, to no avail. How can I print the formatted values of those computed fields, exactly as they are displayed by the actual fields themselves?

I also have a Textarea field that prints as a single line of unformatted text using the code above. How can I print the formatted value of that field when Full HTML is used to enter info into that field?

Thanks!

The Computed field defines its own formatting in the Display Code (PHP) box. If you have done your formatting there, when the page is processed, $vars will contain the output as:

Unsanitized: the output of Display Code (PHP) ($display_output) is unchanged.
Plain text: $display_output is filtered through the Plain Text filter.
Filtered markup: Non-permitted HTML tags are stripped from $display_output.
Raw Value: Display Code (PHP) is ignored and the value from Computed Code (PHP) is used ($entity_field[0]['value'] ).

This is fine for a rendered field using $vars. The Display output code is used when the node is preprocessed. If, however you wish to access the fields from the $node object, only the field value (Raw value) is presented. So you either have to duplicate the Display output code in your template, or you have to move the formatting into the Computed code box.

If you set your $entity_field[0]['value'] to the actual formatted string, then use the default $display_output = $entity_field_item['value']; in the Display output, you should be able to use the above code to display the field as is.

This is why it is much easier to use the processed fields. Instead of coding something like:

print $node->field_fieldname[LANGUAGE_NONE][0]['value'];

If $vars['field_fieldname'] has been set, the template file receives the result of extract($vars). Each array element becomes a variable in its own right and all you have to do in the template file is:

print $field_fieldname;

or

print render($content['field_fieldname'];

if you have not separately included it in $vars in a preprocress. Much simpler when you understand how the data gets moved around.


hook_commerce_shipping_service_info() rate callback: What does the 'data' array do? hook_commerce_shipping_service_info() allows to specify a rate callback.

function snailmail_commerce_shipping_service_info() {
  [..]
  $shipping_services['snailmail']['callbacks']['rate'] = '_snailmail_rate';
  return $shipping_services;
}

function _snailmail_rate($shipping_service, $order) {
  return array(
    // Amount in EUR Cent
    'amount' => 250,
    'currency_code' => 'EUR',
    // What is this?
    'data' => array(),
  );
}

Question: What can I do with the 'data' array in the return value?

Prices in commerce have a data array to establish the original components and component modifiers that these might have. For example, discounts and taxes add components to alter a price after taxes.

I'd say you can use 'data' array as storage of context information like the line items do (they store the product display where the product has been added to the cart) and the price system stores the components there, so it's needed to add elements to it.

Check commerce_price_component_add and commerce_tax_rate_calculate for examples on where this is used.


How can I programmatically render a node's field respecting the view mode settings? I want to render a node's field inside a block. It works like this:

<?php

if ($node) {
  if (isset($node->field_body_secondary) && $field = $node->field_body_secondary->value) {
    $markup = render($field);
    $build = array(
      '#type' => 'markup',
      '#markup' => $markup,
    );
  }
}

return $build;

But this is not 100% as if I would just render the field normally, making it visible in the view mode settings.

To render a single field with the display setting of a view mode you can use the view() method of the field:

Example for rendering the image in teaser format:

$build['image'] = $node->field_image->view('teaser');

Or the body in full:

$build['body'] = $node->body->view('full');


White Screen of Death on Chrome So I'm getting a white screen of death on my newly created Drupal 7 site that was working fine until a minute ago. This is only happening on Chrome, the site works fine on IE and FF.

On chrome, the console gives the following error message:

  net::ERR_INCOMPLETE_CHUNKED_ENCODING

What I've done recently that might be causing this error:

I enabled the xmlsitemap module
I enabled clean url's on my site - maybe this is being caused by something wrong in my .htaccess file?

My cPanel Error log reports the following, though I'm not sure these are related issues:

[Thu Sep 24 20:10:33 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/sites/default/files/milla.jpg, referer: http://mydomain.fi/?q=node/7/edit&destination=admin/content

[Thu Sep 24 20:09:04 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin, referer: http://mydomain.fi/?q=admin/structure/types/manage/blog-post&destination=admin/config/search/xmlsitemap/settings

[Thu Sep 24 20:00:07 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

[Thu Sep 24 19:59:59 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

[Thu Sep 24 19:59:48 2015] [error] [client xx.xxx.xx.xx] File does not exist: /home/myuser/public_html/admin

First real Drupal project that I'm actually hosting somewhere, and now that I just got it up and running it's all coming crashing down :(

Well, I found a solution from here:
http://www.zyxware.com/articles/3424/solved-drupal-boost-drupal-site-not-working-in-chrome-and-getting-a-blank-white-screen-when-boost-is-enabled

I added the following line to my .htaccess file:

Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"

Still occasionally getting the same error message in the console, but at least now the site is loading :)


8 - Translate static content In my site there are lot of static content such as section headers and random content. I want to translate them.

Can I translate with them {% trans %}my content{% endtrans %} in twig?

If yes, where to insert the translations in the backend?

Yes - you can do it hardcoded in twig, this can be translated via the user interface translation: /admin/config/regional/translate. The locale module needs to be enabled.

  BUT, i would only recommend this method for static content (and maybe random)!

For dynamic content i suggest to use the drupal multilingual feature(s). Start by enabling the module content_translation.
Then you can edit a node, and add a translation for it in the backend (node/x/edit). See the docs on d.o. for further information.


Drupal 7 + Services 3 : anonymous user can't access user/register endpoint (401 access denied) I'm using Services for providing an external webapp to register new user to the Drupal server.

I'm able to login from the webapp, create node and post comment.

But I can't have access to user registration.

My endpoint is configured and got all CRUD functionnality for user checked.

But when I try to acces it : http://localhost/rest/user/register

I got a 401 : ["Access denied for user anonymous"]

I guess I'm missing sone permissions, but I can't figure out which one ?

Could you please help me ?

Thanks in advance.

nieud

Well, apparently the 401 is a false error message.

I had an error in the data structure I posted to user/register, when I fixed it the 401 disappeared.

I still have an error on my user registration but this is now a 500.


Let users access account before confirming email address I'd like to let users access their account without confirming email address. But still send the email confirmation. Then I'll display a message saying that if email is not confirmed within 3 days, account will be deleted. How can I do this in drupal 7 ? Is there any module that can help me do this, or if I need to do it in my custom module, please give me a hint about how can this be done ? Thank you.

You can do this by help of LoginToboggan module. There are so many features of this module, immediate login is one of them.


Create Group permission to grant view of all group content I'm running Drupal 8.7.11 and Group 8.x-1.0-rc5.

I have a situation whereby I have > 5,000 groups.  The majority of the users are members of 10 groups.  However I have a small set of users who need an overview of all content from all groups.  I have had issues running the site when enrolling users into all of the groups, so I had to give them 'Bypass group access control' in order that they can use the site without it crashing.

However what I would like to do is create a new 'View all group content' permission, which skips the access check, but doesn't give the users the administrative access that comes with 'Bypass group access control'.

Does anyone have an example of how this might be achieved?

As per their documentation "The permission layers explained" it should work like this:

  I want my site admins to be able to administer all groups without having to join them.

  Assign them a global role, e.g.: "Site admin", and then assign the "Administer group" >permission to the matching advanced outsider role in the group type configuration >section. Anyone with the "Site admin" role set to their account will be able to >administer all groups they are not a member of.


Create a sample HTML select of taxonomy terms I created a custom form in a custom module. (in a class that extends FormBase)
I want to add a (very) simple html select element, this select must contains all taxonomy elements of a specific vocabulary, like this, where the integers are the taxonomy term IDs.

<select id="...>
    <option value="4">tutu</option>
    <option value="15">toto</option>
    <option value="61">tata</option>
    ...
    <option value="48">titi</option>
</select>

How can I create this <select> tag using the taxonomy term ID and the taxonomy term name? The users would not see the taxonomy term ID, but only the taxonomy term name.

With a vocabulary name, how can I generate the good structure (an array?) that allows me create the <select> tag?

You will need to get your terms (with a query or load the vocab), loop over them and create an array of term tid and term label. Set that array as the #options property on the select field in your form code.


Custom navigation menu bar I use the main menu as navigation bar, and I would like to obtain the following result: When the mouse is hovered on one navigation item, the sub menu should be shown as <div> under this item. I would like to be able to style the sub menu <div>s as well.

Shall I actually use the navigation menu or just the main menu?

I am using Drupal 7.

It sounds to me like you are looking for something like Superfish or Nice Menus.

My personal preference is Superfish, as it has become pretty damn useful in recent updates. It's also responsive if that's a requirement, and support touchscreens quite nicely.

EDIT

Something I missed (possibly another personal preference) is that I find the CSS for Nice Menus an absolute NIGHTMARE in comparison with Superfish.


What's the best way to store time I need to store "time" in a content type. The time is actually duration (how long it took people to perform various tasks), with the time varying between a few minutes to several days.

Is there anything already out there (Date doesn't seem to cover it)?

If not, what's the best way to create this?

Ideally I'd like dropdowns for days, hours, minutes, seconds, tenths.

It seems to make sense to store a computed value in the database (total seconds, rather than save everything in five separate fields. Are there any good tutorials on doing this?

I assume I then use a field formatter to break out 300.3 seconds into 6:00.3 or whatever format I want?

Sounds like you're looking for something like Time Period.

That one stores the interval in seconds, so if you need smaller values you will probably have to write your own field widget/formatter but the module might still serve as a base.. or maybe you could extend it to cover this use case as well and e.g. store microseconds.


Form fields getting cleared off of user inputs after validation errors This question is almost exactly my problem, but I'm not making the mistake made by that poster. As in, I'm not using #value to populate my fields, but the proper #default-value.

I'm working with ubercart, and the form I made is part of a checkout pane. Unfortunately, I have had to use drupal_get_form() within the main uc-cart-checkout-form as the value of a checkout pane. Otherwise, I cannot provide independent submit buttons or clump them together properly.

The problem is that after validation, the form fields are getting cleared out. Only the default values are being reset. I have tried writing a validation handler (even if actually the validation is taking place in a custom validation function that I'm calling from the hook_form_alter() of uc_cart_checkout_form)

Is doing this manually with SESSIONS the only way out? By calling a drupal_get_form inside a drupal_get_form, am I confusing FAPI irrevocably?

I reckon using the ternary conditional operator to check if there is anything in $form_state['values'] would get there, i.e. something like:

$default_value = 'Test Default Value';

$form['test'] = array(
  '#type' => 'textfield',
  '#default_value' => !empty($form_state['values']['test'])?$form_state['values']['test']:$default_value,
);


New scheduled rule knocks out existing scheduled rule I have a rule set with an active rule to send mail to a user. This is triggered by a workflow being marked done.

This seems to work just fine until more than one, completely seperate, workflow is marked done.

When I view the scheduling rule set page that shows what's in queue for scheduling I can see the mail that is about to go out from the workflow I marked as done. Now when I go ahead and mark another workflow as done it seems to replace the email that was about to go out to another user from the previous workflow being marked done with the most recent one.

Any ideas as to why I cannot have more than one scheduled rule set in queue at a time?

D6, rules module up to date at v1.5

Make sure the Identifier for the scheduled task is unique. Adding the node ID of the node that completed the workflow could work to ensure the Identifier field is unique.

A new task will replace an existing task with the same Identifier. This happens because the Identifier value is the key each task is stored with in cron.

Check out this free video Introducing Rules Scheduler for more tips.


Omega using wrong grid class? So, I'm using Omega (with custom subtheme), and I'm running into a strange issue. I have a logo block in header first which only displays on the front page (and has grid-3 class), and I have a menu in header second which is displayed everywhere (and has grid-9 class). The front page is fine, but on every other page the region-header-second div with the menu keeps the grid-9 class, which is kind of messing with the layout. Shouldn't this automatically be set to grid-12 when the block in header first is absent? Has anyone run across this? It sort of feels like this is just 'stuck', but clear cache, etc. hasn't

Within your subtheme settings drill down to the specific region you have problems with and make sure the prefix and suffix settings are correct.


Count values from field i have a content-type "participants" with a field "number".

i want to calculate the total of all the values that are inserted in all the "participants"-node.

ie:

Node 1 -> 200 participants
Node 2 -> 3 participants
Node 3 -> 15 participants

Total: 218

Only the result should be visible

I was thinking to do it with views, but i'm not succeeding.

Any suggestions?

Use views calc to achieve this behaviour, This module adds simple calculations to a views table: https://www.drupal.org/project/views_calc


How do I create a simple table? I am working on a module where I need to display content in a table. Though I have created a simple table already, I need to know how to use theme(), as the function cannot be called directly.

Basically, What is the equivalent of the following line, which was perfectly fine in Drupal 7?

return theme(table,array(header => '$header', rows => '$rows'));

As reported in New render element #type 'table' and theme() renamed to _theme() and should not be called directly, the equivalent of $table = theme('table', array('header' => $header, 'rows' => $rows)) for Drupal 8 is the following.

$form['table'] = [
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];

(Replace $form with the variable containing the rendering array.)


Trying to using Rules to create page redirects to external links per node, but it's not working I like using Rules and am trying to create a page redirect, for a certain content type i’ve created. So instead of the user viewing the node, they get redirected to an external website. the site address get’s input via a simple text field in the content type i’ve created. i’ve tried different setting for this field, plain text, full html.

In the action part of the Rule i’v set as System/Page Redirect and the value as [node:field_ext_link_text]. But it’s doing something to the URL (decoding or encoding??) and instead say going to www.somewebsite.com, i get a page not found that reads

"/%3Cp%3E%3Ca%20href%3D%22http%3A//www.somewebsite.com%22%3Ewww.somewebsite.com%3C/a%3E%3C/p%3E%0A" could not be found.

i really don’t understand what it’s doing to this URL.

i also installed the link module and tried using a field type link but got similar results. i've also tried ommitting http://,

i also tried using Rabbit Hole module to accomplish the same thing, but got similar results.

Any help would be greatly appreciated. … have spent way to much time on this…(!)

Use the field redirection module. A great overview was provided by llulabot

https://www.lullabot.com/blog/article/module-monday-field-redirection

Mind you I've used Views with Conditional Fields to allow a single link to be either internal or external using a views template override when clicked (based on a radio button in the content type). Field redirection is easier to use than your custom solution.


Module does not show up in blocks (6.x) I have a module that I've activated, but it does not show up in the disabled blocks list.

The module is named "My Module."
Inside the my_module folder I have the following files:

my_module.module
my_module.info

my_module.info

name = My Module
description = My module description.
core = 6.x
package = My Modules

my_module.module

<?php
function hook_block($op = 'list', $delta = 0, $edit = array()){
  switch ($op) {
    case 'list':
      $block = array();
      //List out all blocks you want to create here
      $block[0]["info"] = t('Display info');
      break;
    case 'view':
      switch ($delta) {
        case 0:
          global $user;
          $block['subject'] = "ADMIN Header of the block";

          if (in_array('Site admin', array_values($user->roles) || $user->uid == 1)) {
            $block['content'] = "input form";
            $block['subject'] = "Header of the block";
          }
          break;
      }
  }
}

Change function hook_block to function my_module_block, and add return $block; to the end of the 'list' and  'view' cases.


global variable/array unset when hook_field_presave() is being called I am trying to pass a global array and work with it in hook_field_presave() but that global array is unset. How do I pass a global array and work with it in presave?

example

function find_feed_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   etc.
   etc.
global $testvar;
$testvar = $array = array(
    "foo" => "bar",
    "bar" => "foo",
    );
}

function find_feed_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
   global $testvar;
   dpm ($tesvar);  // result = NULL
   etc.
   etc.
}

This will never work - global variables only exist in the context of a single page request. Since the form build and presave happen in different requests, you can't use globals in the way you're trying to.

Use a session var instead, that will persist


Getting libraries to load with newer jQuery using jqmulti I'm kind of a newbie to this so I could be missing something really obvious, but I'm having trouble getting specific libraries to load with jQuery 1.7 in noconflict mode using jqmulti. I'm working on a theme based off twitter_bootstrap, and the bootstrap.js library is dependent on more recent jQuery. I've got jqmulti recognizing and loading 1.7 if I check "load even if no libraries are assigned" but when I have that unchecked and attempt to use hook_jqmulti_files() to assign particular libraries, nothing happens.

This is what I have in my template.php:

function regent_jqmulti_files() {
    return array(
        'sites/all/themes/regent/bootstrap/js/bootstrap.js',
        'sites/all/themes/regent/bootstrap/js/bootstrap.min.js'
    );
}

but when I look at my rendered html, the library is loaded, but nothing about noconflict mode,  and jQ 1.7 is nowhere to be found. I'm sure I'm missing something basic and stupid, this being the first time I've tried to set something like this up.

If you have checked "load even if no libraries are assigned", jQuery 1.7 should load regardless of anything else you do. So in your HTML you should see Drupal's jQuery loading, and you should also see jQuery1.7 loading, and also a script called switch.js, which takes care of the noConflict() mode. If you don't see those loading, there is a problem that's not related to your hook. Check the jQuery Multi settings page, does it list the jQuery version it's using?


I want to add css class to a field inside hook_field_widget_form_alter, but it doesn't work! in this link
https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_widget_form_alter/7

it describes that we can add css class to an element in a form via this code

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

I tried to use it but it seems $element['#attributes']['class'][] = 'myclass'; doesn't add any css class to form after rendering.

So how can I add css class to a form element inside hook_field_widget_form_alter() ?

Old issue but it might help future viewers.
Try this:
$element['value']['#attributes']['class'] = 'myclass';

See field_multiple_value_form() which creates the render array.
Then main theme function for rendering fields in forms is theme_field_multiple_value_form() and the parent theme function is theme_form_element()


Image and other media file management My question may seem vague but I'm confused and need advice on Drupal 7 media files management, so please bear with me. I'm looking for existing modules or ways to build the following functionality with minimal effort:

1) Image management. I'm building a site that is mostly text articles with a random image or two scattered here and there (an average Wikipedia article may be a good example). I want to be able to

1.a) insert scaled image thumbnails into my text and provide an explanation of what is in the image right under it (exactly as they do in Wikipedia). This doesn't seem to be standard Drupal feature when handling images.

1.b) if it is possible I also want my image thumbnails to be clickable with links leading to original unscaled images (again something that can be seen at Wikipedia, though they first lead you to another page that contains image information and copyright status).

2) Media file management. Sometimes I want to attach a file to an article that browser itself won't handle, something like .mp3 or .pdf. If I simply add a File field to an article, it won't offer any protection against anyone who decides to download it. Can I possibly make downloading a file a bit more complex - like forcing a visitor to enter captcha first?

Ari,

Let me start off by saying that media files (images, videos, etc..) attached to nodes, Meaning they are acctually uploaded when entering in a node content, those files are stored in the default file folder (usually 'sites/default/files' ), unless that field in the content type specifies otherwise.

Example:
If i create a content type called 'blog entry', I would add a field to that content type called media.  When you get to the screen where you can edit the field information, you can select accepted file extentions, where the files would be stored in relative path to the default file location in your sites file location settings (again, usually: sites/default/files)

I would make this file location 'blog-entry/media' for this new field in my new content type. So my files would upload to: sites/default/files/blog-entry/media  when i uploaded them during the addition of content.

The thumbnail settings are somewhat default and can be adjusted under the display settings for the content type. THere are default thumbnail parameters you can select from, or you can add/remove thumnail options in the site settings as well under image settings

Once you get a hang of this flow you will see how easy it really is to manage media.

Another module worth looking into (after you have done the above, so that you may understand what the core of Drupal is doing with your media files), is the Media Module. It makes uploading and managing a little easier than core.

Also to note: stay away from Media Gallery right now.. its a mess as of this week.. most bugs should be resolved sometime next month.


Add permissions for a new content type Context: I created a new content type (press room nodetype) locally and made a feature with it so it is easier to deploy on my dev-stage-prod environments. This works perfectly well. The thing is, is I need to add permissions to some user roles right away in the same deployment process. I can't find the proper way to run some code after the feature-revert-all;

At the moment I put my code in a new module press_room.install.

function press_room_update_7001() {
    module_enable(['press_room_nodetype']); // installs the feature that will add the new content type

    $permission = [
        'edit any press_room content' => true,
    ];
    _add_permission_to_role('myrole',$permission); // too soon, content type not yet created
}

This module is enabled by another .install (homepage).

function homepage_update_7003() {
    module_enable(['press_room']);
}

With this code the new content type is created and the module to preprocess its output is enabled but the permissions are not given. It seems the content type is not (fully) created when the permissions needs to be added, so Drupal skips those lines and do nothing. If I run my code a second time, it works since the content type already exists.

Has anyone a solution to process code after a new content type has been created. What is the proper way to do this? Thank you.

This may not be what you're looking for but here is what we do to deploy on several production sites.

Store as much in Features as possible
Write update scripts when needed (as you've done). However, we enable modules via drush, never in code.
then run: drush en feature_module_name -y && drush updb

If multiple modules need to be enabled, we normal setup a chain of dependencies in the *.info files.


Alternate to field_get_items() ?? CCK fields reconstriction? After a long quest, finally I got the solution for splitting $content in Drupal 7 in node.tpl.php.

Previously i was using i was using :-

print $node->field_name['und'][0]['value'];

Which was giving a warning :-

Notice: Undefined offset: 0 in include() (line 24 of C:\xampp\htdocs\drup\sites\all\themes\myCustomTheme\node.tpl.php)

Now I am using the function below which works fine with no errors

$output= field_get_items('node', $node, 'field_name');
$output = $output[0]['safe_value'];
print $output;

Now the problem is I have more than 50 fields on the page , I don't think it would be efficient to call field_get_items('node', $node, 'field_name') function 50 times.

Whats the alternate ?
OR should I strict to the field_get_items function
OR should I strict to the print $node->field_name['und'][0]['value']; which I heard is not good to use in Drupal 7 as und is undefined. This though solves my problem but gives irritating warnings.

First off, 'und' is the value of the LANGUAGE_NONE constant, which is used for the content not associated to a particular language. Not all the fields have a value for that, and if you are trying to access it, you get a PHP warning.

For example, for taxonomy terms, the array structure could be one of the following.

tags

other taxonomy terms

If you need to get the field value that would be used for the currently used language, you can just use field_get_items(). Its code cannot be optimized, as it needs to determinate the language used for the field.

function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
  $langcode = field_language($entity_type, $entity, $field_name, $langcode);
  return isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE;
}

Even the code for field_language() cannot be much optimized. You could avoid multiple calls to field_valid_language(), but that is the only thing you can do.

If you have your own code to decide which language should be used for the fields, you can access the field data directly, without using field_get_items().


How to export translated variables settings in code? In a custom module I define several configuration variables by implementing the Variable module's API. The module is part of a multilingual site project, so some of these variables should be translatable.

In my hook_variable_info() implementation, these variables are defined as with 'localize' => TRUE so they are available in the Multilingual settings > Variables interface provided by the Variable translation module (part of Internationalization). But their default state is not to be translated. So, in order to have the variable translated, the site administrator needs to visit the page and select my module's variables.

I need my custom variables to be automatically translated when the module is installed.

The module already uses Features to export other configuration, so a solution based on Features would be nice. But it can be purely code based.

Update: With recent version of the Variable translation module (ie. 7.x-1.7), the list of translated variables is stored by the language variable realm controller in its list variable. The following code demonstrate how to use the realm controller to set translated variables from a module hook_enable() implementation.

function MODULE_enable() {
  // Get the language variable controller.
  $controller = variable_realm_controller('language');
  // The list of translatable variables.
  $translatable_variables = $controller->getEnabledVariables();
  // The list of variables that could be translated.
  $available_variables = $controller->getAvailableVariables();
  // Add our variables to $translatable_variables.
  foreach ($available_variables as $name) {
    // Translate user mail messages.
    if (preg_match('/^user_mail_[a-zA-Z_\[\]]*\[mail_part\]$/', $name)) {
      $translatable_variables[] = $name;
    }
  }
  $translatable_variables = array_merge($translatable_variables, array(
    'user_registration_help',
    'user_picture_guidelines',
    'maintenance_mode_message',
    'menu_main_links_source',
    'menu_secondary_links_source',
  ));
  // Save the updated list of translatable variables.
  $controller->setRealmVariable('list', array_unique($translatable_variables));
}

Update: This is not the way to do it, unless you are using an old version of Variable translation module (< 7.x-1.7)

The names of the translated variables are stored in the i18n_variable_conf variable. This variable itself cannot be exported using Strongarm (or similar solution). I ended using an old trick: checking the variable in a hook_init implementation and setting it if needed. The array in the foreach controller contains the names of the variables to be translated.

/**
 * Implements hook_init();
 */
function MODULE_init() {
  $i18n_variable_conf = variable_get('i18n_variable_conf', array());
  $i18n_variable_conf_updated = FALSE;
  foreach(array(...) as $name) {
    if (!in_array($name, $i18n_variable_conf)) {
      $i18n_variable_conf[] = $name;
      $i18n_variable_conf_updated = TRUE;
    }
  }
  if ($i18n_variable_conf_updated) {
    variable_set('i18n_variable_conf', $i18n_variable_conf);
    variable_set('i18n_variable_list', variable_children($i18n_variable_conf));
    cache_clear_all('*', I18N_VARIABLE_CACHE, TRUE);
  }
}

Compared to a feature based solution, this enforce the settings for the configured variables and will cancel any manual edit. This may wanted or not wanted. In my case it was.

My only issue with this solution, is that it had some overhead to each request.


Wrap html in link based on uri component of other field I need to wrap a div in a template file in an a tag whose href comes from a file field. My markup would be something like this:

Title

Sounds easy enough but the uri that I'm given looks like this "public://newsletter/downloads/Issue 95_0.pdf" which renders but when clicked doesn't go anywhere. How can I turn that link into a valid link?

I needed to use the drupal function file_create_url and PHP parse_url to accomplish this.

function newsletter_preprocess_node(&$variables) {

  if ($variables['type'] === 'newsletter' && $variables['view_mode']) {
    // Generate a path to the file based on the download uri
    $path = $variables['field_download'][0]['uri'];
    $path = file_create_url($path);
    $path = parse_url($path);
    $path = $path['path'];
    $variables['download_link'] = $path;
  }
}


Did the bootstrap process change? I've had minimal experience with Drupal 7, and I am migrating over to Drupal 8.

I was curious as to what the flow of execution is when serving up a basic page in Drupal 8. In Drupal 7, this was considered the bootstrap process.

Is there an equivalent in Drupal 8?

The process is rather different. There are some common elements but maybe what can get confusing is how D8 leverages the Symfony Framework.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalKernel('prod', $autoloader);

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();

$kernel->terminate($request, $response);

As can be witnessed by the index.php, things look a bit different. But it is essentially "bootstrapping" functionality. To get a really good sense of what is going on, I would highly recommend reading the following:

https://cipix.nl/understanding-drupal-8-part-1-general-structure-framework

Also, the Drupal 8 Documentation helps to get a good grasp on what is available to work with:

https://www.drupal.org/docs/8/

Especially giving the API's a good looksy:

https://www.drupal.org/docs/8/api

As I said, it's quite different than before. A lot more OOP going on. It's quite powerful and gives developers a lot more tools to work with but if you aren't used to how PSR-0 and PSR-4 autoloading work, you might find it hard to debug and grock.

Good luck and Happy Drupalling!


Send a message when a comment is left I want to send a message to users that have commented on a node each time a new comment is left.

I think I am half way there.

I have created a component of the content type, added a loop that looks at the “node:comments” and set the email up using referenced mail list

I have also created a rule that triggers the component on the event of a new comment.

The problem I have is that I want to exclude the node author as they get notified anyway when a new comment is left in a separate rule.

Also, that if you have left more than 1 comment on the node you get more than 1 email so I need to filter it down.

I am fairly new so as much detail as possible would be appricatied.

Many thanks :-)

David

How about the modules -

Comment Notify

  Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

or

Notify

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.

and see Email notification for new comments


Count flags on user's content In my Drupal 7 site I want to display how many times user's content was flagged.
As option I want to set a global variable counts and display it in different parts of *.tpl.php files. The value can be calculated with flag_get_counts($entity_type, $entity_id) for each user's node_id. Function that calculates counts should be called in template_page_preprocess() to update value each time page is reloaded.

What is more efficient approach to implement this?

The right way is using template_preprocess_node().

Place the following code in template.php of your front end theme:

function YOUR_THEME_preprocess_node(&$vars) {
  // I suppose you don't want to do this for every content type on the site.
  switch ($vars['node']->type) {
    case 'YOUR_CONTENT_TYPE':
      $vars['count'] = flag_get_counts('node', $vars['node']->nid);
      break;
  }
}

This will make the $count variable available in .tpl.php files that are used for displaying nodes of your content type.


drupal_mail() new line \n not working I'm trying to insert a new line in message body using \n but it's not working.
Tried already with \r\n and it doesn't work also.

Any help?

Tks.

Could be a couple things, without seeing any of your code it's difficult to help you.

Try:

Making sure you're using double quotes (") instead of single quotes (') around the new line characters. (This is because PHP does not interpolate strings defined by single quotes).
Setting the Content-Type to text/plain in the mail headers. (If you need HTML in your email, use <br /> for new lines).

Also, you should always use \r\n with emails so the new line is recognized across all platforms.


Calendar module: Where is the pager markup? How can I translate it? This is so driving me insane. I installed this: http://drupal.org/project/calendar

Now I'm trying to get the 'Next' and 'Prev' links in the monthly calendar to translate. Those strings don't show up in string translation, so I decided to look for their origins; where do they come from. Problem is, I can't even find the markup. The rendered final markup looks like

        « Prev      &nbsp;

&nbsp;
        Next »

It has to be somewhere, but where?

The pager markup is not directly related to calendar. It is part of date views, a submodule to the date module. Assuming your date module is installed in sites/all/modules, you can override the markup by copying the templates in sites/all/modules/date/date_views/themes to your themes template directory. You can also see the template preprocess functions in sites/all/modules/date/date_views/themes/theme.inc