Image as form submit I am building a custom form inside a block that has a clickable image as submit.

Here the screenshot of the outcome:

Here is the form code:

function my_form($form, &$form_state) {
  $image = '#';

  if (module_exists('my_base') && function_exists('my_base_get_form_settings')){
    $image = my_base_get_form_settings('IMAGE');
    $form['my_text'] = array(
      '#markup' => '<p>'.my_base_get_form_settings('BODY').'</p>'
    );
  }
  $form['submit'] = array(
    '#type' => 'image_button',
    '#src' => $image,
    '#attributes' => array(
                      'style' => 'width:80%',
                      'OnSubmit' => 'my_function();return false;'),
  );
  return $form;
}

I want the image to be clickable and to run the javascript, but without the ugly style of the default button. I didn't find any example that matched my needs.

How to I properly build an image submit in drupal 7? This is obviusly not the right way.

You could try a modification of this: found it here.

<?php
function theme_form_comment_form_alter(&$form, &$form_state, &$form_id) {

  $form['actions']['submit']['#type'] = 'image_button';
  $form['actions']['submit']['#src'] = base_path() . path_to_theme() . '/img/button-off.gif';
  $form['actions']['submit']['#attributes']['title'] = t('Create Comment');
  $form['actions']['submit']['#attributes']['onmouseover'] = "this.src='" . base_path() . path_to_theme() . "/img/button-on.gif'";
  $form['actions']['submit']['#attributes']['onmouseout'] = "this.src='" . base_path() . path_to_theme() . "/img/button-off.gif'";

}
?>


get views customfield php value in another field i create a views in drupal 6.24.set up some field like username and uid,
in third field used customfield php .with my custom php code filled this filed,
in another customfield php want use the value of customfield php value ,how can i do it?
i know with $data->uid (if userid exist im my views filed) can get current row uid.
i test $data->phpcode but return null to me. please tell me about how can i get customfield php in views?

You should use the views_php module instead. It is the successor of Views Customfield PHP. The current module you are using does only render content, but has no value. views_php introduce the possibility to define both value and rendering settings. You should then be able to use the generated value in other fields.


How do I add venue location automatically when user selects a venue? Does anyone know how I can allow a user to select a venue (such as a night club or restaurant) from a node reference autocomplete field and have the address of the venue also displayed.  This assumes that the venue is already in the system along with the venue's address.

The problem I am trying to solve is as follows:  my website allows users to post a comment about a venue which is already in the website's database.  I want the user to be able to enter the comment and type the name of the venue from an autocomplete box.  I don't want the user to have to enter the address of the venue rather have it auto populate.

Any help on this would be greatly appreciated.

Thanks,

Paul

EDIT: Just realized that this post is a few months old. Hopefully you already found a solution to your problem. If not, maybe this can be of use.

If I'm understanding correctly, you would like to have the address appear in the published comment, and comment is a content type. I emphasize published because this method only allows the information to appear in the published node and not within the content creation form (which is unfortunate, because I've been searching for this functionality for my own site). Assuming the above is the case, then I think the best way to do this would be with Rules. These instructions should get you close, I think, but I haven't used the functionality in quite this way before. Once installed:

Add a field in your comment content type that matches the address/location field in your venue content type
Go to admin/config/workflow/rules
Add a new rule, and under "react on event" select "After saving new content"
Add condition "content is of type", and select your comment content type
Add action "fetch entity by id", and in the data selector input/select "node:your-reference-field:nid"
Add action "set a data value", in the data selector drill down to "node:address-field-of-comment-content-type", click continue, click on "switch to data selection" in the new value area if it's not already selected, and then on that data selector field drill down to "entity-fetched:address-field-of-venue-content-type"
Save changes

This should grab the address from the referenced node before the comment is saved, and populate the comment's address field with the referenced venue's address, after the user clicks the save content button but before it is saved.  You're probably going to want to hide the address field in the comment content creation form so that users can't mess with it. It will more than likely just confuse them since they are not directly editing it. Hopefully this helps you out. Like I said before, I haven't used it in quite this way, but I have used it in a similar fashion.

You also might want to check out Entityreference Prepopulate. It allows you to fill an entity reference field automatically within the url. So, if you have a link on the venue page to create a "comment" for the venue, the you can use this module to automatically populate the entity reference field with the venue, making it so that users don't have to make the selection themselves.


I want to add user points whenever user like the page for Facebook. How can I do this? After sharing or like a page on Facebook I want to add userpoints in Drupal 7, how can I do this?

First, you need to have your users login to your site using Facebook API. There are many modules for it, two I know and seen used are:

Facebook Connect
Facebook OAuth

That's the only real way to know "he" on Facebook is "he" on your site.

Then, Facebook will not push it's data to you. So you have 2 cases:

Button "like this page on Facebook" on your page - you can detect it being clicked and make a rule for it, as  Patrick Kenny told in his comment.
Like clicked directly on Facebook - now that's hard. It was discussed on stackoverflow with some apparently good results, and there are tutorials avaliable.

Last but not least - you need to make sure you grant this bonus only once. If not, users could fabricate points by simply repeatedly liking-unliking your page.


URL-Alias for language neutral content I have a page with 8 languages. Most of the content is translated and have a language assigned. But there is one part of the page, where I need language neutral content to show in each language.

If I create a language neutral content, it generates the "Language Neutral" path from the URL-Alias settings. This looks basically like the English path. Thats Ok. But it looks now for every language like the english path. Only the language prefix changes:

/path/to/content
/de/path/to/content
/fr/path/to/content

Is there a way to generate programatically URL-Aliases to this node for each enabled language?

/path/to/content
/de/pfad/zum/inhalt
/fr/chemin/au/contenu

I have found something similar for Taxonomy Terms where it creates a URL-Alias for each term in each language (Pathauto i18n Taxonomy). But I should have this for nodes.

How can I achieve this without creating each alias manually?

You can use the Pathauto i18n module:

  This module provides functionality to create aliases for each
  language. Also this module will be helpful, if you use field
  translation and you want show node on all language with paths,
  different from node/nid.


Different taxonomy term title for menu and term page Need help with one problem, I want to use different term title, 1-st for menu and breadcrumbs, 2-nd for term page

For example in menu and breadcrumbs: "doors"
In term page: "glasses doors"

I thought create special field for alternative title and add to page.tpl but I don't know how I can do it.

Can anybody help?

You can use drupal_set_title() with implementing hook_preprocess_page().

/**
 * Implements hook_preprocess_page().
 */
function mymodule_preprocess_page(&$variables) {
  $langcode = $variables['language']->language;
  $term = menu_get_object('taxonomy_term', 2, $langcode);
  if (!empty($term)) {
    drupal_set_title($term->custom_field[$langcode][0]['value']);
  }
}

menu_get_object() may not work because some module may override the menu entry taxonomy/term/% as mentioned by mxh.

If you want more robust way to retrieve the term object. Please use below snippet.

if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
  $term = taxonomy_term_load(arg(2));
}
if (isset($term) && !empty($term)) {
  // code.
}


How to create custom rules action event conditions? Is there any universal formula or module to create custom rules actions, events and conditions? So that I just have to replace the required values and rest of the code remains the same. I searched, but I did not find such code. I found few, but those were targeted towards a specific need/question.

For example there are lot of things missing. I am using message module to log activity. I am using statuses module and flag 2 (flag 3 is not compatible with the statuses module) I am trying to do following

Log statuses comments. Logs only for "currently logged in user". Cannot determine who commented. for e.g. John commented on your status update. Event available, but only shows current user name instead of who commented.
Log activity for "John liked your status update". No event available.
Similarly, for status updates comments, "likes flag".
John started following you on stackexchange. Event is available, but it also lacks option to tell who followed you. It also only shows current user name. Obviously you do not need your name here, you want to know who followed you.
John mentioned you on stackexchange. Again, instead of john, it will show current user because you do not have any option when setting up the rule.

The simple activities are easily created though.

A "universal formula or module to create custom rules actions, events and conditions" (as is your question), is to write a custom module. To do so, you either create a new module, or you extend any of your existing custom modules. Refer to Drupal custom Rules how to write your own events conditions, actions and custom object (+custom tokens) for a great tutorial about how to do so. The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).

Part 1: Defining the Event, Condition and Action

Define the Rules Event

/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

Define the Rules Condition

/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

Define the Rules Action

/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

Part 2: Coding the custom Event, Condition and Action

Event:

Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the your_module_package_bought in it):

  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

Condition:

To evaluate the Rules condition (to check if it is TRUE or FALSE), the function your_module_condition_package_type is executed using the arguments provided. Here is an example of how such function could look like:

function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

Action:

Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named your_module_action_change_order_status.


D7 how to check does the uploaded photo have EXIF data? I'm using Drupal 7 with module EXIF.
I want to check if uploaded photo have EXIF data if not then don't allow the user to add this content.

If you want to check a file that is being added through a file field on a content type you can use hook_node_presave. Unless you need the exif module for other reasons you can do without this module and just use the exif_read_data function. Make sure to enable to the exif extension in php.

function mymodule_node_presave($node) {
  if ($node->type == 'article') {
    // Still needs some checking here to see if a file is provided
    $fid = $node->field_file['und'][0]['fid'];
    $file = file_load($fid);
    $hasExif = exif_read_data($file->uri, 0, true);
  }
}


How to create rule to redirect an admin after log in to an admin specific node? I have different roles for users of my Drupal 7 site. I have added a rule that whenever an authenticated user logs in they are directed to a node (say node/90). This works fine: both admin and authenticated users are redirected.

However I want that the admin be redirected to a different node say node/25. So I added a new rule and selected under condition that user role is administrator and in action also forced a redirect. However the admin still redirects to node/90. Why so and how can I achieve my use case?

As suggested by NikhilM, I have created a custom module for it and the .module file has

    <?php

function redirect_ad_help($path, $arg) {
  switch ($path) {
    case "admin/help#redirect_ad":
      return '<p>' . t("Redirect") . '</p>';
      break;
  }
}
function redirect_ad_user_login(&$edit, $account) {
 if($account->uid == 1)
  drupal_goto('node->97');
 else
  drupal_goto('node->69');
}

I also tried doing $edit['redirect'] = 'node/97'; instead of drupal_goto() but I am taken to the home page only and not to the desired node.

My guess would be that your rule weights are not as they should be.  If your rule that matches the admin role fires first and your rule that matches all authenticated users fires second then admins will always be redirected to node/90.

Check on the weights.  In your case, you want the more specific rules (the one for admins) to fire second.  So you need to make its weight larger than the more general rule.

Does that make it work for you?  I don't think you should need a custom module for this...

Also - disable the custom module while you're testing this out, to make sure the two are not interfering.


Output data of different content types in same page I have two content types :

Content type 1 named book with two fields author and language
Content type 2 named movie with two fields date and resolution

In my-theme/templates/page.html.twig I want to render a first section with all the books and a second section with all the movies :

Book Author 1

Book Language 1

Book Author 2

Book Language 2

Book Author 3

Book Language 3

Movie Date 1

Movie Resolution 1

Movie Date 2

Movie Resolution 2

Movie Date 3

Movie Resolution 3

How can I achieve that in Drupal 8 and Twig, is it mandatory to use pre-processing and provide the template with the variable, should I create views or blocks and render them in my page... What is the correct way to do that?

A concrete example will be much appreciated !

    {% for book in books %}

{{ [Book Author Here] }}

{{ [Book Language Here] }}

    {% endfor %}

    {% for movie in movies %}

{{ [Movie Date Here] }}

{{ [Movie Resolution Here] }}

    {% endfor %}

These types of problems are usually solved using Views.

You can create a single Page Display in Views listing the two Content Type nodes. Set the Page Path to what your link to that page to be. Add Sort Criteria by Content type so all the book nodes appear before the movie nodes (add more Sort criteria if necessary after that one). Make sure you set the Fields to be Hidden if Empty, since the two CTs you want to list don't share any Fields. Set that under each Field settings, and under Format settings.

Another, probably more common way to build the lists is to create two different Views Displays, one for each Content Type. For example you can create a Page Display to list only the book nodes with the two related Fields, then add Attachment Display in the same View and override it to show only movie nodes. Also override the Fields to show the two Fields you have on movie CT, instead of the two Fields from the book CT. Set the Attachment to show on the Page Display.


Regions not showing in block region demonstration My regions are not showing anymore in my block regions demonstration. However they are showing in my block layout.

The regions also not display on the pages. I don't know what I did wrong. I checked the .info.yml, libraries.yml and .theme but nothing helped. I cleared the cache and still it wouldn't display.

What I did:

Cleared the cache
Checked info.yml
Checked .theme
Checked .libraries.yml
Added blocks to the regions in question

It's pretty hard to troubleshoot, but I would really recommend looking at the .theme file again. It sounds like the region is not configured/configured incorrectly there. Maybe post that here?


File is saved to /tmp directory, despite setting it permanent I have a form, where I can upload a file:

function policies_edit_form($form, &$form_state, $data_array = NULL)
{
  ...
  $form['file'] = array(
        "#title" => "Document file",
        '#type' => 'file',
        '#size' => 22,
        );
  ...
}

function policies_edit_form_validate($form, &$form_state)
{
   $file = file_save_upload('file', array(
           'file_validate_extensions' => array('pdf doc docx'),
                                 ));
   if ($file) {
        // Save the file for use in the submit handler.
        $form_state['values']['file'] = $file;
    }
}

function policies_edit_form_submit($form, &$form_state)
{
  if($form_state['values']['file'] != '')
  {
    $form_state['values']['file']->status = FILE_STATUS_PERMANENT;
    $file = file_save($form_state['values']['file']);
  }
}

Despite I set the status to FILE_STATUS_PERMANENT, the file is uploaded to /tmp directory. After the upload is done, bash commands give this:

bash-4.2$ cd /tmp
bash-4.2$ ls -la 1_1.pdf
-rw-rw-r-- 1 apache apache 111531 Sep 16 16:06 1_1.pdf

And "temporary://" folder in the database:

mysql> SELECT * FROM file_managed;
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+
| fid | uid | filename | uri                 | filemime        | filesize | status | timestamp  |
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+
|   2 |   1 | 1.pdf    | temporary://1_1.pdf | application/pdf |   111531 |      1 | 1379333217 |
+-----+-----+----------+---------------------+-----------------+----------+--------+------------+

How can I upload it to public://policies/ folder? Should I manually set $form_state['values']['file']->uri or there is another way?

Just use a managed file element, it's much easier:

$form['fid'] = array(
  "#title" => "Document file",
  '#type' => 'managed_file',
  '#size' => 22,
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('pdf doc docx'),
  ),
);

Then remove the validation handler and change you submit handler to:

$file = file_load($form_state['values']['fid']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

And you're done; Drupal handles moving the temp file into the right place for you, as well as adding relevant records to the file_managed/file_usage tables.


Can you suggest any alternative for Statistics module? We have a pretty descend traffic to our Drupal website, approximately 600 page views per minute. We have enabled the Drupal statistics module for storing the node page views.

At peek traffic hours, we observed a high usage of Disk I/O wait, and we doubt that it is due to statistics module. Please correct me if am wrong. If yes, kindly suggest some alternative method to implement node view counter.

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits).
Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.


How to add CKeditor Templates Using CKeditor module I am trying to add a new template.

I have modified default.js in

\sites\all\modules\ckeditor\ckeditor\plugins\templates\templates\default.js

By adding a new entry, however after Flushing caches/restarting web server, I still don't see the new template when I edit content.

It was hard to find the information but I succeed:

Copy ckeditor.config.js from the ckeditor module ( sites/all/modules/contrib/ckeditor/ ) to your theme ( sites/all/themes/MYTHEME/ )
Edit the ckeditor profile configuration in Drupal ( admin/config/content/ckeditor/edit/Full ): in ADVANCE OPTION, set Load ckeditor.config.js from the theme path to YES
Modify the ckeditor.config.js from your theme to add your custom template file:

CKEDITOR.editorConfig = function(config) {

config.templates_files = [ Drupal.settings.basePath +   'sites/all/themes/MYTHEME/js/ckeditor.custom.templates.js' ];
//...continue the config file

Copy your image template to sites/all/themes/MYTHEME/ckeditor-tpl/
In your JS theme file ( sites/all/themes/MYTHEME/js/ ) create a file ckeditor.custom.templates.js as following:

CKEDITOR.addTemplates( 'default',
{
imagesPath: CKEDITOR_BASEPATH + '../../themes/boson/ckeditor-tpl/' ,
templates :
    [
        {
            title: 'My template',
            image: 'my-template.PNG',
            description: 'Your custom template.',
            html: 'Hello world!'
        },
    ]
});

it works well for me. Hope it will help someone.


Webform hook field text element I Use Drupal 8.8 with Webform 8.x, in a simple webform with a select list element and a text field element, I need to update a text field element with values resulting from database queries when the user chooses an option from the listbox.

I would like to accomplish this with a PHP code in a custom mymodule. How can I intercept the user's action when selecting a value from the select list?

Besides intercepting the event I also need to know the content of the choice that the user has made on the select list.

How can it be done? Can anyone give me an example?

There are more than one way to do what you are  asking note both these will require you to create a custom module. (I assume you know how to do this or can google it)

here need to change to your form id, and your field names..

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // change to your form id
  if ($form_id == 'webform_submission_contact_add_form') {
    //dump($form['elements']);
    $form['elements']['select_me']['#ajax'] = [
      'callback' => 'MYMODULE_callback_ajax',
      'event' => 'change',
      'wrapper' => 'changethis',
      'method' => 'replace',
    ];

   $form['elements']['TEXTFIELDNAME']['#prefix'] = '
';
   $form['elements']['TEXTFIELDNAME']['#suffix'] = '
';
 }
}
// ajax call back
function MYMODULE_callback_ajax(&$form, FormStateInterface $form_state) {
  $value_selected = $form_state->getValue('select_me');
  if (!empty($value_selected)) {
    // Here do queries then set the value of your text field.

    $form['elements']'TEXTFIELDNAME']['#value'] = $value_selected;
    return $form['elements']'subject'];
  }
}


Twig conditional render if specific field in array of referenced entities contains text In a Twig template, I'm conditionally rendering a sidebar based on whether custom field content.field_body (Paragraphs entity reference revisions field type) contains any items.
{% if content.field_body['#items'] %}

In this article:

      {% for item in content.field_body['#items'] %}
        {% if item.entity.field_subhead %}

            {{ item.entity.field_subhead.value | raw }}

        {% endif %}
      {% endfor %}

{% endif %}

This worked fine until the requirements changed. :)
Now I need to render this entire sidebar
 if and only if one of the item.entity.field_subhead fields in the ['#items'] array contains a value.
{{ dump(content.field_body['#items']|keys) }} returns the following:
^ array:2 [▼
  0 => 0
  1 => 1
]

So the ['#items'] are a regular numerically-indexed array.
Rephrasing the question, is it possible in Twig to write a conditional that returns true if any key of a multi-value field contains a specific field?
This is further complicated by the fact that there may be different Paragraph types referenced here, and only one of these (the "Section" paragraphs type) will contain entity.field_subhead, but there might be any number of Sections.
Bonus points if whitespace returns false.
EDIT: Thanks @Hudri!
For future reference, the code that worked in my case looked like this:
{# Test every Section for non-empty Subhead #}
{% set render_sidebar = false %}
{% for field_item in node.field_body %}
  {% if field_item.entity.field_subhead %}
    {% if not field_item.entity.field_subhead.isEmpty %}
      {% set render_sidebar = true %}
    {% endif %}
  {% endif %}
{% endfor %}
{# If any Section contains non-empty Subhead, render block #}
{% if render_sidebar %}

    {# a bunch of markup #}

{% endif %}

I'd always do data checks on the entity object (in this case node), and not on the render array content. The second part is the magic .entity to get the linked referenced entity from the host's entity reference field:
{% set render_something = false %}
{% for field_item in node.field_entity_reference %}
  {% if not field_item.entity.field_to_check.isEmpty %}
    {% set render_something = true %}
  {% endif %}
{% endfor %}

{% if render_something %}
  <div class="my_wrapper">
    ...content...
  </div>
{% endif %}

Be warned though data behind .entity is usually not cache-safe (but it is cache-safe in this special case with Paragraphs, because their revisioning is directly tied to their host entity)


How to permit users to add more items to a multivalue field conditionally? I'm working on a publication management site and need a multivalue field collection (which contains several file upload fields). Our authors can upload multiple versions of their publication but only after reviewers (or managers) allow it. Basically I would like to hide the "add another item" button and show if certain conditions are met.

Just place this in a custom module replacing what is given in CAPITAL letters:

function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'CONTENT_TYPE_node_form') {
    if (CONDITIONS) {
      unset($form['field_files_collection'][LANGUAGE_NONE]['add_more']);
    }

  }
}


Add attributes to a template based on current node I need to add a style attribute to the .region-content tag in order to set a field-dependent background image.

How do I do this? I have the node in page.html.twig in the page.node variable, but not in region.html.twig, and there doesn't seem to be a way to transfer it from one to the other at that level.

Edit:

This seemed like a good first attempt:

function [THEME]_preprocess_page(&$variables) {
  $variables['page']['content']['#context']['node'] = $variables['node'];
}

function [THEME]_preprocess_region(&$variables) {
  if ($variables['region'] == 'content') {
    var_dump($variables['context']);
  }
}

Unfortunately, that doesn't work - the context variable is still an empty array. How do I transfer context from one theme element to one of its children?

This could be done with a global* variable or something, but that looks horrendously inelegant.

Edit: Well, preferably a call to a function with a static variable, but that still seems like a bad hack.

In Drupal 8 you can get the node object from the routing system:

function [THEME]_preprocess_region(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
}


how can I create special views search I create advanced search with views.
I want type one word and search it in 10 fields that I create in content and show all contents that use "word" in each fields

You can create an exposed view filter using 'global: combine fields filter', and select all the fields where you want to search the 'hello' (or wathever word you want) word. As long as you don't specify a content type, you will get all the elements that contain one of those fields with the written word.

To add the fields to the combine filter you need to have them on the fields you are showing in the view, but you can hide them if you want.

  edit:  this is a solution in D7 and but I think D8 may provide a very similar system.


Show Comment Form on its own Page or Popup I am trying to figgure out how to show the comment form on its own page. So far I have been able to show it on a seperate page. All I had to do was to go to field comment setting and uncheck "Show reply form on the same page as comments"

So this allow the comments to show on a new page. The only issue is that the new page still shows body above. Is there any way to hide the body on the comment form page?

Ideally I would like to load the comment form on a popup or modal. Can this be done with bootstrap modal or Colorbox inline?

You can accomplish this using an extra node template for the page where the comment form is displayed:

In your theme file create an extra template suggestion for the comment form:

function HOOK_theme_suggestions_node_alter(array &$suggestions, array $variables) {
    $route_name = \Drupal::service('current_route_match')->getRouteName();

    if($route_name === 'comment.reply') {
        $suggestions[] = 'node__commentform';
    }
}

Create an extra node template node--commentform.html.twig, and remove just about everything. You probably want to leave the node title, but otherwise there's nothing you need there:

  {{ title_prefix }}
  {% if not page %}

      {{ label }}

  {% endif %}
  {{ title_suffix }}

The comment form is rendered outside this template, so you don't need any of it.


How to add page "Contact us"/"Terms of usage" using a link in the footer but page's content to be in the main content(middle region)? This seems to be a very newbie question. This is what I want to do:

I 'd like to have a link of type "Terms of usage"/"contact us" in the footer, and when the user clicks on it, a page to be appeared in the main region.
How that could be done? Is it possible? Because from what I 've already seen, the page appears in the same theme region with its parent menu.

Do not know the version your using., search for 'overlay' in modules there are many.

In Drupal 7. Grab the following for direction

http://drupal.org/project/admin_path

http://drupal.org/project/context_overlay


Display name of Content Type instead of node Title in Views I have multiple different content types: Part A, Part B, Part C, etc.

What I need, is to display "Part A" in Views, instead of the title of the content. I also need to link to the content.

Is there an easy way to do this? It seems like such a simple thing, but I've found nothing on Google.

I'm thinking of using the Automatic Node Titles module to replace the title with "Part A (username - date)", so is this the best way?

It's simple. Go to your view. Add field >> Content: Type

Then in the field settings, check 'Link this field to the original piece of content'

That's it. You will find content type in each row. and if you click on it goes to node content page.


Show table records in view via hook_form I managed to get things looking a bit better, However I dont know why the checkbox below is showing like the picture. I want to select the checkbox and make it do something with the corresponding article. By the way I have it, will it work? Thanks in advance.

`function rss_list_form($form, &$form_state) {

$results = db_query("SELECT * FROM {rss_table}");
$i = 0;
foreach($results AS $result) {

    $form[$i] = array(
        '#type' => 'checkbox',
        '#prefix' => '
',
        '#suffix' => '
',
    );
    $form[$result->GUID] = array(
        '#type' => 'item',
        '#title' => $result->title,
        '#markup' => $result->description,
        '#prefix' => '
',
        '#suffix' => '
',
    );
    $i++;
}
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);

return $form;

}`

I manage to get things working like I wanted !! So I will include a screenshot and the code for people on the same boat.

function rss_list_form($form, $form_state) {

$header = array(
'article' => t('Article'),
);

$rows = array();
$sql = "SELECT * FROM {rss_table}";
$result = db_query($sql);
    foreach ($result as $dbrow) {
    $rows[$dbrow->GUID] = array(
        'article' =>
        '
'.$dbrow->title .'
'.'
'
        .'
'.$dbrow->description.'
'.'
'
        .$dbrow->date .'
'.''.$dbrow->link.''.'
',
    );
    }
$form['rss_select'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $rows,
    '#empty' => t('No articles found.'),
);
$form['import'] = array(
    '#type' => 'button',
    '#value' => t('Import'),
    '#weight' => 0,
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
);
$form['delete'] = array(
    '#type' => 'button',
    '#value' => t('Delete'),
);
return $form;

}


How to show sub-menu in a block? I have a menu in Drupal 7 with 2 main links like home and about us, but I have 3 sub menu in about us like

About us

About Us 1
About Us 2

I need to show these 2 submenu in a block and show active when about1 same for about2.

Sounds as if you need the Submenu Tree module.

This is an excerpt form the project page:

  Submenu Tree provides a method for structuring content hierarchically. For content which has a menu link, Submenu Tree display a list of content which is at the same level or below the content in the menu.

Is this what you were looking for?


How to grab a user's Fivestar voting value with Rules? On my website, users can rate nodes via comments. The Fivestar field is called 'Stars'. I'd like to use the user's voting value in a rule that's activated when a new comment has been saved. (The rule should update a radioactivity field, called 'Popularity', from the node that's commented on.)

When debugging the 'Stars' field in a comment, I'm able to get exactly the value I need via field_stars['und'][0]['rating']. However, I can't find a way to grab it in the Rules UI. I'm always ending up with comment:field-stars: in an action.

I tried adding a condition 'Entity has field: Parameter: Entity: [comment:node], Field: field_stars'. This gave me the option to dig deeper to comment:field-stars:user-rating, but when I'm using it further on in my rule, it always throws an error "The variable or parameter value is empty."

What's going wrong and how can I solve this?

Edit: After reading this question, I tried solving my problem with the following rule.

{ "rules_new_vote" : {
    "LABEL" : "New vote",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php", "radioactivity", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "field_popularity" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "integer", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "null" : "null" } }
        }
      },
      { "php_eval" : { "code" : "$rating = \u0026drupal_static(\u0027rating\u0027, $default_value = $comment-\u003Efield_stars[\u0027und\u0027][0][\u0027rating\u0027]);" } },
      { "radioactivity_emit" : {
          "data" : [ "comment:node:field-popularity" ],
          "value" : { "select" : "null", "php" : { "code" : "return $rating;" } }
        }
      }
    ]
  }
}

Unfortunately, it doesn't work properly: when saving a comment, the following error is thrown:

  Notice: Undefined variable: rating in eval() (line 1 of
  C:\wamp\www\mysite\sites\all\modules\rules\modules\php.eval.inc(146)
  : eval()'d code).

How can I solve this?

I finally found a solution for my problem. This is my exported rule:

{ "rules_new_vote" : {
    "LABEL" : New vote",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "php", "radioactivity", "comment" ],
    "ON" : { "comment_insert--comment_node_article" : { "bundle" : "comment_node_article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "comment:node" ], "field" : "field_popularity" } }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "integer",
            "value" : {
              "select" : "comment:cid",
              "php" : { "code" : "$comment = comment_load($value);\r\n$vote = $comment-\u003Efield_stars[\u0027und\u0027][0][\u0027rating\u0027\r\nif ($vote == 20) {return -4;}\ r\nif ($vote == 40) {return 2;}\r\nif ($vote == 60) {return 3;}\r\nif ($vote == 80) {return 4;}\r\nif ($vote == 100) {return 5;}" }
            }
          },
          "PROVIDE" : { "variable_added" : { "rating" : "Rating" } }
        }
      },
      { "radioactivity_emit" : { "data" : [ "comment:node:field-popularity" ], "value" : [ "rating" ] } }
    ]
  }
}

The trick was to store the cid as a new variable and to use that value in the PHP evaluation (the proposed values in my code can be changed to your needs). I've no idea why this wasn't possible in an easier way via the UI, but maybe it's a bug in the Firestar module.


The Drupal way of adding HTML syntax within hook_redirect_alter I'm trying to setup client-side redirects instead of server-side redirects.  Since Varnish is being used for caching, I would like that to remain; so the request should not get to Drupal, Varnish should handle the redirect.  Ultimately, using session cookies, I'm trying to have the value for source/referrer path available at the landing page (because redirects clear the original referrer headers).

In Drupal 7, within a custom module, I'm using hook_redirect_alter() to stop the redirect process, then print out javascript to the page to do the redirect.  My question is, what is the Drupal way of adding the below print statement to the page within this hook?

/**
 * Implements hook_redirect_alter().
 */
function mymodule_redirect_alter($redirect) {
  print('

      redirect . '">Javascript is disabled. Click here to continue

  ');

  // This kills sever-side redirect
  exit();
}

Since you cannot specify a 301 redirect in javascript, here is what I did all within hook_redirect_alter() :

function mymodule_redirect_alter($redirect) {
  // If checkbox is set then use URL parameter for redirect, otherwise ignore everything
  if (variable_get('my_checkbox', '') == '1') {
    $params = drupal_get_query_parameters();
    $my_parameter = variable_get('my_parameter', '');

    // Append redirect values seperated by commas if the specified parameter exists
    if (!empty($params[$my_parameter])) {
      $refs = $params[$my_parameter] . ',' . $redirect->source;
    }
    // Otherwise add souce as the value of the parameter
    else {
      $refs = $redirect->source;
    }

    // Create parameters to append to URL
    $params = array('query' => array($my_parameter => $refs));

    // Do the actual redirect with this new parameter
    drupal_goto($redirect->redirect, $params);

    // This kills sever-side redirect
    exit();
  }
}

So the URL mysite.com/original_page will be redirected to a page with URL mysite.com/mypage?redirect=original_page


Duplicate subdirectory in path aliases I have an odd bug that isn't on other drupal install for other domains on my server.

Basically, menus work fine.

However links in the content will look like this:

https://example.com/content/content/node/123

instead of this

https://example.com/content/node/123

which is how it should be.

Interestingly enough this persists in using the l() function in Drupal 7 templates or in views even if I use rewrite output.

This doesn't happen on another Drupal 7 install with a different domain and web directory. I've changed base_url in settings.php and it does nothing and RewriteBase in .htaccess and it does nothing. I flushed all caches. I even changed to a basic theme. None if it made any difference. I'm stumped and about to resort to outputting variables from core. Any help?

With the duplicate sub directory in the URL, or without it, confusingly enough, the node does display and everything works. What is going on?

I figured it out.  I installed pathauto to try and force it to work and realized that the url aliases set on every node had content/ prepended to them as part of a mass import.

I ran this in the mysql console to update them correctly:

update url_alias set alias = REPLACE(alias,'content/node','node');

And problem fixed.


Include external JS/CSS libraries in a module? What is the Drupal 8 equivalent of including external libraries (like sites/all/libraries) for custom modules?

Quoting this blog post

Core API changes in Drupal 8
The drupal_add_js() and drupal_add_css() functions for manual inclusions of JS/CSS files have been removed in favour of library definitions that properly declare their dependencies. As a result of this, all modules and also themes have to declare their libraries in order to include JS and/or CSS files. During the development of D8 the way of declaring a library evolved from a renamed info hook (hook_library_info()) to finally using YAML (like in many other places in D8) by describing the libraries in *.libraries.yml files. The info hook finally was removed fully. See the change record for more information. The new hook_library_info_alter() hook is of course still there.
Another big change is the usage of Composer for dependency management, like many other modern frameworks do. Although Composer is primarily for PHP libraries, it can be used for JS libraries too. Using Composer not only spares you manually downloading the library from Github, etc and afterwards manually extracting and uploading the files to your server, but also eliminates the error source of placing the files into the right directory structure. (Note: Composer integration is not fully finished yet, see: https://www.drupal.org/node/2372815)


Replace UID in view tab with name on user profile page I'm working on a Drupal 8 site. I made a custom page view displaying special content created by the user. The menu tab shows on the user profile correctly by using Pathauto to show the correct address on the primary user profile page using a pattern of: user/[user:field_full_name].
On the tab page created by my custom view, I can't get it to show the user name, only the user ID from the page view path: /user/%user/other-work
I would like the tab's page view URL to show the user's name instead of just the user ID. I already tried different patterns in Pathauto, but it doesn't seem to have that ability. Pathauto does work for fixing the default user page URL, but none of my custom views pages I added. Does anyone know if it's possible for a custom view page like mine to show the user's name instead of the UID in the tab's URL?

To replace UID in view tab with name on user profile page:

follow those steps:

Create a user relationship :

Add contextual filters with User Name

3.Configure your contextual filter ((author) User: Name) like this

Save your configuration.

Result


Drupal 6 will not use updated htaccess 301 information I'm not 100% sure that this is a Drupal problem, but I think there is any issue with my site not flushing the cache. I am trying to change a redirect. I was having some trouble with URL Redirect in the CMS, so I am using the .htaccess file directly. Previously I had set up

redirect 301 /renew https://OLDREDIRECT.com

I just changed that to

redirect 301 /renew https://NEWREDIRECT.com

However, no matter what I do, the site keeps redirecting to the old link.

I have flushed the cache in Drupal, I've flushed my own browser cache, and I even tried running cron, but it will not use the new redirect info in .htaccess.

Does anyone have any idea what might be going on?

Thank you.

.htaccess shouldn't require any cache flushes, restarts of the server, etc. They should just take effect.

If you want to check to make sure that your editing the right file (and your not on a production server) you can always throw and invalid line in your .htaccess file. If it throws back a 500 error, your editing the right file and something is wrong somewhere in it, if it doesn't your're working on the wrong file.


Drupal 7 Breaks CSS Rule Ordering Standards when CSS Aggregation is Turned On Drupal 7 has an interesting bug (some may consider this a feature) when rules are included before an external CSS document is included using @import. The CSS Aggregation engine will let you "bend the rules" by declaring CSS before calling external stylesheets with @import. While there are very different solutions provided here, they both solve the issue.

Example CSS:

This example works with CSS Aggregation turned ON but will not work if CSS Aggregation is OFF.

* { margin: 0; padding: 0; box-sizing: border-box; }
@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';

My assumption is that Drupal 7 CSS Aggregation engine actually fetches the contents of the @import calls and appends the contents to the main file as a subroutine.

Solution:

The solution was to follow the CSS standards by moving all of the @import calls to the top of the document, before declaring rules internally.

@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';
* { margin: 0; padding: 0; box-sizing: border-box; }

While this question was originally marked as "off-topic", I think it's still important to illustrate how CSS is interpreted by the Drupal 7 CSS Aggregation Engine. It should be understood that these two different methods are VERY DIFFERENT in the way they are interpreted since CSS is sensitive to rule ordering.

More Accurate Solution:

The more accurate solution to this problem would be to include the first line in another CSS document, for instance reset.css.

@import 'reset.css';
@import 'header.css';
@import 'component-a.css';
@import 'component-b.css';
@import 'footer.css';

I hope this helps other people understand the nuances of the Drupal 7 CSS Aggregation engine.

Solved my own question. There were rules that came before the @import. So this wasn't a Drupal 7 issue, it was a CSS interpretation error.


Commerce Checkout ignores CAPTCHA I'm running a Drupal 7 web-site with Drupal Commerce and CAPTCHA modules. I have a CAPTCHA challenge set up on the checkout page. Although an incorrect solved CAPTCHA will show an error, the CAPTCHA still gets ignored when I click "Continue to next step", thus the CAPTCHA can be left empty and the site will still take the user to the next form.

The CAPTCHA is added in the CAPTCHA config (admin/config/people/captcha) to the form "commerce_checkout_form_checkout".

Things I've tried (but didn't help):

Add a CAPTCHA field to the form programmatically;
Add "[required] => 1" to said field;
Tried with both the Math CAPTCHA and reCAPTCHA.

How can I make CAPTCHA work on Drupal Commerce's checkout form?

I don't know exactly how your CAPTCHA module works, but one possible problem is that the checkout form uses button level validate / submit handlers instead of the form level handlers your CAPTCHA module might be working through. In Drupal forms, if the button used to submit the form has those handlers, the form level handlers will be ignored.


Error 324 (net::ERR_EMPTY_RESPONSE) Using Drupal 7 and Clean theme and installed Views module. Everything is worked but now, when click Save in Views get this error:

''Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.''

My site is on MAMP local. Whats this problem?

clearing cache might help:

truncate table cache;


Why doesn't drush check for updates of dev versions of my modules installed by composer? I am using Drush (8.0.3) on my Drupal 8 site (8.0.3) to check for updates, but Drush is not checking for updates of any modules that I checked out the dev branch for.

$ drush @mysite ups --check-disabled
Checking available update data for Drupal.                                  [ok]
Checking available update data for Address (address).                       [ok]
Checking available update data for CloudFlare (cloudflare).                 [ok]
Checking available update data for Commerce (commerce).                     [ok]
Checking available update data for Composer Manager                         [ok]
(composer_manager).
Checking available update data for Chaos tools (ctools).                    [ok]
Checking available update data for Domain Registration                      [ok]
(domain_registration).
Checking available update data for Entity (entity).                         [ok]
Checking available update data for Google Analytics                         [ok]
(google_analytics).

I have dev branches of the following modules:

Inmail
SMTP
Rules
Several others not in the list above

Now I have some idea about what may be wrong: I am using Pantheon for my site, and I added these modules to composer.json, then ran composer update to install them.  For dev modules, this adds .git repositories for each dev module.

I then committed all this to Pantheon, which gave me a message about not supporting submodules.  I ignored this message because I could still install the modules on Pantheon, but I now suspect that either this or installing via composer has somehow busted Drush for me.

How can I get Drush to also check for updates to the dev branches of modules installed by composer?

Drush relies on information written by the Drupal.org package manager to determine whether or not updates are needed to modules or core.

If you use git to install Drupal modules, then you may also use the git-deploy module, and it will add the information needed for Drush to do the update.  Git deploy also works for modules installed via Composer using git; Composer uses git to install when using the --prefer-source directive, or when the module version installed is a development version.

If you use the Composer option --prefer-dist, then Composer will install the tarball packaged by drupal.org, which is why git-deploy is not needed in most cases for stable modules.

Note that there is a bug in git-deploy that prevents it from working when the path to the Drupal root contains spaces. There is a patch to fix this problem available in the git-deploy issue queue; see #2672166.


Revisions revert unexpectedly I have a really horrible intermittent bug where a collection of nodes will reset to a previous revision.

Here is an image of the revisions tab on the node:

There are three unusual aspects:

The 'current revision' is at the bottom of the list and has lower vid than the rest.
The date of the 'current revision' is yesterday but the low vid implies it was created a while ago.
The revision log says "Updated by FeedsNodeProcessor" yesterday but the Feeds log tells me "Last run 1 week ago".

I'm hoping someone can point me in the right direction on where to look for a cause since I can't replicate the behaviour.

It feels like the vid in the {node} table has been changed. Along with the created date and revision timestamp.  I'm really not sure how that could happen, though...

EDIT: Current Hypothesis

I have a custom module that updates a field.  It uses a cron queue, so I'm wondering if the queue contains stale node data:

/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();

  $queue = DrupalQueue::get('ih_video_transcripts');
  foreach($videos as $video) {
    $queue->createItem($video);
  }
}

In my queue's 'worker callback', I should probably reload the node in case the object has been left in the queue for some time?  And ensure I set $node->revision = TRUE before node_save?

I tested my hypothesis above and it was correct.  The queue isn't fully processed during a cron run, so there are stale node objects sitting in the queue table in the database.  The solution was to reload the node in the worker callback.

Original Code

/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();

  $queue = DrupalQueue::get('ih_video_transcripts');
  foreach($videos as $video) {
    $queue->createItem($video);
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE PROBLEMATIC PART, $video_node is stale since it is
  // pulled from the queue table of the database and there may have been
  // multiple cron runs since it was created (2 days in my case).
  $video_node->field_transcript_text[$video_node->language][0]['value'] = "My value";
  node_save($video_node);
}

The Fix

/**
 * Implements callback_queue_worker().
 */
function ih_transcript_import_import_transcript($video_node) {
  // THIS IS THE IMPORTANT FIX, reload the video node to ensure
  // we are saving the most up to date data.
  $video_node = node_load($video_node->nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}

Better Fix

Save ONLY the node Id in the queue rather than the entire node.  Also, I added some code to ensure that there are no duplicates in the queue.  My queue table had 64000 records!!

/**
 * Implements hook_cron().
 */
function ih_transcript_import_cron() {
  // Load all Video nodes.
  $videos = ih_transcript_import_load_video_nodes();
  $currentQueueItems = array();
  $claimedItems = array();

  $queue = DrupalQueue::get('ih_video_transcripts');

  // We only want to add an item to a queue if it doesn't already exist in the
  // queue to avoid the queue table becoming massive.  Retrieve a list of
  // node ids that already exist in the queue.
  while($item = $queue->claimItem()) {
    $currentQueueItems[] = $item->data;

    // Store a copy of the claimed items, so we can release them again. We
    // only claim them in order to grab the node Id, so need to release again
    // to allow processing.
    $claimedItems[] = $item;
  }

  // Release claimed queue items to allow them to be processed by other workers.
  foreach($claimedItems as $claimedItem) {
    $queue->releaseItem($claimedItem);
  }

  foreach($videos as $video) {
    // Don't add videos that already exist in the queue.
    if(!in_array($video->nid, $currentQueueItems)) {
      $queue->createItem($video->nid);
    }
  }
}

/**
 * Implements hook_cron_queue_info().
 */
function ih_transcript_import_cron_queue_info() {
  $queues['ih_video_transcripts'] = array(
    'worker callback' => 'ih_transcript_import_import_transcript',
    'time' => '60',
  );
  return $queues;
}

/**
 * Implements callback_queue_worker().  Can also be called independently of cron
 * to import a single transcript.
 */
function ih_transcript_import_import_transcript($video_nid) {

  $video_node = node_load($video_nid);

  $video_node->field_transcript_text[$video_node->language][0]['value'] = $transcript_text->data;
  node_save($video_node);
}


Where do I set the HTML that wraps a module's config $form inputs? I am transferring a module from one site to another. All is well except the modules form (where I set settings, upload images, etc). On the original site this is nicely wrapped in a table with each section being a row, but on my new site the form elements are just placed in one after the other, appearing vertically. This is despite me copying the modules .inc, .tpl and .module files almost verbatim.

I'm new to Drupal in general so am struggling with this a bit. Would anyone know where this is set (what file, what function)?

function gallery_grid_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['gallery_grid'] = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/templates',
    'template' => 'gallery-grid',
    'variables' => [],
  );

  // Draggable table for gallery-grid admin form.
  $items['gallery_grid_draggable_form'] = array(
    'render element' => 'fieldset',
    'file' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/gallery_grid.theme.inc',
  );

  return $items;
}

Contents of gallery_grid.theme.inc:

function theme_gallery_grid_draggable_form($variables) {
  $fieldset = $variables['fieldset'];
  $rows = array();

  // Table for the items.
  foreach (element_children($fieldset) as $key) {
    $fieldset[$key]['weight']['#attributes']['class'] = array('item-weight');
    $rows[] = array(
      'data' => array(
        render($fieldset[$key]['image_file']),
        render($fieldset[$key]['image_url']) . render($fieldset[$key]['image_title']),
        render($fieldset[$key]['delete_row']),
        render($fieldset[$key]['weight']),
      ),
      'class' => array('draggable'),
    );
  }

  // Header and render.
  $header = array(t('Image *'), t('Image Settings'), t('Actions'), t('Weight'));
  $table_id = 'items-table';
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => $table_id),
    'sticky' => FALSE,
  ));

  // Add tabledrag.
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight');
  return $output;
}

Did you look at form templates? The steps change a little if you are using a starter theme, but the basics are the same.

http://themery.com/dgd7/advanced-theming/forms/with-templates


Issue with the cognito module I am running into the below issue :

  The website encountered an unexpected error. Please try again
  later.InvalidArgumentException:
  Class "\Drupal\cognito\Form\Email\UserLoginForm" does not
  exist. in Drupal\Core\DependencyInjection\ClassResolver->getInstanceFromDefinition()
  (line 24 of core/lib/Drupal/Core/DependencyInjection/ClassResolver.php).

I installed the Cognito module.
Its not properly built yet hence on installing it throws an error did not allow me to login into back end.
I tried to manually uninstall the module by deleting the folder and
then i cleared the cache through drush.
Tried re-installing and un-installing the cognito module with Drush
commands as well but still throws the same error.

But this is the error that i get even on clearing the cache.

You can't uninstall modules by deleting them. You need to run the uninstall routine. Via UI (which doesn't work in your case as you can't log in) or via CLI (Drush or Drupal Console).

Put the module back.
Uninstall it via Drush.
Log in.

drush pm:download cognito
drush pm:uninstall cognito
Log in.


How do I Send HTML Emails via Rules? The Rules module provides a value field for the "send mail" action. Since I also have the PHP filter module, I have the ability to add PHP code there. I want to add HTML formatting to my email. Is there a more "correct/Drupal way" of sending HTML based emails via rules other than pasting my code there?

The pet module looks like a decent candidate, but has low-ish usage numbers.

Mimemail or HTMLMail both look like they support Rules.


How to build my SQL statement to export all webform submissions using Forena? I am using Drupal 7.54. and my users are grouped together through a custom user field.

I want to export all webform's submissions for a given group of users in one CSV.

So as suggested in the post How do I programmatically export all webform submissions into a single csv?, I plan to use a custom datablock that fits my need.

I am new to Drupal and don't have much knowledge about how it works and how Drupal stores custom fields in the database.

I couldn't build the right SQL.

What would be the appropriate sql statement in this context?

Have a look at this example SQL, which is a so called "Data Block" I created using the Forena module (disclosure: I'm a co-maintainer), and starting from relative path admin/structure/forena/data:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Some details about the example I'm using here:

5 in the WHERE-clause is the node id of the webform (which I can edit via node/5/edit). For this webform, I want to query some of its submissions (= results (which I can browse via node/5/webform-results).
3 in the WHERE-clause is the component id of the webform (which I can edit via node/5/webform/components/3). This particular component is configured as an eMail field, and these collected eMail IDs is what I want to export to a CSV file.

Adapt the hardcoded values 3 and 5 (in the WHERE clause) to fit your requirements. Or transform them in parameters contained in a data block (use this link if you wonder how to do that). Then save this data block with whatever name you want, eg drupal_cust/webform_submissions_data.

Use it as a prototype to build your custom report from it, using the Forena Report designer in which you select the webform_submissions_data data block mentioned above. Which just a few click you could create a report with a "layout" for which the design (in XHTML format) looks like so (also note the "tokens" shown within the td-tags):

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

Don't forget to select the "document types" you want to enable (to export the report), such as "CSV" (as in your question).

For the sake of completeness: the "layout" of a report is what is contained with the  and  tag. Similar to a regular HTML file, Forena will add an appropriate  and  tag in front of it, and surround everything with   and  tag (and also adds a few more lines at the beginning, to make it an XML file. So that when you save your report specifications, the entire file gets saved in your file system as a so called FRX file (FRX = Forena Report XML). For the above report layout, this is how the corresponding FRX file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>

<title>Webform Export</title>
<frx:category>Webform</frx:category>
<frx:options/>
<frx:parameters>
</frx:parameters>
<frx:docgen>
  <frx:doc type="csv"/>
  <frx:doc type="pdf"/>
</frx:docgen>
<frx:fields>
</frx:fields>
<frx:menu/>
<frx:cache/>


How can open add content form in modal form module I want to load content form (example article content type ) in modal.

As Modal module allow to open forms in modal, but by default it given this feature to some of the form. My question is how can I use this module to add other content type forms.

How can I add content in modal form ?

finally I found my answer, I put it here for another than want do something like this

function mymodule_menu() {
  $items = array();

  $items['mymodule/page'] = array(
    'page callback' => 'mymodule_page',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  $items['mymodule/%ctools_js'] = array(
    'page callback' => 'mymodule_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Helper function to make a link.
 */
function _mymodule_make_link($link_text = '') {
  // Set a default value if no text in supplied.
  if (empty($link_text)) {
    $link_text = 'Magical Modal';
  }

  return '
' . l($link_text, 'mymodule/nojs', array('attributes' => array('class' => 'ctools-use-modal'))) . '
';
}

/**
 * An example page.
 */
function mymodule_page() {
  // Load the modal library and add the modal javascript.
  ctools_include('modal');
  ctools_modal_add_js();
  return _mymodule_make_link('Magical modal');
}

/**
 * Ajax menu callback.
 */
function mymodule_callback($ajax) {
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    );

    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('mymodule_form', $form_state);

    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    }

    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('mymodule_form');
  }
}

/**
 * Drupal form to be put in a modal.
 */
function mymodule_form(&$form, $form_state) {
  module_load_include('inc', 'node', 'node.pages');
$form = node_add('article');
  return $form;
}


Multiple pagers in one page I have a view with two separate displays that is used in one single page. Both the displays are using a pager. To get things working I set a unique id for each pager under pager options. This works and I can use each pager independently. The problem is that the separator used in the url to distinguish between the two pagers is encoded as %2C. So my question is if there is a way to avoid this and if possible even change the character used?

I believe this is only possible by hacking the core pager functionality, so I wouldn't suggest it.

You could add this to your theme

function MYTHEME_pager_link($variables) {
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

You'd need to change this line if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) { to use the separator you wanted.

But you'd also have to change a line in Drupal's core pager include (/includes/pager.inc)

In this function you'd change the character in the explode to what you want to use.

function pager_find_page($element = 0) {
  $page = isset($_GET['page']) ? $_GET['page'] : '';
  $page_array = explode(',', $page);
  if (!isset($page_array[$element])) {
    $page_array[$element] = 0;
  }
  return (int) $page_array[$element];
}

Edit: keep in mind, this will break pagers that are not using your theme which means your admin pagers probably won't work unless you do the same for your admin theme.


How do I find "where-used" / many-to-one related entities? A field in my Content Type A references a Content Type B.

I'd like to find, in each instance of Content Type B, a list of all the As that reference it at a particular point in time.

[Update]:
I made the question less ambiguous in the light of the answer I found with help from others here.

If you want a quick solution in code, you can use the same way as in drupal 7:

Add a field (configurable in view modes):

hook_entity_extra_field_info

Put the code for the field in here:

hook_ENTITY_TYPE_view

Use this code:

How to check if an article is referenced from a collection?


Add field collection table in code I am creating a form to collect data for a specific content type which has a field collection in it.

So basically I am creating nodes manually through form API.
What I need to do is to add a field collection table to my form which corresponds to the field collection I declared in the node type.

I have got how the table is rendered in the original add content form, which is like this:

[field_student_grades] => Array
    (
        [#type] => container
        [#attributes] => Array
            (
                [class] => Array
                    (
                        [0] => field-type-field-collection
                        [1] => field-name-field-student-grades
                        [2] => field-widget-field-collection-table
                    )

            )

        [#weight] => 5
        [#tree] => 1
        [#language] => und
        [und] => Array
            (
                [0] => Array
                    (
                        [#entity_type] => field_collection_item
                        [#entity] => FieldCollectionItemEntity Object
                            (
                                [fieldInfo:protected] =>
                                [hostEntity:protected] => stdClass Object
                                    (
                                        [uid] => 1

But I do not know how to deal with the [und] and [hostEntity:protected] and stdClass Object in code.

You can't access Protected members directly.

you'll need to extend the class that represents that object to provide getter methods for the protected properties.


Node "add" with already set paragraph fields Each of my article nodes has a set of 7 paragraphs elements that must be filled in. Is there some way the client does not have to add them manually each time?

Would I create a hook that adds some kind of auto (default) paragraph entity to the paragraph field when the node is created?

Is this technically possible?

I think I have seen once a module that allows to define default paragraphs via the url.

But I think I am wrong.

Actually it is pretty simple. I have written a module with the following hook:

Hope that helps somebody. Pretty handy and user friendly when it comes to content that is mainly created through paragraphs elements.

You attach the field widgets to the node when the add form is opened.

function xxx_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {

    if("article" === $entity->bundle()){
        $bundles = ['article_navigation_banner', 'call_to_action_banner', 'author_information'];
        $entity_manager = \Drupal::entityManager();
        $langcode = $form_state->get('langcode');

        $field = $entity->get('field_ui_elements');

        $target_type = $field->getSetting('target_type');

        foreach ($bundles as $bundle_name) {
            // Create paragraph and display.
            $entity_type = $entity_manager->getDefinition($target_type);
            $bundle_key = $entity_type->getKey('bundle');

            $options = array(
                $bundle_key => $bundle_name,
                'langcode' => $langcode,
            );

            if("call_to_action_banner" === $bundle_name){

            }

            /** @var FieldableEntityInterface $paragraphs_entity */
            $paragraphs_entity = $entity_manager->getStorage($target_type)->create($options);

            // Field values.
            $field->appendItem($paragraphs_entity);
        }

    }

}


Views exposed pager options I need to hide the pager's exposed options (results per page) when the view has no results. I looked everywhere but can't find anything.

Thanks

There is no intuitive way to do it, but I found a solution using hook_views_post_execute and hook_form_views_exposed_form_alter:

function MYMODULE_views_post_execute(&$view) {
  if ($view->name == 'MY-VIEW-NAME') {
    // Regenerate the exposed form after execute the view query
    $exposed_form = $view->display_handler->get_plugin('exposed_form');
    $view->exposed_widgets = $exposed_form->render_exposed_form();
  }
}

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == 'MY-VIEW-NAME') {
    if ($view->total_rows == 0) {
      // Hide 'results per page' when the view has no results.
      $form['items_per_page']['#access'] = FALSE;
    }
  }
}


Flexible drupal content-types Okay it might sound a little weird for me to ask a question about dynamic content-types seeing as that's what drupal is all about.. however I'm wondering if there is a preferred method to do a page template that will allow you to add hooks in to activate modules within the page.

for example

if I had a simple 2 column layout w/ main content and right rail next to eachother. would it be feasible to create a template that would take an argument (lets say something you can put in the description) like "$rightRail = twitter;" and then the page renders w/ a twitter module in the right rail?

I hope that makes sense. I'm running into an issue where we have a bunch of pages that look similar, except the rightrail has a very different information in terms of modules, etc... and I wanted to see what the best way to unify my template would be.

Right now the team is creating a new content type and page template for each type... and I don't like that.

thanks guys.

I am thinking you are wanting to learn more about blocks.  You could, for example, have a block that output an iframe/html/whatever widget.  In the blocks hooks, you can use all sorts of information to decide when to display it it, eg what page/url, what type of node, etc.  So, for example with twitter, you could grab information/fields from the node it is being displayed next to and customize it appropriately.


Node Reference, and Entity Reference are great; I need “Menu reference” Is there a Menu reference module I can use to attach menus to nodes, and render them on the page?

I have never used the module, but in theory, Block Reference should be able to solve your problem. If needed, I assume you can combine it with Menu Block to set up the menu blocks you need.


Use Rules to Change Field Value By Clicking URL I am creating a simple internal ticketing system which emails customers when the status of their ticket changes (Open -> Waiting on parts). I have set up rules to do this and I haven't had any issues with it. However, I would like to create a way for customers to "unsubscribe" from the emails. I have created a checkbox field named "allow emails" which determines if customers will or will not get an email as a condition for the rule.

I would also like to include a link at the end that if clicked the customer would set the field to "no" or "off".

Note:Customers aren't actual users on the site but are nodes within a "customer" content type. The users are our internal staff that would log in to use the website.

Can rules do this by itself or do I need a separate module?

Thanks

I'm not sure I understand exactly what you need, but the great module Rules Link (https://www.drupal.org/project/rules_link) provides a link that can be attached to any content type or entity, and can also be accessed in Views as a special Rules Link field. When you click the link a preset Rule is triggered. The link passes the node or entity as a parameter to the Rule. There is also the option of using a "Javascript" link that invokes the Rule via AJAX (without reloading the whole node) - I've never used that option, but I suspect that it may help your needs.


Display suite, two layouts for the same node? I'm using display suite with nodeblock and I'd like to have a different layout for the block than the main page. How can I do this?

You can do this by using different view modes.

On the content type edit page (eg. admin/structure/types/manage/page) you can set a default view mode for node blocks of that content type.
On the content type manage display page (eg. admin/structure/types/manage/page/display) configure the full content display mode (or default if you haven't enabled the full content mode) the way you want the full pages to display and configure the view mode you specified in step 1 the way you want the blocks to display.
You mention display suite in your question. You can also create additional view modes using display suite (admin/structure/ds/view_modes)


Using the Profile2 module, how to access contextual information to place a views block on profile page? I'm trying to add a list of author's content to a profile2 page. The profile page is separate from the user account page so I can't use get UID from URL option.

Using the View Default Argument From Context Module I added this code to it.

function views_arg_context_profile2_view($entity, $view_mode, $langcode) {
  context_set('user', 'uid', $entity->uid);
  context_set('profile', 'pid', $entity->pid);
}

Now there is an option in Views Default Argument to pull the ID from context and I place either user or profile in the appropriate text field and it works fine.


How can I report to Drupal what is the translation in a language of a string passed to t()? I'm using Drupal 7. I see that the t() function is responsible for translating terms. Where do I go to find the list of translatable terms? For example, suppose I have t('hello world') in my code.  What file do I edit to tell Drupal 7 that the French version of "hello world" is bonjour toute le monde?

You could browse to the Translate interface page
(/admin/config/regional/translate/translate).
You could use a .po file and import it (en/admin/config/regional/translate/import).

You'll have to enable the Locale module for this (it's in core).
More information is available on Translating a site interface to different languages.


How can I add a captcha to this HTML form I wanted to add a captcha box to this form. The past developer added this form as html within the content editor.. how can i integrate the captcha to this form? I'm relatively new to drupal and work in wordpress but i am not sure how i can integrate the drupal captcha feature to this form.

    <form action="#" method="post">

Name:
            <input id="Name" type="text" name="Name" />

Email:
            <input id="Email" type="text" name="Email" />

Phone:
            <input id="Phone" type="text" name="Phone" />

Leave this empty:
            <input type="text" name="url" />

How Can We Help?

            <textarea id="Message" name="Message" rows="4" cols="30"></textarea>

            <input id="submit" type="submit" name="submit" value="Submit" />

    </form>

I'd say you have two obvious choices :

either you reimplement the form using the drupal webform module and then add some captcha module like recaptcha,
or you keep going the tought html-only route and just see how you can integrate a captcha library within your "html within the content editor" form...

I'd say the first strategy is wiser. Particularly since your form is fairly straighforward.


Drupal Migration Date format On the old server in the database my date column has rows in this format: 2014-10-15 13:00:00

When i do $this->addFieldMapping('field_date_time', 'date');
it imports, but is off by 12 hours.

I've tried various ways to convert it in a prepareRow function but with no luck. Am I missing something?

Sorta embarrassing, but adding the solution to my problem, just in case anyone else runs into this. If you configure the date field in the content type. There is a drop down of time zone handling. Ours got set incorrectly somewhere down the line. After fixing that, and rerunning the migration everything worked as intended.


How do I create a page consist of more than 100 lines, by custom module? I created a page which consist of HTML tags. The code for that is the following one:

function mynewpage_menu() {
  $items['mypage'] = array(
    'title' => 'my page title',
    'page callback' => 'mypage_page',
    'access arguments' => array('administer page'),
  );
  return $items;
}

function mypage_page() {
  $output='html code here';
  return $output
}

Is it the right way to generate a page if i have more than 100 lines? What if I have iframe , img and canvas tags and what if I want to include paths and hyper references?

In what other ways can I generate a page containing 100 HTML tags?

Update:
Am I right in associating mynew-page.tpl.php with the following theme function?

function mymodule_theme() {
  return array(
    'mypage' => array(
      'variables' => array('account' => NULL),
      'template' => 'mynew-page',
    ),
  );
}

There isn't a limit on the number of lines returned by a page callback, or on the number of tags it can return.
If the output is getting complex, it's rather better to separate the code into different theme functions; for example, for outputting a link there is l(), for outputting an image there is theme('image'), and for outputting a table there is theme('table'). The first rule is to reuse the existing functions.

In Drupal 7, a page callback can also return a renderable array, such as the following one returned by tracker_page():

  $page['tracker'] = array(
    '#rows' => $rows,
    '#header' => array(t('Type'), t('Title'), t('Author'), t('Replies'), t('Last updated')),
    '#theme' => 'table',
    '#empty' => t('No content available.'),
    '#attached' => array(
      'css' => array(drupal_get_path('module', 'tracker') . '/tracker.css' => array()),
    ),
  );
  $page['pager'] = array(
    '#theme' => 'pager',
    '#quantity' => 25,
    '#weight' => 10,
  );
  $page['#sorted'] = TRUE;

  return $page;

In these cases, the page callback doesn't return any HTML tags. This is also the preferred method, in Drupal 7, as it allows to the other modules to easily change the output of another module.

As alternative, you can use a template file for rendering the output. In this case, you need to:

Define a theme function that uses the template file; that is what is done from the Node module for theme('node'), which is defined in node_theme() using the following definition (Drupal 7):

'node' => array(
  'render element' => 'elements',
  'template' => 'node',
),

Optionally create a preprocess and/or a process function for the template, their purpose is to add variables to the ones that are passed to the template file. In the case of the Node module, those functions are template_preprocess_node() and template_preprocess_node().
Invoke the theme function to produce the output. In the case of theme('node'), this is done as in the following code:

// Drupal 6.
return theme('node', $node, $teaser, $page);

// Drupal 7.
$build += array(
  '#theme' => 'node',
  '#node' => $node,
  '#view_mode' => $view_mode,
  '#language' => $langcode,
);

Update
This is a common error: The template file name and the theme name must not be different; the only difference can be between using hyphens and using underscores. For the rest, the theme name and the template filename must be the same, which means that "mypage" as theme function and "mynew-page" as template filename don't work; if you are going to use "mynew-page" as template file, then the theme function must be theme_mynew_page(), reported in the theme definition as "mynew_page."


form submit function never gets called. My drupal form submit function is not called. validation function is called. Form name is Mymodule_user_profile_form($form, &$form_state), validation function name is Mymodule_user_profile_form_validate($form, &$form_state) and submit function name is Mymodule_user_profile_form_submit($form, &$form_state). I have studied all the previously asked questions.

This is the last portion where I declare my submit button is defined.

$form['profile']['profile-share']['profile-save-reset-btn']['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Spara'),
  //'#name' => 'save-profile',
);

I have tried like this.

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

var_dump($form['#submit']); Shows the submit function but it's never called. Any Idea about this?

The submit function is correct. By default, Drupal should call Mymodule_user_profile_form_submit() function without declared it with the '#submit' attribute. Could you publish all the code to have a deeper exploration of it?

Edit:

You could try this:

$form['profile']['profile-share']['profile-save-reset-btn']['submit']['#submit'][] =  'Mymodule_user_profile_form_submit';

The atrribute is in the upper side of the rendering array. The attibute should be at the same level to be fired when the submit button is pressed:

Here an example of form api reference:

$form['actions']['delete'] = array(

  '#type' => 'submit',

  '#value' => t('Delete'),

  '#weight' => 15,

  '#submit' => array('node_form_delete_submit'),

 );

You could also attach the '#submit' in the upper level if you declare '#type' as 'form'. For example:

$form['#type'] = 'form';
$form['#submit'] = array('your_function');
$form['first_tree']['element'] = array( ... ) ;
$form['second_tree']['element'] = array( ... ) ;


Cannot enable node_view in ctools page_manager permanently I have a strange problem. If I enable node_view in page_manager everything works as expected and the node layout is according to my settings. If I then do a menu cache clear node_view is not used anymore and my node layout is as without node_view. If I do a

page_manager_get_current_page();         (1)

shortly after activating node_view the array contains the normal values. Looking into the db the variable

variable_get('page_manager_node_view_disabled')         (2)

returns 0 as it should be. After the menu cache clear the function in (1) returns an empty array whereas the variable in (2) remains 0. Also the node_view page stays active inside the page_manager UI. If I deactivate and activate node_view everything works again until I refresh the menu cache again. So this seems to be an infinite loop for me: Everytime I do a menu cache flush I have to deactivate/activate node_view.

I don't know how long this problem exists, but I observed changes in my node layout also last year. I am using Drupal commons, so maybe the problem is related to this, since commons throws in a lot of modules and perhaps something overwrites node_view (panelizer is disabled on the specific nodes).

If I look into the code of the module, there should be a message

drupal_set_message(t('Page manager module is unable to enable node/%node because some other module already has overridden with %callback.', array('%callback' => $callback)), 'error');

if node_view is overridden, but there is simply nothing in dblog. I am really stuck here...

Does anyone have an idea what could be wrong or what I could do to find the reason for this behaviour?

Found the reason:

I had a module enabled which implemented a menu_alter which has changed

$items['node/%node']['page callback']


hook_commerce_checkout_complete is never called I need to send out a PDF via mail upon order completion, and according to DrupalContrib, I can use hook_commerce_checkout($order) to achieve this.

this is my module code:

<?php

function pdf_checkout_commerce_checkout_complete($order) {
  // No example.
  \Drupal::logger('pdf_checkout')->info('Hook called.');
}

My problem is, that it is never called, I've tried everything from just sending a log message when it is used, to creating a new, clean, module just to test it.
None of it has worked.

Is the hook still being used in Commerce 2.x? If not, what should I look at instead to achieve a similar effect?

Thanks in advance.

Is the hook still being used in Commerce 2.x?

No.

  If not, what should I look at instead to achieve a similar effect?

Commerce 8.x-2.x depends on the state_machine module which has events that are triggered when an order is placed (=checkout complete) as well as other state changes.

See Assigning (adding) an entity reference when an Order process is completed


I cannot turn off cache I tried everything to turn the cache off. Even when using drushs command "cr" it does not help.

I used this guide:
https://www.drupal.org/node/2598914

I cannot work like this. I also turned on devels theme rebuild on page view feature. Although I don't understand what is meant with this here:

  Rebuild the theme information like the registry
  While creating new templates, change the $theme.info.yml and theme_ overrides the theme information needs to be rebuilt.

Example:

function theme_preprocess_taxonomy_term(&$variables) {
    kint("1");
}

When changing the number even "drush cr" does not help. I got to refresh like 4 times until the browser shows the change.
Its not like that with kint - also "var_dump()" needs it's 4,5 times.

Could anybody please tell me what to do?

Browsers can be pretty aggressive about caching. Provided you're not using some other caching layers like redis/memcache, varnish, or a CDN, I'd start by disabling the browser cache.

In Firefox, open the inspector and click on the gear icon in the top right to open the Toolbox Options menu. Under the Advanced settings section, check the 'Disable HTTP Cache (when toolbox is open)'. I think Chrome is very similar in this.

Also be sure to use the hard refresh option. For Firefox it's Ctrl+f5. https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-quickly


How to get different size image on views I have view that fetch content and I show it on a block. My view shows 16 nodes and each node has title, date and image. For images I use imagecache to get correct size image. I have set this image to use the imagecache preset on view field settings. But now, I would need that the 1st and 7th image are different size (other images are 300x300 but 1st & 7th should be 750x400). How can i do this? Is it possible to achieve somehow in views configuration or on template level? Its drupal 6.

I used IMCE under Drupal 6.x. However, the resize only occurs at the time you upload and image with their editor which is cumbersome, to say the least. It depends on who has to upload the images, I guess.

Otherwise, CSS, as others mentioned, is probably your best bet. Now a day, browsers properly (cleanly) resize images so they still look good. (10 years ago, however, it was horrible!)

If you want to use IMCE and need to resize existing images, you could look into using convert on your server to resize existing files. However, you'll have to write an intelligent script that properly renames everything properly...


How do I access profile fields? I have installed the Profile module. I am trying to programmatically load profiles. The code works, but I am not able to access any field value.
class IdCardController extends ControllerBase {

  /**
   * Init id card download.
   */
  public function initDownload(User $user) {

    $user_profile = $this->entityTypeManager()->getStorage('profile')->loadByProperties([
      'uid' => $user->id(),
      'type' => 'personal_information',
    ]);
    kint($user_profile);
  }
}

Using kint(), I can see all methods are protected.

You could examine the Profile Entity class here profile / src / Entity / ProfileInterface.php, showing you a list of public methods including its getter methods, eg.:
$profile->getCreatedTime();

Additionally and similar as with Entities in general, you can also call data via either $entity->get('field_name')->getValue() or $entity->field_name->getValue().
See more on that here: Get information from an entity/ Entity methods
So if you have a Profile Entity with a field machine name address, then you could get its data like:
$profile = \Drupal\profile\Entity\Profile::load(123);
$profile->get('address')->getValue();
$profile->address->getValue();


Drupal site menu overlay stuck in Chrome Browser when scrolling down I noticed a strange behavior in my drupal Portal when using Chrome. There is an overlay at the top of the page. In Chrome, that overlay gets “stuck” on the page and you can’t easily get rid of it, and it starts constantly flickering. If I refresh its fine and when I scroll down the problem appears again.

Any help or suggestions are appreciated. Thank you.

Please find the attached screenshot here:

enter code here

.fixed#header {
    position: fixed;
    top: 0;
    left: 0;
    padding: 18px 0;
    width: 100%;
    background-color: #fff;
    background-color: rgba(255,255,255,.95);
    -webkit-box-shadow: 0 2px 3px rgba(0,0,0,.2);
    -moz-box-shadow: 0 2px 3px rgba(0,0,0,.2);
    box-shadow: 0 2px 3px rgba(0,0,0,.2);
    transform: translateZ(0);
}
style.css?onmqdt:859

header {

z-index: 99;
padding-top: 40px;
background-color: #fff;

}

Hard to say without being able to inspect it, the z-index on #header won't work unless position is set to something other than static (the default value).

Try setting #header to be position: relative; or position: absolute; whichever is more appropriate and see if that helps, or at least helps narrow down the problem.


Site adds "he" to the URLs of all the Hebrew nodes automatically All the nodes of my Hebrew site using Drupal 8 have this problem: Their address is similar to www.example.com/he/node/1, instead of what I was used to in Drupal 6+7 that was www.example.com/node/1. The difference is that now the URLs contain /he/ which I have never added.

It happens even when a node (whenever written in Hebrew or English) has its language set to English or Not specified.

What I tried is the following:

At the start all, my nodes were set to Hebrew so I thought it could be the behavior of the new language system of Drupal 8. I thus changed all nodes written for English speaking audience from Hebrew to English; I flushed the cache, but it didn't help: These nodes still had /he/ in their URLs.
I thought the Alternative hreflang module could cause this, so I removed it, but the problem persisted after flushing the cache.

Try deactivating the URL detection method under admin/config/regional/language/detection.


Changing Font Options in CKEditor I've tried a few different methods to change the options listed in the "font" drop-down in CKEditor, to no avail.

First off, I went to Config > CKEditor > Profiles > edit each profile > Advanced Options > Custom JavaScript configuration and followed the instructions below, putting something like

config.font_names = "Helvetica Neue;Helvetica;Arial;sans-serif;"

but nothing changed. I went into the config.js file located at sites\all\modules\ckeditor\ckeditor\ and added the following lines inside the function call:

config.font_names = "Helvetica/Helvetica Neue, Hevletica, Arial, sans-serif;"

but nothing changed. I then tried removing the prior line in Drupal's Configuration menu but that also didn't help. I've cleared my browser's cache and Drupal's cache, no luck. I've tried Firefox & Chrome, no luck.

Am I missing something or is this a bug? As a last resort, I could go directly into ckeditor\ckeditor_source\plugins\font\plugin.js and change the font_names listed there but the documentation I've read indicates my methods above should work, so I'm trying to avoid that.

Solution:
It took me quite a while to figure this out.
Let us say you want to use Verdana as the default font. Here is what you can do:

Open contents.css and change the font tag:

font-family: Verdana;
In the application/page where the output will be published, add this style:

.entry-content {font-family: Tahoma;}

That's it! Now you have change the default font successfully. This works for the font size as well. I just finished developing this question2answer site, http://banatbanat.com, which utilizes CKEditor and this tiny issue kept me awake for two days!