Create hierarchical taxonomy url alias with token term:parents using a field other than term:name Sorry, the title is a bit of a mouthful but I will attempt to clarify.

I have a question about pathauto tokens to create a URL alias for a nested/hierarchical taxonomy.

Specifically, I have a taxonomy called Category, which is n layers deep; e.g:

  Category level 01 > Category level 02 > Category level 03

And so on. The question appears to have been asked many times before and there are a number of good solutions, including the following pattern:

  [term:parents:join:/]/[term:name]

This yields the following url alias for the above example:

  category-level-01/category-level-02/category-level-03

Pretty straightforward. This would be perfect except in my example the taxonomy terms are in Chinese.

I need English in the path aliases, so I have set up a new field in my taxonomy called 'Name English'. This gives me the following replacement pattern:

  [term:parents:join:/]/[term:field_name_english]

Which is almost perfect, but the parents default to using the name field, and there does not seem to be an easy way of overriding this. I cannot use the parent taxonomy terms with delta because it's not dynamic; e.g:

  [term:parents-all:1:field_name_english]/[term:field_name_english]

Some taxonomy depths will be deeper than others.

So, in summary, I need to somehow specify an alternate term field to name for the [term:parents] token. To do this I assume I will need to do one of the following:

Create a custom token
Override the current [term:parents] token

Can anyone advise on this? Thanks a million.

Option 1

You could copy the token created by the taxonomy module for [term:parents:join:/] and recreate it in your own module, using your field as a substitute for title.

This would require some familiarity with the token system. There is also a module entitled 'Custom Token' that might be worth a look, though I have not used it.

Option 2

One divergent way I could suggest to get around this is to use drupal's title field to store your english language title, and another field to store the chinese title (*field_chinese_title*).

You could then preprocess the node title within your theme/module to replace $variables['title'] with *field_chinese_title*. You might also have to do this for menu entries and search results, and you would also have to remember to use *field_chinese_title* for views fields etc.

YOURTHEME/template.php:

<?php
function YOURTHEME_process_page(&$variables) {
  if (isset($variables['node']->field_chinese_title['und'][0]['value'])) {
    $variables['title'] = $variables['node']->field_chinese_title['und'][0]['value'];
  }
}

function YOURTHEME_preprocess_search_result(&$variables) {
  // use chinese version of title for search results
  if (isset($variables['result']['node']->field_chinese_title)) {
    $variables['title'] = $variables['result']['node']->field_chinese_title['und'][0]['value']);
  }
}

I admit I have little experience of multi language sites, and I do realise that this method might look a little crude, but I have used a variation (with autonodetitle) to differentiate the titles used by menu entries and nodes (so that menu entries can optionally be more concise) and it works beautifully. For my use case, I later found a module for that...


Drupal Display "Master" Error in View While I'm creating view displays for three of my content types, created first two and auto previews look fine. When I created the third one, the server kinda went down for a while. So I waited till it comes back online, I'm no longer able to auto preview any of the displays, and I'm getting the following error

Display "Master" uses fields but there are none defined for it or all
are excluded.
Display "Page" uses fields but there are none defined
for it or all are excluded.

Help will be appreciated. Thanks

Check to make sure you have at least one field listed under 'Fields.'  If you use a display type that requires fields without any being selected you will see the error noted in your question.

If it's bugging out, try to cancel your changes and refresh the page.  Add a field, save and see if the preview works again.


Drush make and multisite I am building a multisite and each sub-site may have its own contrib modules.

For example:
sites/all/modules/contrib/entity
sites/site1/modules/contrib/views
sites/site2/modules/contrib/services

I build a makefile for the shared modules:

api = 2
core = 7.x
projects[entity][] = ""

And one makefile per subsite which includes the global makefile:

includes[] = "make.yml"
projects[views][] = ""

The inclusion works properly but I can't get the modules being downloaded in different directories.

I try to run the drush make command with --contrib-destination=sites option, add defaults[projects][subdir] = all/modules/contrib in the global makefile and to specify a subdir for each sub-sites's specific module projects[views][subdir] = "sites1/modules/contrib". No luck, the modules are downloaded in sites/modules/all/modules/contrib and sites/modules/site1/modules/contrib instead.

Is there any way to get it working? I now think to add some custom code to a script to run after the drush make command to move specific modules to proper directory.

Thanks,

By checking the drush code itself, we discovered the possibility to add contrib_destination on specific project level.

projects[views][] = ""
projects[views][contrib_destination] = "sites/site1"

However, as it would had quite a lot of lines to the makefile (we must add the contrib_destination line to all modules used by site1 only) we decided to not use the includes feature and to keep to separate makefiles.

To build our docroot, we then have one "global" makefile to prepare the sites/all modules and another ones for each subsites (sites/site1). Then we launch the drush make command for each makefile (using a shell wrapper to handle it).

This is not perfect and would probably be easier to have something build-in (I don't know what would be the best syntax for that).


How to migrate multi role to an user using migrate csv plugin I have migrated bunch of users using the Migrate Source CSV and am succeeded in it, But I want multi-roles to be defined for single user.

Here is my config file,

Here is my following cases that I have tried out in a CSV file and it failed,

Is there is anything am missing out?

First put your all roles inside double quote separating by comma (,) and be sure that your all roles on csv file must be role's machine name.

then edit your config file something like this....

process:
  name: name
  mail: email
  pass: password
  roles:
    plugin: explode
    delimiter: ','
    source: roles
  status: status
destination:
  plugin: 'entity:user'
  md5_passwords: true

you have to use plugin: explode provided by drupal to import multiple roles separated by comma (,).

And if you are importing password also then use md5_passwords: true


Change node language from Language neutral to English in bulk using VBO I have enabled entity translation and multi-language feature to an existing Drupal site. Currently all nodes in the site are set as Language Neutral, so the translation tab wont appear. If I edit a node and manually change the language to English the translation tab will appear and I can add the translated content for other languages.

I've tried the VBO - Modify entity values operator method mentioned at How can I set the language of nodes in bulk to existing content when making a site multilingual? but after changing the language from language neutral to English via VBO, the body content is not displaying when I edit the node later. The body content will appear if I change the value back to language neutral. It looks like the language of the field body is not change with the view bulk operations.

Is there any way I can can do a bulk operation and change the language of the nodes in bulk so that the nodes are translatable?

Thanks

Oh, yes, I remember this pitfall. Here's what happens: assuming the default language of your site is English, any Language Neutral node is assumed to be English. If you look at the node table in the database, you'll see that their language is 'und'. This is per content type, so let's say we have Language Neutral Basic pages. If you now add a Basic page with language English, its body won't be displayed, though if you check the database, you'll see that it's there (and the node's language is 'en').

The moral: all English-language nodes of the same content type must have language set to either 'und" or 'en', or the ones set to 'en' won't display. On our site, we set the critical content types to Require language (Don't allow Language Neutral). (Under Admin -> Structure -> Content types -> Edit -> Multilingual settings.)


How do I programmatically create a simple 'page' node? I have already found Drupal 6 documentation on how to programmatically create a page node.
How is it possible to achieve that in Drupal 7?

I've changed my strategy, and I'm using another approach, but I'm getting the following error:

  Fatal error: Cannot access empty property in C:\...\...\...\...\modules\field\field.attach.inc on line 198

I'm using the following code:

$form_state = array();
module_load_include('inc', 'node', 'node.pages');

$node = array('type' => 'page');
$form_state['values']['uid'] = 1;
$form_state['values']['name'] = 'admin';

$form_state['values']['title'] = 'Programatic Page';
$form_state['values']['language'] = 'en';

$form_state['values']['body']['en'][0]['value'] = 'My own value';
$form_state['values']['body']['en'][0]['summary'] = 'My own summary';
$form_state['values']['body']['en'][0]['format'] = 'filtered_html';

$form_state['values']['menu']['enabled'] = 1;
$form_state['values']['menu']['link_title'] = 'Auto-page';
$form_state['values']['menu']['description'] = 'Own Programatic Page';
$form_state['values']['menu']['parent'] = 'main-menu:0';
$form_state['values']['menu']['weight'] = 5;

$form_state['values']['path']['alias'] = 'auto-page';
$form_state['values']['comment'] = 1;

$form_state['values']['status'] = 1;
$form_state['values']['promote'] = 0;
$form_state['values']['revision'] = 0;

$form_state['values']['op'] = t('Save');

drupal_form_submit('page_node_form', $form_state, $node);

Is there anything wrong?

Using Firebug (Mozilla Firefox plugin), I figured out the name of the elements and then fill it with the proper values.
Creating a 'page' node programmatically, in Drupal 7, is done using the following code:

global $user;

$customNode = new stdClass();

$customNode->type = 'page';
node_object_prepare($customNode);
$customNode->uid = $user->uid;
$customNode->name = $user->name;

$customNode->title = 'Your page title';
$customNode->language = 'en';
$customNode->body[$customNode->language][0]['value'] = 'Your value';
$customNode->body[$customNode->language][0]['summary'] = 'Your summary';
$customNode->body[$customNode->language][0]['format'] = 'filtered_html';

$customNode->menu['enabled'] = 1;       // 1 to enable providing a link in main menu
$customNode->menu['link_title'] = 'Your page link title';
$customNode->menu['description'] = 'Your page description';
$customNode->menu['parent'] = 'main-menu:0';
$customNode->menu['weight'] = 2;

$customNode->path['alias'] = 'Your Alias';
$customNode->comment = 1;

$customNode->status = 1;        // 1 means published
$customNode->promote = 0;
$customNode->revision = 0;

$customNode->changed = $_SERVER['REQUEST_TIME'];
$customNode->created = $_SERVER['REQUEST_TIME'];

node_submit($customNode);
node_save($customNode);

This not completely functioning.
The page is being created successfully with all the values, but the link is not shown in the main menu navigation (I mean in the main menu tabs near the Home tab).
I checked it out in the created content and it's there, accessed it via "edit" button, pressed "save" (without editing anything), and it appears in the main menu.

I want it to automatically show when it is created. Do you have any idea?

The Devel project includes a module called Devel Generate for generating dummy content. You could use it as an example. I think the parts you'd need are in the devel_generate.inc file.


How can I find image style SRC from within twig template in view? Why I can't use {{ file_url(node.field_image.0.entity.uri.value) }} in my custom view

The result not like /drupal-8.6.1/sites/default/files/2018-10/gen9C52.tmp.jpeg

Why I can't use {{ file_url(node.field_image.0.entity.uri.value) }} in
  my custom view

Simply because your view does not have access to the node variable object.

You can use Image URL Formatter module. Then add your image field and for formatter select Image URL.


How to set the value of a field "reference to a term" with the use of entity_metadata_wrapper? In a content type with a have taxonomy field "reference to a term" which I want to connect to a webform submission.

I have the following code in rules:

$brancheid = $submissions[$sid]->data[1][0];
$oplossingsid = $submissions[$sid]->data[2][0];
$nodeid = $submissions[$sid]->data[3][0];

$node = node_load($nodeid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$node_wrapper->title->set('done');   // this is working
$node_wrapper->save();
$node_wrapper->field_sector->set($brancheid);
$node_wrapper->field_dienst->set($oplossingsid);
$node_wrapper->save();

After submission of the webform the title is saved. But field_sector and field_dienst (taxonomy reference to a term types) and are not saved. I tried several combinations but do not get it.

What should I do?

Strange. This is not working:

$node_wrapper->field_sector->set($brancheid);
$node_wrapper->field_dienst->set($oplossingsid);

But this is working:

$node_wrapper->field_sector = $brancheid;
$node_wrapper->field_dienst = $oplossingsid;


How it's safe migrate fid and uid? I'm working on a content migration between a d7 and a d8 sites.
I'm trying to use migration and I've a doubt: the d8 site is empty and every user, content, file, term will be filled with migration from the d7 installation.

Is it safe to migrate also ID (uid, nid, tid, fid) from d7 to d8?
Or is better to migrate UUIDS and use them to match content relations?

The core migrations from D6/D7 to D8 do preserve IDs by default. But, it is fragile, you have to be careful not to create any content on the D8 side before you've completed all migration. Unless you depend on public-facing addresses (e.g., /node/[nid]), it's simpler to just allow IDs to be assigned on migration. See https://www.drupal.org/node/2748609#comment-11293627 for more.


Shipping/Delivery Labels in Drupal Commerce I've been searching for a way to print shipping/delivery labels for Drupal Commerce (drupal 7 kickstart). I'm amazed that there still seems to be no real solution to this but rather a series of hacks. I was sure this would be adequately covered or even be part of core! We could do this in Ubercart and yet it seems to have been overlooked in Drupal Commerce.

Anyway, we want to be able to print the labels to a label printer as we process each order from the admin screen. The closest 'solution' is this Print mailing address labels from a view. This isn't exactly ideal as we just need a button next to 'Shipping Address' which prints the label to the label printer.

Using the Themer Devel module it tells us we should be able to override commerce-order--backoffice.tpl.php where we were hoping to inject a print code and customise the print fields using the Print Module http://drupal.org/project/print but drupal refused to see our version of commerce-order--backoffice.tpl.php.

We just seem to be going around and around with this one trying idea after idea getting nowhere, very frustrating that this has been overlooked by Drupal Commerce.

Any ideas much appreciated.
Chris

There are myriad number of ways that people want their shipping labels—some print them pre-cut sheets and other use label printers. Overall, every setup is a bit different.

Ultimately, your shipping label solution will be custom (although calling it hack is a bit much). You can use a view to create a single printable "page" (just use an argument to limit it to a single result) and then just use CSS to style it. If you're wanting to print a whole bunch of them, then leave out the argument and ensure that you're setting the proper page size and putting in your page-breaks properly.


views filter: broken filter - but what's broken about it? I am trying to build a views filter and after a lot of digging into the views-workflow, I think I might have understood the basics. I used a lot of resources 1 2 3 4 and of course doc.logrus.com, but now Views tells me that my handler is broken.

If there is anybody outhere that can help me get my filter-handler working, I would be in a huge debt!

Right now I have the following three files:

ds_regions.module

function ds_regions_views_api(){
  return array(
    'api' => 3,
    'path' => drupal_get_path('module','ds_regions')
  );
}

ds_regions.views.inc

<?php
function ds_regions_views_handlers() {
  return array(
    'info' => array(
    'path' => drupal_get_path('module','ds_regions'),
  ),
  'handlers' => array(
    'ds_regions_handler_filter_view' => array (
      'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function ds_regions_views_data(){
  $data=array();
  $data['node']['ds_regions_filter']=array(
    'title' => t('ds regions view filter'),
    'help' => t('Filters the nodes by region'),
    'filter' => array(
      'handler' => 'ds_regions_handler_filter_view',
    ),
  );
  $data['field_data_field_verein']['table']['join']['node']=array(
    'left_field' => 'nid',
    'field' => 'field_verein_tid',
  );
  $data['ds_vereine']['table']['join']['node']=array(
    'left_field' => 'field_verein_tid',
    'left_table' => 'field_data_field_verein',
    'field' => 'tid',
  );
  return $data;
}
?>

ds_regions_handler_filter_view.inc

<?php
class ds_regions_handler_filter_view extends views_handler_filter{
  function admin_summary(){}
  function option_definition(){
    $options = parent::option_definition();
    $options['misc'] = array('default' => '1');
    return $options;
  }
  function value_form(&$form, &$form_state) {
    $form['custom_filter']  = array(
      '#type' => 'textfield'
    );
  }
  function options_form(){}
  function operator_form(){}
  function query(){
  $table = $this->ensure_my_table();
  $this->query->ensure_table('ds_vereine',$this->relationship);
  $this->query->add_where($this->options['group'],"ds_vereine.plz IN (SELECT ds_plz_distance.plz_first FROM `ds_plz_distance` WHERE ds_plz_distance.distance < 20 AND ds_plz_distance.plz_first=ds_vereine.plz) OR ds_vereine.plz IN (SELECT ds_plz_distance.plz_second FROM `ds_plz_distance` WHERE ds_plz_distance.distance < 20 AND ds_plz_distance.plz_second=ds_vereine.plz) OR ds_vereine.plz IN (SELECT ds_plz_ort.plz FROM `ds_plz_ort` ort WHERE ds_plz_ort.kreis=306)");
  }
}
?>

You are looking at Drupal 6 documentation.

You don't need hook_views_handlers() anymore in D7. Instead, you add the file(s) that contains your views handler(s) to your .info file like this:

files[]=ds_regions_handler_filter_view.inc


Theming a Fieldable Panel Pane — should I define a View Mode? I added a Link field to Panopoly's Image fieldable panel pane, but I need to theme it so the link is silently wrapped around the image rather than displayed textually underneath. It also needs to be easily specified by content editors. (Use case: a full-width front page "hero image". Content editors should be able to specify a link for the image.)

How should I go about defining a new kind of Image FPP? Should I define a new view mode? (Since I want editors to be able to use link-wrapped images anywhere, a solution tied to the front page would be too restrictive.)

Making a field template file would be easier than defining a new mode I think.  That would be the normal way to go about it in Drupal.

In your view under Advanced -> OTHER -> Theme: Information you will find template names for the various fields in increasing granularity.  Create a file with the name that best suits your purposes - in this case probably the one that references just the field name and not a specific view or view mode.

Still inside that window, if you click the field name it will show you the default code for the template file, start with that and then edit to your heart's content.  I suggest using dpm($output); to inspect the content that is being passed to the template file, and following the suggestions in the code comment provided for your view mode.

[edit: I misread, thought you were somehow using these in views.  A template file is still probably the way to go.]


Contextual filter based on base level of taxonomy I've been trying to get the following working for a couple of hours:
I have a views block, it displays a single content type.
The content type has a taxonomy field.
The taxonomy items are structured as this:
- option A
- option B
- option C
- - option C1
- - option C2
- - option C3
- option D

I use the values to categorize the content of the nodes. Each node has a single taxonomy value and displays the view block itself.
I want the view to display all nodes of the same taxonomy (this is no problem for A, B and D). But for content tagged as C1, C2 and C3 I want to show all content within the parent taxonomy, "option c".
I have tinkered with depth and parent fields for relations/contextual filters without success... don't really know what to try next and I can't find and decent resources with similar examples that solves my problem. I would prefer to solve it within the views UI if possible.

If your content type contains a reference field to a taxonomy term with depth, you can use a view block with a normal filter, no contextual filter needed.

Choose 'add filter' > 'Has taxonomy terms (with depth)'
Next screen, select the taxonomy vocabulary (I don't know what it's name is in your case, it should be the vocabulary in which 'option c' is a term) and
set 'Depth' to 1, this will also select the first level of children
Next screen, select the parent term for c1, c2 and c3 (in your case
'option c')

The block will now show all content where the reference field has been used to select option C or it's children.
I used this technique in this site: www.zorgsaamwonen.nl which uses 3 main themes with a lot of child themes.


How do I amend roles for the Administer Users by Role module? I'm using the Administer Users by Role module. I have a role set up as Publisher which has all the boxes ticked under the "Administer Users by Role" option (under People/Permissions as shown in the picture below):

The Publisher can create/edit users. I have created a menu option for the Publisher user, which has a path of admin/people/edit so they can see all the users, and add a user too.

My problem is that when the Publisher amends or creates an account, they cannot see the Role of the user they are amending, so they only have the option to create an authenticated user or amend an existing user, they cannot amend the role for that user.

However, as administrator I am able to see the role option and set accordingly.

Can anyone advise how to allow this for my Publisher role?

A possible scenario to implement what you're looking for is like so:

Use the Flag module to allow a Publisher (any other roles also?) to flag users to indicate that they "want to amend the role for that user" (say you label such flag as "Amend User").
Then use the Rules module to react to (Rules Event) "A user gets flagged with the Amend User flag", combined with a Rules Action to "grant a role to the flagged user" (which could be multiple roles also if needed).
If you need more granularity to be able to do so for multiple roles (like role A for user X, role B for user Y and role A and B for user Z), then just use multiple flags (1 for each role individually).

True, this would require 2 more modules, but pretty sure you'll find lots of other use-cases for these amazing modules (which should be part of pretty much every Drupal site).


How to use Views Page + Attachment to show parent and children nodes? I have a site with a node type Lesson, which has a Category field that points to a taxonomy term.

There is another node type Exercise which is a child to a Lesson node.

I previously figured out how to make one view page for a term url that displays both a parent and child nodes. But I was thinking that maybe it is better to have a page view with an attachment, where the page would display a Lesson node's fields and an attachment would display the children Exercise node's fields.

The page view has relationship set to taxonomy term and contextual filter set to the category. Then it is set to display Lesson fields.

In the attachment view, parent is set to page, relationship is set to a Lesson reference field. But I have no idea what to choose as contextual filter because there is no filter for me to choose that will get me the lesson id. The attachment doesn't seem to have a way to get the parent node id (lesson id) from a contextual filter, since the url will only have the term id.

Any ideas on how to make the attachment display the children of the parent that is displayed in the page view?

Thanks!

It sounds like you're getting stuck messing with relationships in the view - this shouldn't be needed to do what you're trying to do.  You can accomplish this with these basic settings:

Lesson: All your lesson fields + term reference to category

Exercise: All your exercise fields + term reference to category

Your view's page display just needs to be set up to display content of type lesson.

The part that I think you're missing is setting the contextual filter.

Add the contextual filter Content: Has taxonomy term ID
Provide default value -> Taxonomy Term ID from URL

Your attachment should be set to show the exercise content type.  Add the same contextual filter to this display and make sure you have inherit contextual filters checked.

This will give you a page that displays the lesson, followed by all exercises tagged with the matching category.


Proper URI path for views render array I'm fairly new to Drupal and Drupalgap.

My Drupal site has a view/content called "donations".

In admin/structure/views, there are two PATHs: /current-donations and /available-donations.  And of course, this URL works fine: http://127.0.0.1:8083/current-donations

Now I'd like to render this view in drupalgap using a views render array.

My first attempt looked like:

function mobile_donor_donations_page() {
try {
    console.log('mobile_donor_donations_list_page()-e');
    var content = {};
    content['avail_donations_list'] = {
        theme: 'view',
        format: 'ul',
        path: '/available-donations', /* the path to the view in Drupal */
        row_callback: 'mobile_donor_donations_list_row',
        empty_callback: 'mobile_donor_donations_list_empty',
        attributes: {
            id: 'avail_donations_list_view'
        }
    };
    return content;
}
catch (error) { console.log(':ER:mobile_donor_donations_page: ' + error); };
}

The above function gets called fine -- on my console (chrome, Ripple) I see

GET: http://127.0.0.1:8083/?q=/available-donations&page=0
200 - OK
views_embed_view - success - TypeError: Cannot read    property 'count' of undefined

Looking at the views_embed_view() code below, it is throwing an exception
because results.view is undefined:

// Render the view if there are some results, or if there are no results and an
// empty_callback has been specified. Otherwise remove the empty div container for
// the view from the DOM.
if (results.view.count != 0 || results.view.count == 0 && options.empty_callback) {

I tried http://127.0.0.1:8083/?q=/available-donations&page=0 from my
browser, it returns html, not JSON.

To force JSON returned, I tried

path: 'drupalgap/node.json&parameters[type]=donation', /* the path to the view in Drupal */

This PATH does indeed return my content as JSON, however the error remains,
since the JSON doesn't contain a "view" element.

GET: http://127.0.0.1:8083/?q=drupalgap/node.json&parameters[type]=donation&page=0
200 - OK
views_embed_view - success - TypeError: Cannot read property 'count' of undefined

What PATH do I need to supply, or do I need to change structure of my content in Drupal to get the view to render?

Thanks!

Be sure to create a JSON Data Document display for your View with a unique page path, then you can use that path in your DrupalGap Views Render Array. More documentation and examples are available here: http://docs.drupalgap.org/7/Views/Displaying_a_View/Views_Render_Array


How do you display the 'Title' field on display/page for custom content type? I created a content type called 'News' and when creating a 'News' entity, I am able to enter a value for the 'Title' field.

However, when I go to 'Manage display' for the content type, the 'Title' field is not listed as one of the fields that can be managed.

Looking at the page/node for a 'News' entity, the 'Title' field only appears in the breadcrumb.  However, I would like to display the 'Title' field elsewhere on the page (not only in the breadcrumb).

Is there a way to achieve this?

In D8 the title is not handled as a normal field. As example for nodes the title is displayed in two ways:

Block: There is a block "Page Title". You can place this block in any region, it' possible to place it multiple times and the visibility can be configured so that it does not appear on every page.
Template: If the node is not displayed as page, then the title is displayed inside the node template.

You can use the same methods for your custom entity.

The first method should work with any custom entity. If you have a route to the entity and you place the block "Page Title" on your site, then the block should be able to resolve the title of the entity.

For the second method you have to put the title in a variable in preprocess and place it in the twig file.

Edit: You have no custom entity, it is a custom content type. So the title is there already as variable "label" and can be used right away:

node--custom-content-type.html.twig

      {{ label }}

This example is the linked title, but you can simply use {{ label }} if you don't need this.


blocks are not translated in Panels I have a simple panel page containing 4 blocks that are all translated (and set to translatable). However they are always displayed in English (default language).

The taxonomy term is passed as a context and is used to display the page title. And it is also translated (%taxonomy_term:i18n-name)

The rest of the page is translated correctly. I unfortunately don't have much more info to share as this is basically it...

What am I missing here? Thanks for your help!

I am using Drupal 7 and Panels 3

This is a known Ctools issue - there is a patch at comment #49.


How to set specific Meta Tag values while creating Article Content.? I am using Meta tags(Module: Metatag) on my Article content type page. I want to set specific  Meta Tag values depending on Article type I select for example by default check some check box for robots.

Does this possible in Drupal 7. If yes please give sample code for doing the same.

You don't need any code for that, that Metatag module has that functionality built into it

These 2 listed features could apply to your use case specifically:

  Per entity and per entity bundle to control default meta tags for all items of a certain type, e.g. all nodes of a certain content type.
  Ability to override meta tags on each entity object, e.g. to override meta tags on an individual node.


How to theme a form with bootstrap I want to add much HTML to my form elements in order to arrange them on the page, I will be using bootstrap framework to do this.

Which method would be better, to create a twig template file or to use HOOK_form_alter?

If the way to do this would be to create a twig template file, then how can I ensure the form html tags with the form method is also rendered to the page? I have attempted to do this but I don't know how to get the actual form to render, just the inputs are there in the html source code.

I know in Drupal 7 that you had to render something called child elements, but when I check for this array in Kint there is no such thing.

A good starting point is the bootstrap theme. They have a stable version for drupal 8. (It's the most object oriented theme I've seen so far)

  So I would suggest to make your custom theme, as sub-theme of it.

If you want to do it fully by yourself, you would use hook_form alter existing forms (if needed) and theme_hooks/html.twig to add some bootstrap specific classes and change HTML structure.
The mentioned theme is a good starting point to look at all the things that need to be changed.


Prevent JS from showing on specific pages I've got a Javascript that I'd been able to post on every page using Drupal_add_js, and everything was fine till my client's needs changed.

Now I need to show that same JS script on every site page except one node type, and one specific URL and I dont know how to do this.
I'd prefer to do it the Drupal way rather than use JS Injector if I can.

Any help is appreciated!
Thanks
Steph

Following your logic, something along the lines of...

$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type=='TYPE') || $_GET['q']=='PATH') {
  ;
} else {
  drupal_add_js(...);
}

...where you are doing your drupal_add_js(...) should do it.  I think this does it cleaner, but it's late in the logic day here:

$mgo=menu_get_object();
if ((isset($mgo) && $mgo->type!='TYPE') && $_GET['q']!='PATH') {
  drupal_add_js(...);
}

ADDITION:

$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos($_GET['q'], 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

will add js only if you are not looking at a product node or not in a path that starts with user/preference_center/ratings_reviews/ BUT please note that if what is after user/preference_center/ratings_reviews is a node, this won't work because that path is actually node/#, so you will have to then do...

$mgo=menu_get_object();
if (isset($mgo) && $mgo->type=='products') || strpos(drupal_get_path_alias(), 'user/preference_center/ratings_reviews/')===0) {
  ; // do nothing
} else {
  drupal_add_js(....);
}

..instead.


No route found for GET /block-render?_format=xml I have installed render-block 8.x-1.0-alpha1 module in drupal 8 and i try to get all blocks like this:

http://localhost/drupal8/block-render?_format=xml

But i get this message error:

<response>
    <message>No route found for "GET /block-render"</message>
</response>

where is the problem ?

I have installed RestUI module and configured the REST resources for Block Render

admin -> config -> SERVICES WEB -> Rest

and it works now !


How can I delete session? I create $_SESSION['loop'][$id].
When I unset $id = 0 then all of $_SESSION['loop'] are delete.
How can I do this?

$id = \Drupal::request()->query->get('id');

if (isset($_SESSION['loop']) & (isset($id)) & ( $_SESSION['loop'] > 0)) {
  $_SESSION['loop'] = $_SESSION['loop'] - 1;
  unset($_SESSION['label'][$id]);
  unset($_SESSION['code'][$id]);
  unset($_SESSION['price'][$id]);
  unset($_SESSION['sellercode'][$id]);
}

return header('Location: /basket');

I would use this structure:

$_SESSION['mybasket'][$id] = [
  'label' => $label,
  'code' => $code,
  'price => $price,
];

Then you can delete one item

unset($_SESSION['mybasket'][$id]);

or the complete basket

unset($_SESSION['mybasket']);

You don't need the variable loop, to count the items use

$count = count($_SESSION['mybasket']);


Domain Access with URL Alias - same content, but with different automated aliases I have a site running Domain Access with two domains - the primary domain and the sub-domain. Both domains share the same content in the database, but I would like the automated URL aliases for the sub-domain to be different from that of the primary domain's.

There are two tables in the database right now - the url_alias table and the domain_2_url_alias table (of which the latter is a copy of the original url_alias table).

I tried modifying the settings under /admin/build/path/pathauto and selected the sub-domain under the "Save settings for:" option, but that didn't seem to have any effect at all.

I can change the values in domain_2_url_alias manually for each node (which worked), but the site generates new content very often, that this wouldn't be a viable solution.

I appreciate any help I can get! Thanks in advance.

I believe this is exactly what the Domain Path module is for.

According to the module page:

  The Domain Path module allows the creation of separate path aliases per domain for nodes created using the Domain Access module.

However, it looks like this module provides the option per node, rather than offering different pathauto patterns which I think is what you want. There's a postponed request in the issue queue for pathauto integration that offers a partial patch, but it's offered as an anti-proof-of-concept, it seems.


How can we add a date picker in a date field exposed filter? In Drupal 8 am trying to add date pickup popup calendar in our custom search form. Search Page is created by Views page and adding DOB field
by the date field expose.

But there is no option to add date popup calendar in views. While date pop up calendar is showing in the "Add Content" page in admin area.

Any idea how can we show datepicker calendar on date field?

Try the contrib module Better Exposed Filters. At the 'Exposed form' settings in your view you can select 'Better Exposed Filters' after enabling BEF. After selecting the exposed form method you should have more options per field, a datepicker is one of them (on date fields).


Is it possible to pass configuration values as arguments to services? I'm writing a module that makes calls to a Web service to read and store data.
Here's my services.yml file:

services:
  example.connection:
    class: Drupal\Core\Http\Client

I've already a settings form (inheriting from ConfigFormBase) that stores a base URL in configuration, and I'd like to pass that as an argument to the Client class's constructor. I've tried this:

class ExampleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {
    $base_url = $container->get('config.factory')
        ->get('example_entity.settings')->get('base_url');
    if ($base_url) {
      $arguments = array('base_url' => $base_url);
      $container->getDefinition('example.connection')
        ->setArguments(array($arguments));
    }
  }
}

But that gives me HTTP 403 errors for every page on the site. Should it be possible to pass arbitrary arguments like this? Hardcoding a URL into the $base_url variable works fine.

In your services file add the following service:

# The bar configuration for the foo module
config.foo.bar.immutable:
  class: \Drupal\Core\Config\ImmutableConfig
  factory: config.factory:get
  arguments: ['bar']
config.foo.bar.mutable:
  class: \Drupal\Core\Config\Config
  factory: config.factory:getEditable
  arguments: ['bar']

In your service create method add either config.foo.bar.immutable or config.foo.bar.mutable service as an argument.


EntityQuery how to get all delta and good for field_dates I've got these dates linked to a node.

I just want to make a request to render all node when time() is between field_date_value AND field_date_end_value OR time() is < to field_date_value

(ps: time() = 06-26)

I coded this for that :

And my render is :

So I think this code find some good value in database but is returning only 1 case with the first date which is wrong instead of the good which is the second and the third.

My wish :

Thanks in advance.

As far as I can see you could already help your self by making your conditions more simple:

  just want to make a request to render all node when time() is between field_date_value AND field_date_end_value OR time() is < to field_date_value

So actually your final condition (which is equivalent with what you wrote is)
time() < field_date_end_value

Also I advice you to use the request time (from Time service) instead of time: in most of the case is that's what should be used.


How to learn JQuery coming from a Drupal background but with little to no knowledge of Javascript? So here I am in 2012 and although I've been making websites in my spare time for several years, I've managed to get the results I needed by using Drupal and simply cutting and pasting Javascript snippets, etc. when necessary.

Recently, I've got into development more seriously and I have some time to study the right way to do things so I've decided that I'd like to learn jQuery.  Basically, I'd like to make my sites a little more exciting and interactive; in the past, the sites I have built have been praised/criticized as "highly informative but very plain."

That said, I don't know much about Javascript to begin with.  Where should I start?  If it matters all my projects going forward will be in Drupal 7.

I was looking forward to the JQuery and Drupal videos on drupalize.me, but unfortunately I live in Japan and have a slow Internet connection which makes it almost impossible to stream the videos.

Understanding basics of Javascript is very important to effectively use and extend jQuery. http://www.youtube.com/watch?v=v2ifWcnQs6M


How to create flexslider slideshow as a background in drupal 8? My slideshow is working but it is not in the background -- I am using paragraphs that I thought would make it easier for my client to add new images - the "flexslider" is in the header and I did create a twig template to put it in the background - "paragraph-frontage-flexslider.html.twig" ; the "flexslider" is there but not in the background (I modified a slideshow background twig that I found)

[section class="region-header.outer-wrapper" style="background-image: URL('{{file_URL(content.field_background_flexslider_imag['#items'].entity.uri.value)}}');"]
  [div class="overlay"][/div]
  [article]
    {{content.field_background_flex_caption}}
  [/article]
[/section]

Any help would be most appreciated!

Flexslider is a javascript library that makes a bunch of changes to the markup once it is loaded.  Instead of trying to put the images in as background images I suggest using position: absolute on either the flexslider itself, or the items you want to sit on top of it.

You may also need a z-index on some items to bring the to the front or send them to the back.


Drush cache clear corrupting database? I just moved to a new computer: Windows 10 with XAMPP. As far as I know I set everything up the same as it was on my old Windows 7 computer. But now, for some reason, much of the time when I run drush cc all or run update.php, the database gets corrupted. Most frequently, some cache tables' *.idb files (tablespaces) are deleted from my mysql directory, which makes those tables appear as "in use" in phpMyAdmin and prevents them from being edited or emptied. They are always cache tables and never tables that actually get modified by my update hooks. Restoring the database is the only way to fix it then. This is a mature site that I've been working on for a long time, and have never seen this until the new computer. What's happening here?

A sample error message when using update.php, caused by a missing *.idb file:

PDOException: SQLSTATE[HY000]: General error: 1812 Tablespace is missing
for table '(null)': DELETE FROM {cache_field} WHERE
(cid = :db_condition_placeholder_0) ; Array (
[:db_condition_placeholder_0] => field:message_type:6 )
in cache_clear_all() (line 168 of
C:\<path>\includes\cache.inc).

My most recent drush cc all error message, which Google has never even heard of, was:

exception 'PDOException' with message 'SQLSTATE[HY000]: General      [error]
error: 1030 Got error -1 "Internal error < 0 (Not system error)" from
storage engine InnoDB'

In general Drush can't corrupt your database, as it's a software which just sends the SQL queries.

However this error can be related to newer version of MySQL, as of 5.5.7, InnoDB always uses the fast truncation technique (which is equivalent to DROP TABLE and CREATE TABLE). So it no longer performs a row-by-row delete for tables with parent-child foreign key relationships, therefore TRUNCATE TABLE returns an error for such tables.

See: 2.11.1.1 Changes Affecting Upgrades to 5.5

This already has been reported in #2229013 for Drupal core.

So you should either:

consider using different data structures:

non-InnoDB,
use redis/memcached for your cache management (so this won't happen),

try clearing your caches in different way, e.g.

echo "SHOW TABLES LIKE 'cache%'" | drush sqlc --extra=--skip-column-names | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

upgrade your Drupal to 8 and see if the same happens (drush cr),
use different database (maybe will work in MariaDB?),
downgrade your MySQL to <5.5.7,
patch the Drupal core by replacing TRUNCATE with DELETE statement,

You may also consider the condition like if ($mysqlversion > 5.57 AND $cache_table_type = 'innodb') { // DELETE } else { // TRUNCATE }.
or wait until the fix is provided for Drupal core (#2229013).


CKEditor removes HTML/CSS when switching to plain texteditor and back My CKEditor seems to remove formatting in a table when I switch from plain text editor back to rich text editor even though the additional formattibn was added in the rich text editor - it seems to persist whenb I switch to plain text but gets removed when I go back to rich text - I have tried around and Disabled the ADVANCED CONTENT FILTER under /admin/config/content/ckeditor/edit/Full but that did not seem to help,. How can I get my changes to persist even past text editor style switches?

EDIT 1

My configuration under /admin/config/content/formats/full_html looks like below but it still doesn't seem to work correctly (yes, I also cleared my caches):

and I selected Disabled /admin/config/content/ckeditor/edit/Full - ADVANCED CONTENT FILTER

EDIT 2
Now after all these changes , on another page my content doesn't seem to properly display anymore: link http://www.lslib.ca/content/skwlax-wellness-centre problem:
under
 I have a colorbox image declared:

 and it wouldn't show up anymore in HTML and I have no idea why...

My CKEditor seems to remove formatting in a table

You need to add the HTML Table tags

to your Allowed HTML Tags


Problem with multiselect module I've installed the multiselect module, to add this option in a custom form.

The problem is that when I see the options, it shows this:

Does anybody know if there is a way to solve this?

This is the code of the form.

  $form['municipios'] = array(
 '#type' => 'multiselect',
 '#title' => t('Municipios'),
 '#options' => $options2,
 '#required' => TRUE,
  );

($options2 is an array with all the option)

Thank you.

Seems like you are messing up with Multiselect and Improved multiselect modules.

Navigate to [your-site]/admin/config/user-interface/improved_multi_select and disable Improved multiselect settings as below.


How do I do an if conditional based on a view in template.php Related to this question: Adding a body ID to a view page

How do I add a conditional based on whether a page is a view or not? I'm not sure how to test for whether a page is a view.

You can call menu_get_item() and it will return an array containing a lot of information about the path you are on.

Inside that, you can look for

[page_callback] => views_page
[page_arguments] => Array (
  [0] => arg0
  [1] => arg1
)

or similar, and then based upon that, figure out what View you are looking at.

FYI:  It might not be obvious from the documentation, but if you call it without arguments, it returns the information about the path/page you are currently on.


Drush config-import/export I'am trying to export menu items but the generated yaml files does not contains any reference to this elements. All menu files look like this:

uuid: 12....04
langcode: en
status: true
dependencies: {  }
id: how-works
label: 'How it works'
description: 'Menu description'
locked: false

Is there a way to export/import menu elements?

Menu items, content nodes, taxonomy terms, etc. are not handled through the Configuration API. Configuration API is meant to handle... well, configuration.

A fast Google search returned Config menu link.
I have not tested that module, but if it works, it should do what you need there.


i18n - Translate only specific fields Sorry if my question seams trivial, but I wonder if it is actually possible.

In Drupal 7, with the i18n module I can easily translate a content entry, but from this, I feel like it creates a fork of my language source content. So my update on the source language are no longer reflected on the translated content.

Example:
I have a content defined as an image plus a text field.
I want only the text field to be translated, not the image. Can I do that?

I have the situation with a website with many languages, I would prefer if I don't need to update all the images for each language whenever I want to update the image.

The best way to do so is by configuring the multilingual parameter of your node type as "Enabled, with field translation".

The steps :

enable the module i18n_fields
edit your node type
go to publishing options tab
set Multilingual support => "Enabled, with field translation"

This way, there will be only one node for all the translation of your node (e.g.: node/534) and only the translatable fields will change between language.

You need to then define which fields you want to translate :

in the content type, go to manage fields tab
choose the field and edit
check the box "Field translation" at the bottom


Update existing nodes with fields from XML or CSV There are 2 greate modules for importing nodes Feeds and Feed Import. Is there a way to update fields of existing nodes on import from XML or CSV file?

For example, there is an XML feed from another website with products (id + price) and file with additional data for the same products (id + description). How to import both sources into the same node in Drupal?

You need to set up feeds and feeds_xpathparser. You could found a good start for configuring all this here : http://www.drupalprogrammer.co.uk/2012/12/use-feeds-module-to-import-xml-data-in.html

Concerning your concern about updating, you can do this by configuring the guid as your external unique id. In the screenshot provided, you can see in my case the xml tag used for unique id is simply <id>.

Then, you just have to configure the node processor so that it will "Update existing node" when it found a duplicate as shown on the screenshot below.


Wyswig editor not showing to authors in Full HTML mode for Authors I am using wyswig with tinymce 3.5 for my drupal site.
The editor is not working for Authors in FULL HTML mode.it is not showing any action after changing it to plain text or full html.

I have rebuilded permissions also tried Full Html Text format (and wysiwyg) show only for administrator role this solution, cleared cache but its not showing for the authors.
Not able to resolve whether it is permission issue or js.

Also this issue is came after i am using book access module.
Check image for reference.

The issue is resolved as it is js error.
I fixed this issue from this solution(https://drupal.org/comment/6313896#comment-6313896).

As i am using wyswig 7.x-2.1 but the above fix is given for 7.x-2.0 which is applied clearly for my version too.
The below fig. shows that the js error.


How to manage patches in composer when they're merged into the module? I'm building a Lightning BLT project and recently the deploy:build failed because the features module merged a patch composer.json was set to apply.

Is there a way to indicate to composer that the patch is already applied and to skip it?

Edit

Is there a way for composer to know programmatically, perhaps from the module code itself, that the patch has been applied?

Run your deploy build locally and if a patch fails during composer up and you see that it has already been integrated into the module, then delete the patch from composer.json.


How to inject text into the beginning of a textfield? I have a multilingual site with 3 languages where only 1 field (Description) is really multilingual, everything else is a translated interface and strings.

For the Description field, it has been my aim to replicate the functionality of Wordpress's "qTranslate" plugin so that the UI looks something like this:

I have almost managed to achieve this using Fieldgroup module, 3 description fields, and Language Sections module (because I found no better way to assign each field to its language).

So far so good. But at the top of each field I have to put in default texts (=fr  =en= =el=) so that Language Sections module knows which field is which language and displays the correct text depending on which is the current language.  If the end-users delete those =en= and =fr= tags, then the whole thing falls apart.

So I need a module that will inject those =fr= and =en= tags at the beginning of each textfield's entered text, in a way that's completely transparent to the user. Is there such a module?  Can Rules achieve a functionality like this?

Alternatively, if there is no such module, how would one go about creating one? Which function or which hook to use?

UPDATE
I made this module called language_markers based on the answer given by Beebee ,but it didn't work. Can you pleasetellmewhat I'mdoing wrong? :

<?php

function language_markers_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'property_for_sale_node_form' || $form_id == 'property_to_rent_node_form') {
    $form['#submit'][] = 'language_markers_submit_handler_function';
  }
}

function language_markers_submit_handler_function($form, &$form_state) {
  foreach($form_state['values'] as $field_name => $value) {
    switch($field_name) {
      case 'field_description_fr':
        $value = '=fr= '.$value;
        break;
      case 'field_description_nl':
        $value = '=nl= '.$value;
        break;
      case 'field_description_en':
        $value = '=en= '.$value;
        break;
    }
  }
}

UPDATE 2:
I have managed to get this to work with Rules module:

Event: After updating existing content of type Property for Sale

Condition: none

Action: Set a data value Parameter: Data: [node:field-description-en..., Value: =en= [node:field-description-en:value]

It works,but when the end-user comes back to edit the node, he sees "=en=" in front of his text. That's a BAD User-Experience.
This is a work-around, not a solution. I still need a solution.

Do your fields have a different field name per language? For example, maybe they follow some sort of convention like field_description_en, field_description_cn, field_description_de?

If so, then perhaps you can use hook_form_alter and add your own submit handler into the form like so :

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'mytype_node_form') {
    $form['#submit'][] = 'my_custom_submit_handler_function';
  }
}

Then create a function my_custom_submit_handler_function($form, &$form_state). Inside the function you'll need to loop through $form_state['values'] like so and just append your language strings before the values:

function my_custom_submit_handler_function($form, &$form_state) {
  foreach($form_state['values'] as $field_name => &$value) { // <-- forgot the & here... oops
    switch($field_name) {
      case 'description_en':
        $value = '=en='.$value;
        break;
      case 'description_cn':
        $value = '=cn='.$value;
        break;
      case 'description_de':
        $value = '=de='.$value;
        break;
    }
  }
}

There's probably better ways to do it though.

Update

@drupalina I forgot to put the ampersand on the submit handler function which would have updated $form_state. Here's your code with a working version:

<?php

function language_markers_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'property_for_sale_node_form' || $form_id == 'property_to_rent_node_form') {
    // You can remove the texts here too. Below is just an example.
    // Path inside $form may not be correct, so
    // do a var_dump($form) or dpm($form, 'form'); to check the array
    // To use dpm() you need to install "devel" module and enable it.
    #dpm($form, 'form');

    // Trim =fr= string from left side of the #value
    $form['field_description_fr']['#value'] = ltrim($form['field_description_fr']['#value'], '=fr=');
    // You might need to set the #default_value too
    $form['field_description_fr']['#default_value'] = ltrim($form['field_description_fr']['#default_value'], '=fr=');

    // Do this for each language...
    // $form['field_description_de']['#value'] = .......

    $form['#submit'][] = 'language_markers_submit_handler_function';
  }
}

function language_markers_submit_handler_function($form, &$form_state) {
  // Note the ampersand before $value below, which allows the
  // modifications on $value to persist into $form_state
  foreach($form_state['values'] as $field_name => &$value) {
    switch($field_name) {
      case 'field_description_fr':
        $value = '=fr= '.$value;
        break;
      case 'field_description_nl':
        $value = '=nl= '.$value;
        break;
      case 'field_description_en':
        $value = '=en= '.$value;
        break;
    }
  }
}

In my opinion, this would quickly turn very unmaintainable as you get more and more fields & languages combinations. So if you are planning to have more than these description fields, I would suggest to use more general ways to find these fields and automatically remove/add the language strings. For example, using hook_field_attach_presave


YML For Enabling a Contrib Module I am adding a contrib module to a project and I would like the module enabling to happen automatically on deployment. My deployment script pulls the code and runs a config update via drush config-import. What would the YML be to enable the module in the codebase on config update?

To enable a module, you just need a line in core.extension.yml. However, you also need all the configuration the module provides. You could copy that over yourself from the config install and optional folder.

But the usual workflow is that at you enable the module manually at some point, using drush or the UI, then optionall customize the configuration and then export the config and deploy that.


How to delete message entities (message stack) of a special template depending on entity age for the "Private Message" module, my Drupal 8 site uses the "Message" module (https://www.drupal.org/project/message) as substructure.
I would like to build a kind of notification center into the page, which should be possible to implement with the message stack (as I heard).
The trigger to generate such a message will probably be a custom module.
The message module also offers a kind of "auto cleanup", but unfortunately as far as I have seen only for all messages and not per message template.
In principle I only want a notification center, which is triggered at certain events and which cleans itself depending on the message type (e.g. only the last 10 messages of a certain template or delete all messages of a certain template which are older than 10 days).
In general, I guess cleanup does not work, as it would probably also delete the "private messages".
Any hints.

It's possible to override the cleanup/auto delete settings in the message template configuration (even via UI) per template. Just visit the template configuration form.


Template for custom form not working I am trying to theme a custom using a template file but unfortunately I am not getting it by using the below method.
listing.module

function listing_menu() {
  $items['ad-listing'] = array(
    'page callback' => 'adlist_template',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,

  );
      return $items;
    }
function listing_form($form, &$form_state) {

$form['title'] = array(
    '#type' => 'textfield',
    '#attributes' => array('placeholder' => t('Title')),
);
$form['category'] = array(
    '#type' => 'select',
    '#options' => array(
        'default' => '- Category -',
        'Car' => 'Car',
        'Van' => 'Van',
    ),
);
 return $form
}

function listing_theme($existing, $type, $theme, $path){
return array(
  'listing_form' => array(
    'render element' => 'form',
    'template' => 'adlisting',
    'path' => drupal_get_path('module', 'listing') . '/form',
  )
    );
}
function adlist_template(){
    return theme('listing_form');
}

listing/form/adlisting.tpl.php

Contact Information

              <?php print render($form['title']); ?>

              <?php print render($form['category']); ?>

          <?php print render($form['ad_submit']); ?>

I tried to follow this thread How to a use a template file to theme a form? but did not help me, neither other solutions

There were 2 major changes on the code above

I changed the form name to listing_adform()
I changed the hook_menu to call my form not theme

  $items['ad-listing'] = array(
    //'page callback' => 'adlist_template',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('listing_adform'),
  );

Flushed the cache, and I saw my fields rendering using my template in form/adlisting.tpl.php


Views of Node Revision with Revision Update Date Expose filter I have a Views of Node Revision with Revision Update Date Exposed.

Exposed form rendered as "textfield" widget by default, I want to have Date popup calendar instead.

Download and Enable the module 'better_exposed_filters'
Refresh view, then change Exposed form style to use Better Exposed Filters (under advanced).
Under BEF settings, use 'jQuery UI Datepicker' widget.


How to use the Rules module to unset all flags (set x days ago) when cron runs? Case: users set flags on content using Flag module (flags are per user, not global).

Requirement: after a period of time the system should automatically unset these flags using Rules module.

The obvious way to do this would seem to be: when cron runs, fetch all instances of flag that have been set, and unset them.

(In actuality, only flags that were created x days ago will be unset; newer flags will be left. But I can't get the basic setup and this will just be a condition.)

    Event: Cron maintenance tasks are performed
    Action: ??

I can't see a way to get/fetch all flags of a certain type that have been set.

(Obviously I could choose the action Execute custom PHP code and write some code against the relevant flag table... but surely there's a cleaner way of doing this..?)

Can anyone help?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below.

Step 1: Create a Rules Component to unflag a node

Create a Rules Component to unflag (= unset the flag) of a node that was flagged by a given user. Assume you give it a machine name like rules_unflag_node_flagged_by_a_user. Use parameters like flagged_node (for the node) and flagging_user (for the user who flagged). And assume that the machine name of your flag is my_special_flag.

Here is a Rules Component (in Rules export format) you can use for this (using the above mentioned machine names):

{ "rules_unflag_node_flagged_by_a_user" : {
    "LABEL" : "Unflag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "my_special_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node unflagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

Use the Rules "Import Component" facility (located within /admin/config/workflow/rules/components) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it.

Consider the Rules Action drupal_message as for QA-testing only (remove it in your final version, no need for that Rules Action).

Step 2: Schedule the execution of the Rules Component

Create a rule like so:

Rules Event = After a node gets flagged (with the flag you're already using).
Rules Action = Schedule the execution of the Rules Component (created in Step 1), for execution within x days.

Here is a Rule (in Rules export format) you can use for this (using the above mentioned machine names):

{ "rules_schedule_the_unflag_a_node_flagged_by_a_user" : {
    "LABEL" : "Schedule the unflag a node flagged by a user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "flag" ],
    "ON" : { "flag_flagged_my_special_flag" : [] },
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "task" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]"
        }
      },
      { "schedule" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "date" : "+7 day",
          "identifier" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]",
          "param_flagging_user" : [ "flagging-user" ],
          "param_flagged_node" : [ "flagged-node" ]
        }
      }
    ]
  }
}

Some more details about the above rule:

The scheduled date of the Rules Component is within 7 days (cfr. your "x" days).
The identifier of the scheduled task is [flag:name]-[flagged-node:nid]-[flagging-user:uid], which should ensure the scheduled tasks have unique identifiers.
The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed if for whatever reason the same user flags the same node with the same flag (so that it only triggers 1 reminder, and with the most recent date).

Use the Rules "Import" facility (located within /admin/config/workflow/rules) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it (and review the value of +7 day to fit your value of "X days"). Then use the Rules UI to enable the rule (it's disabled by default).

Step 3: Run cron periodically

Rules scheduled for execution using Rules Scheduler, will actually be executed "next time cron runs" (after the scheduled date/time has arrived). So make sure to (a) actually run cron and (b) schedule the execution a bit before the cron job will actually run them.

Example: if you want the unflagging to happen every night at (say) 2 am, schedule the Rules Component's execution at (say) 1:55 am, and make sure cron runs at 2 am sharp.

Notes:

The above logic will only apply to nodes flagged by users after the Rule component (Step 1) and Rule (Step 3) was activated.
No need for custom PHP code.

PS: I'm assuming this question is about D7.


How do I divide a row in sub rows? If I want to divide a row into some sub-rows in Drupal 8, what should the code be?

The following code worked fine for simple tables. I need to do something with the $rows array to divide the rows in sub-rows. How can I achieve this?

$form['mytable'] = array(
  '#theme'  => 'table',
  '#header' => $header,
  '#rows'   => $rows,
  '#empty'  => t('Not Found.'),
);

Drupal 8:

$table = [
  '#type' => 'table',
  '#header' => ['ab', 'cd', 'ef'],
  [
    [
      '#plain_text' => 'rowspan',
      '#wrapper_attributes' => ['rowspan' => 2],
    ],
    ['#markup' => '1'],
    ['#markup' => '1'],
  ],
  [['#markup' => '1'], ['#markup' => '1']],
];

Result:

See Drupal Documentation for a colspan example


for how long is Content considered "new" by the filter criteria "Content: has new content"? I'm trying to find out how Drupal uses the "has new content" filter criteria.  I'd like to create a View that only shows the latest content on the site, but not sure what is going to be returned.  24 hours, 7 days, 30 days?

I don't see any way to set the duration, either.

In Drupal 7, the Views module uses the NODE_NEW_LIMIT. If you look at the code used by the views_handler_filter_history_user_timestamp class, which filters the new content, you will notice the following code (in views_handler_filter_history_user_timestamp::query()).

  // Hey, Drupal kills old history, so nodes that haven't been updated
  // since NODE_NEW_LIMIT are bzzzzzzzt outta here!

  $limit = REQUEST_TIME - NODE_NEW_LIMIT;

  $this->ensure_my_table();
  $field = "$this->table_alias.$this->real_field";
  $node = $this->query->ensure_table('node', $this->relationship);

  $clause = '';
  $clause2 = '';
  if (module_exists('comment')) {
    $ncs = $this->query->ensure_table('node_comment_statistics', $this->relationship);
    $clause = ("OR $ncs.last_comment_timestamp > (***CURRENT_TIME*** - $limit)");
    $clause2 = "OR $field < $ncs.last_comment_timestamp";
  }

The same constant is used from node_mark(), which the function that returns a value used to decide if outputting updated, or new in a list of nodes, such as the one shown by the Tracker module.

  if (!isset($cache[$nid])) {
    $cache[$nid] = node_last_viewed($nid);
  }
  if ($cache[$nid] == 0 && $timestamp > NODE_NEW_LIMIT) {
    return MARK_NEW;
  }
  elseif ($timestamp > $cache[$nid] && $timestamp > NODE_NEW_LIMIT) {
    return MARK_UPDATED;
  }
  return MARK_READ;

The value of the NODE_NEW_LIMIT is the number of seconds in 30 days.

To notice that when you visit the node, "new" is not anymore shown.


Edit link in views leads to wrong node Just before the title field I have added a "Content: Edit link" in several of my views to make it easy to edit nodes. In the Rewrite section for this item I have added this to change the edit symbol:

<img src="/sites/all/themes/mysite/images/application_edit.png" alt="Edit symbol" height="16" width="16">

Now I have discovered that the Edit link redirects to the wrong node. The link looks like this:

www.mysite.com/node/25305/edit?destination=node/24207

How can I make it direct the user to the right node? Should I enable Output this field as a link and add the node ID manually? I am not quite sure how to do that using the replacement patterns.

OK, I solved it the easy way. I enabled "Output this field as a link", added the field "Content: nid" as the first field and then changed my rewritten field to this:

And now it works. Hope this helps somebody.


Exclude a .js file on certain Drupal 6 paths I've run into a dilemma with Drupal and SSL.

I'm utilising the Disqus module, however, Drupal loads the Disqus .js files on all pages including the cart and checkout addresses. This would be fine except that it includes non-secure paths to external JS files that contain more non-secure paths, which means that browsers show SSL errors.

I'm trying to find some way to just exclude these .js files on particular paths. I've seen information on excluding files entirely or including them, but not just from these path's.

Any help would be greatly appreciated, thanks!

I think that this module spits out the reference to the JS file inline in the content.  If this is true, then I would use some logic inside template_preprocess_page to determine whether you are on an HTTPS path, and then search/replace $vars["content"] and remove the string.  You may also be able to use template_preprocess_comment_wrapper to do the same thing.

This solution is pretty hackish, but I think it may be your only solution short of patching the module.


POST JSON data denormalization error I created rest resource plugin in a custom module and need to send some JSON data with the request, and access it in the post function. At the moment my post function does not do anything but return some dummy JSON data so I know it is working.

It seems that whenever I try to pass JSON data with the request, it will give me this error: "Could not denormalize object of type , no supporting normalizer found."

If I then try to get this data using file_get_contents('php://input'), it will give me a 403 forbidden error. But if I try to return the same data that I get from file_get_contents('php://input') from the post function, I get the normalizer error again.

I wasn't able to find much information on even making this REST resource and even less on this issue now, so if anyone has any input I would greatly appreciate it, thanks!

What has always worked for me when I build custom REST resource plugins for 8 is making the request and payload for the request in HAL+JSON format after activating the format for the endpoint. The return data has always come back as just JSON. Since many times I've already built content entities which have their own GET, POST, PATCH, DELETE operations, I generally build the custom REST resource plugins for custom operations which I create. I've only tested overriding the default core operations a few times and then I had to disable the core's REST endpoint on a specific operation to allow my endpoint to take priority. ie. My POST operation is used rather than the core's. I'm currently using the Beta14 version of 8.


Conditionally change the image field style and wrapping it in a div The Article content type has been classified by taxonomy vocab Topic, where each Article's node has one topic.

For some usability and design requirements, I want Articles belongs to a specific topic to render the image field in different image style when it is on the full display mode.

I used the code in node--article.tpl.php:

if ($node->field_topic['und'][0]['tid'] == 154){
     // In some preprocessor...
    $images = field_get_items('node', $node, 'field_image');
    if(!empty($images)) {
      $image = field_view_value('node', $node, 'field_image', $images[0], array(
        'type' => 'image',
        'settings' => array(
          'image_style' => '200x260',
          'attributes' => array('class'=>'center-text')
        )
      ));
    }
    // Testing wrapping the image
    $variables['image'] = "----".$image."----";

    // Now, in your .tpl.php
     $content['field_image'] =  $image;
     }
  print render($content)

The above code renders the image with HTML code like the following:

<img typeof="foaf:Image" src="http://example.com/path/to/image/10_0.jpg?itok=COlIqejP" width="200" height="260">

However, it works fine but has two limitations:

1- I could not able to figure out how to enclose  the image inside a div with css class to style it using CSS. The img tag is supplied only i.e without any wrapping divs or spans!

2- Using it from node--article.tpl.php is not recommended and I have a custom module, but I don't know the suitable node's hook that allows me to perform this task.

You can set wrapper for it with simple way
instead

print render($content);

just use

print '
'.render($content['field_image']).'
;

and for second limitation if you have not $node just need load it with node_load  ( if you have nid)

So before your code

  $node= node_load($nid);


Ajax on Autocomplete does not fire again, if previously fired I am using Drupal 6, and question is regarding autocomplete.
As a part of performance, I am caching the results of AJAX calls, so that if the same values are passed, we dont have to fire ajax call again, and should get the result instantly.

Scenario
I have 2 autocomplete fields, one coming from Drupal taxonomy module, for tags and the other is a custom autocomplete field added via form alter, fetching some other information from custom table.

While I was checking on the Drupal default autocomplete field for tags, I saw that the if I insert the same text, the ajax is not fired.
Like I insert "I", I get some values, change it to "j", I get some other values, If I change it back to "I", NO ajax is fired.
However, for my custom autocomplete field, i am able to see 3 ajax calls.

Can someone please put some light as to how drupal does it, so that even i can implement the same on our custom field as well.
I am using drupal 6, but if you are aware of how it is done in Drupal 7 as well, it would be a great help.

The basic idea behind this is to simply cache the AJAX response of an autocomplete query keyed by the query string itself. Eg.

q = 'I',
cache miss
cache['I'] => [ 'India', 'Indonesia', 'Italy', 'Iceland' ]
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

q = 'In'
cache miss
cache['In'] => [ 'India', 'Indonesia' ]

q = 'I'
cache hit
[ 'India', 'Indonesia', 'Italy', 'Iceland' ]

If you inspect misc/autocomplete.js in Drupal 7, you'd notice that there is a Drupal.ACDB (Autocomplete Database for those curious) object. What's more interesting is the search() method implementation in the same object. You'd notice that given a query string, first the in-memory cache object is looked up first before an AJAX request is made. This is something that you might want to emulate too.


How do I use only a taxonomy term in the path alias? I have content that is tagged with multiple terms from the same vocabulary.
How can I use only the first term the node was tagged with, in the URL structure, e.g. domain.com/first/term/with/depth/node-title?

I am trying to do this with the Pathauto module and Drupal 8, but I can't figure it out. It either grabs all the terms used in that node or none.

I gave this a try and the following pattern seems to be working:

[node:field_tags:0:entity]/[node:title]


It's a way to select by default N/A checkbox I want that if a fields is not mandatory the N/A options on select box is ticked by default.

I have tried to tick default value N/A on the field but after the setting disappear.

I use Drupal 7.15.

Cordially

The default N/A will comes the field is not required(not mandatory) and the value N/A will enter to database enen if you are not selected anything.

If you want a N/A selected . Enter another value named "N/A" and make the field as "Required"
and mark the default value as "N/A"(The new N/A will appear along with the default N/A).

Hope this will helps you


How can publishers create hierarchical taxonomy terms during node creation? I have a chicken and egg problem in terms of allowing users to classify and populate their own sections of the site.

I need users to be able to hierarchically classify their content on the fly. I think this means I can provide them with a term reference field. However, the term reference field only gives a predefined selection. The fully populated taxonomy would need to exist before hand.

I'd like to use taxonomy based URLs to make everything seamless: i.e. /section/subsection/node. I just don't know how to get lay users to easily populate these taxonomies on the fly.

Is there a widget which would allow users to add terms to a term reference field during node creation? AFAIK, only tags can be created on the fly, which doesn't help my URL system.

The Hierachical Select Module allows you to enable on the fly term addition into an ordered taxonomy.

It's unfortunately under minimal developent, but is available for D7 and gets the job done. If there are better options, pleaese let me know, but I think this should handle the above use case for now.


Create Taxonomy with Hierarchy from an Array How might I create a vocabulary full of taxonomy with a hierarchy from an array such as this:

$vocab = array(
  'level1-1' => array(
    'level2-1' => array(
      'level3' => array(),
    ),
    'level2-2' => array(
       'level3' => array(
         'level4' => array(),
       ),
    ),
  ),
);

Here is a solution ...

// First create your array of terms
$terms = array(
  'level1-1' => array(
    'level2-1' => array(
      'level3' => array(),
    ),
    'level2-2' => array(
      'level3' => array(
        'level4' => array(),
      ),
    ),
  ),
);

// Create your vocabulary.
// First check if the vocabulary exists otherwise an error will be thrown when trying to create it.
$vocabs = taxonomy_get_vocabularies(NULL);
$vocab = new stdClass();
foreach ($vocabs as $vocab_object) {
    if ($vocab_object->machine_name == 'vocab_short_name') {
        // Vocab found.  Grab the object.
        $vocab = $vocab_object;
        break;
    }
}
// If the vid is not set then create the vocab.
if(!isset($vocab->vid)) {
    $vocab = new stdClass();
    $vocab->name = 'Vocabulary Name';
    $vocab->machine_name = 'vocab_short_name';
    taxonomy_vocabulary_save($vocab);
}
// Recursive function that will create the hierarchical terms.
mymodule_add_hierarchical_terms($terms, $vocab->vid);

function mymodule_add_hierarchical_terms($vocab, $vid, $parent = null) {

  foreach($vocab as $term_name => $term) {
    // Create the term
    $term_object = new stdClass();
    $term_object->vid = $vid;
    $term_object->name = $term_name;
    if(isset($parent)) {
        $term_object->parent = $parent;
    }
    taxonomy_term_save($term_object);

    if(is_array($term)) {
      // Recursively call the function, passing the term id of the parent.
      mymodule_add_hierarchical_terms($term, $vid, $term_object->tid);
    }
  }
}


I want to show a progress bar during form is submitted and processed until submission is created I am using Form API to create a form on a page and I ask user to submit CSV File which is then process in _submit function for that form. Kindly suggest me a way to add progress bar with Drupal's way. I tried this actually but did not work.

function userop_form_users($form_state) {

  $form['file'] = array(
    '#type' => 'file',
    '#title' => t("Upload CSV file containing information."),
    '#description' => t('Download sample file.
Upload a file, allowed extensions: csv'),
    '#ajax' => array(
        'progress' => array('type' => 'bar', 'message' => t('TestMessage'),'interval' => '1500'),
     ),
    );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  $form['#cache'] = FALSE;
  return $form;
}

The easiest way would be to use the managed_file field type and set the #progress_indicator property to 'bar'.

More details are given in this Drupal Answers answer...


How to turn fieldset to normal field for date field I have a date field that is rendered in a fieldset unfortunatelly. I would like to render it as normal field. I found this for drupal 7  how to avoid fieldset in drupal date field

How can this be done in drupal 8?

Drupal 8 core date field looks like this ....

perhaps your theme is overriding this field type like boostrap or some thing if that is the case find the template file move to your sub theme and change it back to normal.

UPDATE:

But If you are using the Select Widget You have some options:

1) Make css to fix the look of it, a good fast option all you need to do is find the field ID then change the rules for that id only. if not using a custom theme you will need a form alter and attach a custom css library.

2) Override the Field set template if you turn on theme debugging (https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates)
and inspect the element will see the templates that the field uses, you can copy them in to your theme and override them, or create your own theme hooks see my example of hook_theme_suggestions_HOOK_alter on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK_alter/8.2.x


How to display menu link language in List Link view of menu? We have a menu, Main Menu. When we view List Links of that menu we can see all the menu links. However, we do not know which menu link is associated to what language.

What would it take to make the page also display the language on the List Links Display? WE tried to modify the menu.admin.inc file to include the language value that is not working.

Page of interest: admin/structure/menu/manage/main-menu

You're looking at making significant changes to the form builder menu_overview_form (e.g. via hook_form_alter()) or perhaps a complete replacement at the menu route admin/structure/menu/manage/%menu handler (e.g. hook_menu_alter()) in menu_menu().

Looking at the form builder shows the scope of the problem, it is making DB query that you'll need to augment with relevant logic for combining with language column. In addition, there is helper function, _menu_overview_tree_form() that builds out the form elements that is coupled with the $tree structure that's coupled with the result of DB query.

Given that, it might be easier for you to replace the route handler with your own custom form than trying to hack around the existing form. You certainly don't want to start hacking menu.admin.inc as your question implies.


Is it acceptable to change the vid column of a term programmatically in the database? I need to move some terms from one vocabulary to another by retaining all their data: translations, aliases, and node references.

Is it acceptable to change its vid column value directly in the database? The terms don't have hierarchy relationships which needs to be handled.

Database
It's possible to do a lot of things in Drupal simply by making SQL queries, either through Drupal or externally. Generally, you never want to take this approach. There are some cases where it can work just fine, but most of the time there is no reason to do it this way.
API
Drupal has a rich API, this is true for Drupal 6, 7 and 8, as they has always been a key feature in Drupal. In your concreate example, you could use taxonomy_term_load and taxonomy_term_save to facilitate an update of a term. Doing it this way, you can edit any data part including the vid. Just because you do it with API's doing forbidden things wont just automatically work, but the chance of things going well is drastically improved.
In this concrete example the API doesn't do anything that is necessarily needed. It sets some internal data on the term and invoke hooks letter module know that is has been updated.
You should note that things can break, if the term you want to change is part of a hierarchy. Things can also break for nodes referencing the term, if the field is not allowed to reference terms in the new vocabulary.
Migration
Migration of data is the bullet proof solution, and unless you have a huge data set, it can be developed and executed pretty easily. The idea is to create a new term and migrate the content you want to migrate and then delete the old term. As an update hook, sample code could look like this:
/**
 * Put in modules .install file, replace xxxx with 7000 or higher
 */
function MODULE_NAME_update_XXXX(&$sandbox) {
  $term = taxonomy_term_load(CONSTANT_WITH_TID);
  $new_term = clone $term;
  unset($new_term->tid);
  unset($new_term->tid);
  $new_term->vid = CONSTANT_WITH_VID;
  taxonomy_term_save($term);
  // Find all nodes we want to update and update them.
  // If there is a lot of nodes, can use $sandbox to make this a batch job.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->fieldCondition('field_which_is_term_reference', 'tid', $term->tid);
  $result = $query->execute();
  foreach (node_load_multiple(array_keys($result['node'])) as $node) {
    $node->field_which_is_term_reference[LANGUAGE_NONE][0]['tid'] = $term->tid;
    node_save($node);
  }
  // Migration all done - delete the old term.
  taxonomy_term_delete($term->tid);
}

Please note that the above code is pure example code, written by heart. Might have syntax error or other errors and makes a lot of assumptions. This is just to illustrate an idea and demonstrate that a migration might not be a big deal.


How can I access the variable from other .tpl.php file? I am working on Advanced forum. And for my need I am editing advanced-forum.naked.post.tpl.php and I want to add the author name at one place. But this template do not have author name, but it has entire author pane printed. Now the variable for the author name is in advanced-forum.naked.author-pane.tpl.php. And it has a author-name code

<?php /* Account name */ ?>
      <div class="author-pane-line author-name">
        <?php print $account_name; ?>
   </div>

now if I am direct pasting this code to advanced-forum.naked.post.tpl.php, it shows error, that variable is not defined.
Moreover, both this tpl files are in the advanced forum module/style file. So, how can I access that variable in that .tpl.php file? Very Thanks.

You can add custom variables using hook_preprocess_node() in your theme's template.php file.

Here's how to add the account name:

function YOUR_THEME_preprocess_node(&$variables) {
  $variables['account_name'] = format_username($variables['account']);
}


How will I access inner fields values in twig template I want to access 'name' key in the given image, but when I am trying with this
author_picture['#user'].contents.name its showing nothing.

Similar question for the node id from today Reason for adding .value to access node id?

Either add .value to the field name

{{ author_picture['#user'].name.value }}

or use a specific method if the entity provides one:

{{ author_picture['#user'].getdisplayname }}

It is preferable to use  User:getDisplayName because it does extra processing:

  By default, the passed-in object's 'name' property is used if it
  exists, or else, the site-defined value for the 'anonymous' variable.
  However, a module may override this by implementing
  hook_user_format_name_alter(&$name, $account).

  Return value

  string|\Drupal\Component\Render\MarkupInterface Either a string that
  will be auto-escaped on output or a MarkupInterface object that is
  already HTML escaped. Either is safe to be printed within HTML
  fragments.


Results in view page having multiple duplicate result I am having a gallery view page taken from a content type which is displaying the results based on relationship and contextual filters. I am getting multiple fields of a node that seem to be duplicates, even though I have checked the reduce duplicate check box in contextual filter field.
Anyone can help on this issues to get perfect value.

What version of Drupal/Views are you using?
In Views v7.x-3.x you can use hook_views_pre_render() in your template.php file or in a module to filter duplicate results like this:

function YOURTHEMENAME_views_pre_render(&$view) {
  $used_nids = array();
  $new_view_result = array();

  if ($view->name == 'YOURVIEWNAME') {
    foreach ($view->result as $row) {
        if (!in_array($row->nid, $used_nids)) {
          $new_view_result[] = $row;
          $used_nids[] = $row->nid;
        }
    }

    $view->result = $new_view_result;
  }
}


How to add a prefix - suffix to a view title I am using Drupal 8. I want to add Prefix and suffix to view title.
I tired with following code but in result html is not rendering.

function Hook_preprocess_page_title(&$variables) {
$variables['title_prefix'] ='

';
$variables['title_suffix'] ='

';

}

Result

My Title

The variables title_prefix and title_suffix will be rendered using Twig, and therefore filtered from markup and potentially harmful code.

If you like to use HTML within Twig variables, you need to use an instance of the Markup class:

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK() for page_title.
 */
function mytheme_preprocess_page_title(array &$variables) {
  $variables['title_prefix']['#markup'] = Markup::create('

');
  $variables['title_suffix']['#markup'] = Markup::create('

');
}

PS.: The above hook would add the markup to all titles. If this really is your intention, consider altering the page-title.html.twig template instead.


Change a label in a View to a div? How can I change the label for a view to be a div instead? Here is my HTML, its the "Sort by" label I need to change.

<form class="ctools-auto-submit-full-form views-exposed-form-author-content-panel-pane-1 ctools-auto-submit-processed" action="/" method="get" id="views-exposed-form-author-content-panel-pane-1" accept-charset="UTF-8">

  Sort by

Date

Popular

<input type="hidden" name="sort_bef_combine" value="created DESC">

      <button class="ctools-use-ajax ctools-auto-submit-click js-hide btn form-submit" id="edit-submit-author-content" name="" value="Apply">Apply</button>

</form>

The template responsible is views-exposed-form.tpl.php. Within the template the code below prints the form:

      <?php print $widget->widget; ?>

I've done a dsm on the $widget but the array just contains the full HTML.

Ive looked at hook_form_alter and done a dsm on this but in the full form array I still cant see a way to change the form label to a different element.

Looks like you are using better exposed filter module, it has option to configure the sorting label

so instead of Sort By
Sort by
 it will not replace the label but give you a nested div if that works for you.


implementation of hook_menu() is not working I want a page where a user can create 3 different content types : "Machine" , 'Equipment" or "Services" .
My goal is to implement 3 tabs for each content type node creation form.

I implemented hook_menu like below :

function MyMODULE_menu() {

  $items['instrument'] = array(
    'title' => 'Instrument',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );

  $items['instrument/machine'] = array(
    'title' => 'Machine',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'product_node_form',
  );
  $items['instrument/equipment'] = array(
    'title' => 'Equipment',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'equipments_node_form',
  );
  $items['instrument/service'] = array(
    'title' => 'Service',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => 'member_profile_node_form',
  );

  return $items;
}

After enabling my module, I expected that the menu item should be in main menu, but it wasn't there and I got a 'page not found error' when targeting "mywebsiteaddress/instrument" .

Where is my mistake?

There are 2 things going on: you've not defined the permissions on the menu & you've not defined the page callback for when the 'instrument' path is accessed. Without this, Drupal doesn't know when or what to display for your 'instrument' menu item.

Doing something like this:

  $items['instrument'] = array(
    'title' => 'Instrument',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    //@TODO: define a function called mymodule_instrument_page_callback
    // that will render the page for the 'instrument' path.
    'page callback' => 'mymodule_instrument_page_callback',
    // Setting 'access arguments' => array('view content')
    // will allow anyone with the 'view content' permission to view the menu item.
    //'access callback' can be used for dynamically determining access
    'access arguments' => array('view content'),
  );

Will make your menu item available. See the hook_menu() docs for information on page & access callbacks.


Can I stop D6's email sending to blocked users? I have a few actions. They send email to authors.
The problem is, I don't want emails to be sent if the user is blocked.

Any suggestion is appreciated.

ps: I couldn't create a tag on drupal.stackexchange.com . So tagging this custom-module for posting sake.

You could use hook_mail_alter() to check the mail before it's send and filter it depending on your conditions.


How do I change ID to a custom one? How can I change the view block ID from block-views-portfolio-view-block to portfolio?

Add this to your theme's template.php file:

function THEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-portfolio-view-block")
    $variables['block_html_id'] = "portfolio";

}


Unpublish blog content after a certain time I have blog content (created with the Blog module). I want to create an archive which has 30 days of time. After that when we click on archive it will unpublish the blog content. Any idea how to do it?

https://drupal.org/project/scheduler

  This module allows nodes to be published and unpublished on specified
  dates.

  Dates can be entered either as plain text or with calendar popups. To
  use calendar popups you need to install the Date Popup module, which
  is part of the Date module.


Is $site_name , $logo ,$site_slogan are part of render array $page? is $site_name , $logo  ,$site_slogan variables values are store in render array $page? or they are independent from $page? if they are independent.then list of variables that have same nature?

The variables you use in templates aren't really part of the render arrays themselves.  They are created by the various preprocess and process functions and added to the $variables array.  By default, those you list are added in either a template_preprocess_page() or template_preprocess_html(), which your theme can have, too.  Look at the source to see what is going on.  For example, the stock template_preprocess_page sets $site_slogan like

$variables['site_slogan'] = (theme_get_setting('toggle_slogan') ?
                            filter_xss_admin(variable_get('site_slogan', '')) : '');

To aid in figuring this out, I suggest installing the Devel module, and looking at the functions that it provides.  For example, you can do

dpr($variables);

to get a dump of everything in the $variables array, or you can do

kpr($page);

to poke through the $page object via Krumo, which is included in Devel.


How do I hide buttons like the "delete" one in a node form? Consider I created a CCK node called assignment, and I am adding assignments with that.

There is a field called "published" with a check box. If the assignment is published, then it should not be deleted.

My problem is how I can hide the "delete" button if the assignment is published. By using prefix and suffix and using display: none; in hook_form_alter() will work, but it is not the secured way. I need something in the Drupal way.

You can use hook_access().
Super simple example will hide button "Delete" automaticaly and disallow deletion of some nodes in any other places in Drupal.

Important note:

  The administrative account (user ID #1) always passes any access check, so this hook is not called in that case.

function MYMODULE_access($op, $node, $account) {
   if ($op == 'delete') {
      if ($node->something != 'something') {
          return FALSE;
      }
   }
}

For Drupal 7 there is hook_node_access() for this stuff.