hook_js_alter is getting cached I recently come across a issue where my page was rendering two boostrap.js (Offcourse bad coding). An external Js from a module and another js from twitter bootstrap theme. Its causing some of the other js library to stop working(say bootstrap.multiselect.js).  So thought of removing the one of the js by mytheme_js_alter. Below code is working fine to achieve what is want, but with one execption. Sometime its does not work, and after clearing the cache it starts working.

function mytheme_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  $current_path = \Drupal::service('path.current')->getPath();
  $current_uri = \Drupal::request()->getRequestUri();
  if ($current_path == '/node/777' || $current_uri == '/mypage') {
    $external_bootstrap = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js';
    if (array_key_exists($external_bootstrap, $javascript)) {
        $javascript[$external_bootstrap]['data'] = $javascript['https://cdn.jsdelivr.net/npm/bootstrap@3.4.0/dist/js/bootstrap.min.js']['data'];
unset$javascript['https://cdn.jsdelivr.net/npm/bootstrap@3.4.0/dist/js/bootstrap.js']);
    }
  }
}

Has anyone faced same issue of caching? Please suggest any solution to overcome this.

libraries-override:
  MODULE_NAME/LIBRARYNAME: false
  MODULE_NAME/LIBRARYNAME: false


Permission for specific role to edit ANY comment I'm using the default Drupal 7 comments for my website and I would like to give specific roles the ability to edit any comment. My role can edit just about everything about a comment(Name, email, time etc.) but not the comment itself.

Only as user 1 I can edit the comments it seems.

Am I missing something here?

EDIT
I just figured out that it's not the permission for the field. It's the permission for the Rich Text Editor that was wrong. Checking the normal Administer comments and settings was enough. I'm an idiot.

The permission drupal gives by default says 'edit own comments'. I do not see a permission which allows 'edit any comment'. Try using User Tweaks module. Module page says

  edit any comments (and edit any  comments), which allows
  user with the Post comments permission to edit comments. The
  permission is not required for users with the Administer comments
  permission.

Updated Answer-

I just saw the comment module code.
You simply have to give Administer Comment Permission for that Role, but it will give delete permission as well.

If you are comfortable in custom coding you can alter the access callback for comment edit menu item.

If you see hook_menu implemented by comment module, here is the delete menu item code

 // Every other comment path uses %, but this one loads the comment directly,
  // so we don't end up loading it twice (in the page and access callback).
  $items ['comment/%comment/edit'] = array(
    'title' => 'Edit',
    'page callback' => 'comment_edit_page',
    'page arguments' => array(1),
    'access callback' => 'comment_access',
    'access arguments' => array('edit', 1),
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
  );

which basically calls comment_access function as

function comment_access($op, $comment) {
  global $user;

  if ($op == 'edit') {
    return ($user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
  }
}

You can implement hook_menu_alter to change access callback for edit, something as below.

  // Implements hook_menu_alter
  function mymodule_name_menu_alter(&$items)  {
    $items ['comment/%comment/edit']['access callback'] = '_my_module_name_custom_callbck';
  }

// Access Callbck for comment edit.

  function _my_module_name_custom_callbck($op, $comment) {
     if ($op == 'edit') {
     global $user;
      return (in_array('your_user_role', $user->roles) || $user->uid && $user->uid == $comment->uid && $comment->status == COMMENT_PUBLISHED && user_access('edit own comments')) || user_access('administer comments');
    }
  }

Note: I have not evaluated why drupal is not giving it by default, it will still be important to identify.


User Relationships and viewing content I have installed User Relationships for a project.  User A is friends with user B.  When user A posts a piece of content, currently it shows up on his front page, as well as user B's front page.

I just want any user to view their friends' content if they are viewing a friend's user profile.  I created views for the content as menu tabs for the users.  If someone is a friend, they should be able to view the content.  Otherwise, it should remain private for the user.

To rephrase my desired functionality, a user's content should only be viewable by the owner, and by any friends, via a user menu tab.

There are two ways to manage access to content with the User Relationships module.

The node access module allows you to open up access to nodes to friends but does not provide any way to remove that access, you'll need another module to do that.

The panels module allows you to show and hide panes based on whether or not a relationship exists.


Enable translation for theme settings Theme settings are not translatable in core. Is there a way to make them translatable? I have some additional theme settings which needs to have different values per language.

I'm trying to achieve something like this - How do I translate theme settings?

What I have so far -

mytheme/config/schema/mytheme.schema.yml

mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text_format
      label: 'Additional settings'

mytheme/config/install/mytheme.settings.yml

custom_textarea:
  value: "
*this is an additional settings.
\r\n"
  format: full_html
langcode: en

mytheme/mytheme.config_translation.yml

mytheme.settings:
  title: 'my theme settings'
  base_route_name: system.theme_settings
  names:
    - mytheme.settings

theme-settings.php

/**
 * Implements hook_form_system_theme_settings_alter().
 *
 * Form override for theme settings.
 */
function mytheme_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {

  $custom_textarea = theme_get_setting('custom_textarea');
  $form['custom_textarea'] = [
    '#type'          => 'text_format',
    '#title'         => t('custom textarea'),
    '#format'        => 'full_html',
    '#default_value' => $custom_textarea['value'],
  ];

}

When I navigate to admin/config/regional/config-translation it shows the 'my theme settings' but when I click on Translate it navigates to admin/appearance/settings/translate and returns Access Denied.

I also tried updating the base_route_name in mytheme.config_translation.yml to system.theme_settings_theme but when I navigage to admin/appearance/settings/mytheme/translate it throws a fatal error.

Looking forward for any suggestions.

in schema change field type to text and add translatable: true

mytheme.settings:
  type: theme_settings
  label: 'My theme settings'
  mapping:
    custom_textarea:
      type: text
      label: 'Additional settings'
      translatable: true

You may also face this problem later https://www.drupal.org/project/drupal/issues/2719553 (my reply there is the last from current date)


How to display the abstract with javascript I have a page that is a list of items, where I show the article title, author and abstract, but I want to show the abstract with javascript, a link that says show abstract and when I click out the absract od this article.

Then when clicking on the same link that hide the abstract.

Any idea to do this.
PS: I am using the latest version of Drupal 7.

One way you can do it is with the field group module.

You can go to the display settings of your content type and add a group, set it as a div or fieldset, depending on what you want it to look like, and set it as collapsed.

That is probably the easiest way.


How to count the number of anonymous users that are currently using the site? I want to either use a module or write a module which allows me to count the number of Anonymous Users that are currently using the site.

What is the best method for this to be achieved? I looked at the statistics module but this does not enable me to count the data. I discovered views is capable of  this with this setting, "Content statistics: Most recent views". But, there was no option for anonymous data.

The admin_menu module does this, and provides this function:

/**
 * Counts how many users are active on the site.
 *
 * Counts how many users have sessions which have been active since the
 * specified time. Can count either anonymous sessions or authenticated
 * sessions.
 *
 * @param $timestamp
 *   A Unix timestamp. Users who have been active since this time will be
 *   counted. The default is 0, which counts all existing sessions.
 * @param $anonymous
 *   TRUE counts only anonymous users. FALSE counts only authenticated users.
 *
 * @return
 *   The number of users with sessions.
 *
 * @todo There are mostly no anonymous sessions anymore. Split this into a
 *   separate module providing proper user statistics.
 */
function admin_menu_session_count($timestamp = 0, $anonymous = TRUE) {
  $query = db_select('sessions');
  $query->addExpression('COUNT(sid)', 'count');
  $query->condition('timestamp', $timestamp, '>=');
  $query->condition('uid', 0, $anonymous ? '=' : '>');
  return $query->execute()->fetchField();
}

It returns the count of users who have been active in the past (default) 15 minutes like this:

    function admin_menu_get_user_count() {
      $interval   = REQUEST_TIME - variable_get('user_block_seconds_online', 900);
      $count_anon = admin_menu_session_count($interval, TRUE);
      $count_auth = admin_menu_session_count($interval, FALSE);

      return t('@count-anon / @count-auth', array('@count-anon' => $count_anon, '@count-auth' => $count_auth));
}


Replace strings with new strings I have a page with list of teasers. It contain links like 1 comment, 1 new comment, add your comment. I want to change 1 comment to 1 response, 1 new comment to 1 new response and add new comment to add new response.
I used string overrides module and tried to change the strings, but i was able to change only add new comment to add new response. How to change 1 comment and 1 new comment? please help.

There is another solution to implement hook_preprocess_node to modify the comments links.

You can follow the answers in the Modifying teaser node comment links


Show PDF/print icons inside a template file I am using a template file to render a content type. So I print variables as with the following code.

print $node->body

I have installed the Print module, and I have selected the option to display print icons for this content type to, but the icons are not getting printed.

How can the icons be printed inside a template file?

As the README.txt says

  Administration > Structure > Content types (admin/structure/types)
  For each content type it is possible to enable or disable the
  PF link via the "Show printer-friendly version link"
  checkbox. (default: enabled) It is also possible to
  enable or disable the PF link in individual comments via the
  "Show printer-friendly version link in individual comments"
  checkbox. (default: disabled)

API

print_insert_link(), print_mail_insert_link(), print_pdf_insert_link()

  The *_insert_link functions are available to content developers that
  prefer to place the printer-friendly link in a custom location. It is
  advisable to disable the regular Printer-friendly link so that it is
  not shown in both locations.

Take a look at THEMEABLE FUNCTIONS

It is a best Practice to read modules README.txt.


How can a poster of a comment notify selected users about a new comment? When I write a comment on a node, I want to be able to select the users that will get a notification (via e-mail) about that new comment. Basecamp has this feature and I think it is very cool.

Is this possible without customization? I know how to notify the author of the comment, but this is different.

When I write a comment on a node, I want to be able to select the users that will get a notification about that new comment.

1) Download Rules and Entity Reference Modules.
2) Enable Rules, Rules UI (User Interface, we need this), and Entity Reference
3) In your comment fields

Add a field with Entity Reference and a widget of Auto complete (tag style)

For example: I named mine lalala (click picture below to enlarge)

4) In your field settings:

Select User as your target type

After you click save field settings you are taken to another screen, scroll down and find Number of values and change it to Unlimited and Save Changes.

5) Add a new rule by going to /admin/config/workflow/rules/reaction/add

React on Event: After Saving New Comment
Restrict by Type: Select your content type (In this example it's Article Comments, since in Articles Comments is where I put my lalala field.)

6) Click on Add a Loop

Data selector: comment:field-lalala (remember I named my entity reference field lalala)

7) Click Add Action, but the one from the loop!

8) Select Fetch Entity by Property

Entity Type: User
Property: Email
Data Selector: list-item:mail
Limit Result Count: put a large number here in case it has an effect. (since we are looping, I don't believe so, but I am not 100% sure)

9) Add another action to the loop, this time add Send Mail
Click on switch to data selection button.

To: list-item:mail

The end result should look like this

Now add a new comment.
On your entity reference field since we are using Autocomplete (tag style) you start to type a user name and select the user. Then add a comma , to add more users
Ex:
After posting the comment, all referenced users should receive an e-mail.


Drupal 8 url after installation using drush site-install I used Composer to download and install Drupal 8.8.1 on Linux and used drush site:install command for setup.

Only the following lines/messages were shown after I entered drush site:install command.

You are about to DROP all tables in your 'drupal8' database. Do you want to continue? (yes/no) [yes]:

>yes

[notice]Starting Drupal installation. This takes a while.
[success] Installation complete. User name and password displayed.

I don't know my site URL. How do I find my site URL? Is there a default site URL?

Thank you

Congratulations on getting this far. You got Drupal and Drush downloaded and were able to configure the database. Those can both be challenging things to do.

Based on your description it seems like do not have a webserver. Drupal.org has some documentation on setting up a webserver and there are a few solutions to that, like setting up apache or nginx.

Since you mentioned you have drush available one of the easiest solutions is to use drush's runserver command. It is documented here

From the project root run the command:

drush runserver

The output of that command will tell you the URL to load into your browser. By default the URL is http://127.0.0.1:8888 which it will tell you Listening on http://127.0.0.1:8888.

Here's a more detailed article from Lullabot on runserver.


How to generate different image styles at upload? I'm using Drupal 8.
Is there a hook for generating image from image style or better one module?

For example. I upload an image. When image is displayed for the first time, Drupal generates image style. Can I hook to that event somehow, at best when uploading the image?

Ah yes, you are right.

  Image derivatives will be automatically generated once requested and not-yet existing.

That's a quote from my own answer to a similar question. I guess you could try to hook into the upload somehow like Image Style Warmer does it, or simply try that module out yourself.

  Synopsis

  The Image Style Warmer module provides options to create image styles
  during upload or via queue worker. So configured image derivates
  already exists when they are requested.


Programmatically add fields to content type I have created a content type in Drupal 7 using the following code.

function module_node_info() {
  return array(
    'module' => array(
      'name' => t('module'),
      'base' => 'module',
      'module' => 'module',
      'description' => t("You can add a content for module from here."),
    ),
  );
}

This seems to be working fine: I see the content type and I can add fields. When I create fields for this content type through code, the fields show up when I click on 'add content' but they are not showing in my content type. When I add nodes of that specific content type, the nodes are not showing and the fields are empty when I edit them.

I miss something, but I have no idea what that could be. I use the following code to create the fields.

function module_form($node, &$form_state) {
  $form = array();

  $form['module_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Enter the name of your module'),
    '#required' => TRUE,
    '#description' => t('This name will be visible on the website'),
  );

  return $form;
}

The second piece of code creates a field in the Form API. This means that you do that when you create a custom form with several fields in it and then you have to handle its submission in your custom way. If this is what you want to do, fine. In this case you would need to add your custom form in your hook_menu().

Instead, from what I can understand with your question, you would like to add a field of the Field API to tour custom node type. For this matter you would need to use the field_create_field() and field_create_instance() functions. The excellent examples module provides very neat examples of how to accomplish that.


Creating custom CSS for a book Using Drupal 7 and creating a number of books with the Books module. They each have their own specific design, so specific CSS needed per book. I know I could create specific content types for each book but I think that would become unmanageable as the number of books grow.
We are using the Code Per Node module, we could make use of the Context module to detect which book it is, and then insert a block somewhere on the page with some associated CSS. In theory that would work but is there a better way to do this?

In Drupal 7, you can add a CSS class to the <body> tag for your book. For nodes, you have the class added by default. For example page-node-2056, for the /node/2056 path.

For Book nodes, you might add the book ID inside your template.php theme file, in the theme_preprocess_html function:

function MYTHEME_preprocess_html(&$vars) {
  // If on an individual node page, add the book ID to body classes.
  if ($node = menu_get_object()) {
    if (isset($node->book['bid'])) {
      $vars['classes_array'][] = drupal_html_class('book-id-' . $node->book['bid']);
    }
  }
}

You can then take the ID for each book and add all the style definitions in a single CSS file. Something like the following:

.book-id-xxx {
  /* Style for book xxx. */
}
.book-id-yyy {
  /* Syle for book yyy. */
}
... and so on

Would it make sense for what you need?


Sub-theme adding prefix to all block machine names On my site, I have created a sub-theme of a sub-theme using this as a guide to set this up https://www.drupal.org/docs/8/theming-drupal-8/creating-a-drupal-8-sub-theme-or-sub-theme-of-sub-theme and it does work with carrying over all of the css/js/regions but for some reason, it is renaming all of the blocks with the prefix of the sub-theme.

So, for example, I have a block with a machine name of mainnavigation when I install/set as default the sub-theme it will change this block to theme3_mainnavigation.

I have tried removing the block and placing it back in with the same name of mainnavigation but I run into an issue where a message will appear that says this machine name already exists.

Does anyone know how to get around this so the sub-theme will use the machine names of already existing names instead of creating a prefix?

Thanks for any help!

You can't.

This behavior is core functionality from the Block module that's enforcing its data model. Each time you place a block, you're creating a unique Block entity that has a theme property tied to it. Thus, the mainnavigation block entity can't simultaneously be used on the default theme as well as theme3.

This is why Drupal defaults to generating ${theme_machine_name}_${block_machine_name} so the user doesn't have to think about it.


Adding a date time field value within a node programmatically [field_download_time] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => 2012-11-27 09:38:00
                                [timezone] => America/Phoenix
                                [timezone_db] => America/Phoenix
                                [date_type] => datetime
                            )

                    )

            )

What I see for a field_download_time is given above..
I am adding nodes programmatically so the code for following field is as given below

 $download_node->field_download_time[]['value'] = date('m-d-Y H:i', REQUEST_TIME);//--?

I don't get an error on running the above code but the value of current date is not displayed

But When I run the following code given below I get an error
THE ERROR : Actually the code is such that when u go to the link it downloads a file .Basically the error is that  file is not downloaded.

  $download_node->field_download_time['und'][]['value'] = date('m-d-Y H:i', REQUEST_TIME);//--?

[0] => Array
                            (
                                [value] => 2012-11-27 09:38:00
                                [timezone] => America/Phoenix
                                [timezone_db] => America/Phoenix
                                [date_type] => datetime
                            )

As seen above,
the error was occuring due to improper date format So when I changed the date format to  date(Y-m-d\TH:i:s, REQUEST_TIME);
the $download_node->field_download_time['und'][]['value'] did not gave any error .


Update the price of a line item after shipping method is selected I looked everywhere and couldn't find the appropriate and clear explanation of how to change the price of a line item.
I have a line item called "fee", the fee changes based on the date and zipcode. I have a function that returns the correct fee based on the parameters.
Now what hook do I call to update the "fee" line item?
This is what I found

function ck_custom_commerce_cart_order_refresh($order_wrapper)
{
$fee = _ck_custom_delivery_fee($order);//this function returns an integer

foreach ($order_wrapper->commerce_line_items as $line_item_wrapper)
{
    if($line_item_wrapper->type->value()=="fee")
    {
        //I would like to update the fee
    }
}
}

Please what is the right of way of accomplishing this?
FYI: I'm using the commerce fees module if that helps.

You want to change the price components of the line item you're wanting to update. You can use rules for this, but since you're writing a hook, you can just call the function that Rules would use:

commerce_line_item_unit_price_amount($line_item, $amount, $component_name, $round_mode);

For example, if you want to change it to $5.00:

commerce_line_item_unit_price_amount($line_item, 500, 'base', COMMERCE_ROUND_HALF_DOWN);


Drupal mkdir folder permission When creating directory using function drupal_mkdir in custom module, how to set folder permission access to "Create and delete files"?

drupal_mkdir('public://myfolder/');

The second parameter is $mode, which you can provide. e.g.

drupal_mkdir('public://myfolder/', 0755);

By default the 'file_chmod_directory; will be used, which, by default, is 0775.

Exactly what mode you use will obviously depend on your server set up. If you're not sure, ask your sysadmin what it should be.


Pagination isn't working I have a homepage view called FrontPage. Currently, it shows the pagination link like "1, 2, 3 Next->" as it should; when I click on Next, it goes to http://example.com, not http://example.com/page/1/0.

I have checked the taxonomy archive, and it is has the same problem. The same is true for the Blog posts.

I checked pager.inc, but I don't see any problem. I haven't hooked anything in template.php.

Why is the Next link pointing to the wrong page, and what could I do to fix it?

Including your versions of Drupal core and Views module might be helpful.

Any chance you're using the Global Redirect module? I had the same problem when I took a dev site live (Drupal 7.26, Views 7.x-3.7 and 7.x-3.7+22-dev, Global Redirect 7.x-1.5), and this patch in globalredirect.module addressed the issue.

https://drupal.org/node/1789546


Jquery Library Conflict Error in Drupal 7 I've been currently developing a module. Before it was working fine but as I started working on my module, the console throws an error every time I click a link in my Drupal admin menu.

For example:

When I click the "dashboard" link , it says:

When I click the "content" link, it says:

By the way, jquery-1.11.2.min.js is a JQuery library I added in my hook_init function to keep my module working.

function myid_init (){
    //Jquery Library
    drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");
}

Im using drupal 7.34. Can anyone explain me, why is this happening and how to fix it? Thanks.

I would wager a guess it's because (or related to) Drupal including it's own version (1.4) of jquery, and you trying to include a second copy at version 1.11.2 - some functionality is deprecated in later versions of jquery, items that drupal and its modules are expecting to find. If you need to increase the version use something like the module Jquery Update instead of your own add_js and see if that solves it.

Upgrades the version of jQuery in Drupal core to a newer version of
jQuery.
Updates...
Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD


How do I override ajax-progress-throbber in a theme? In my Drupal 7 site, I created a custom theme. In my theme, I want to change the AJAX progress throbber HTML structure, which by default is the following one.

&nbsp;

Please wait...

I searched a lot about this issue, but I couldn't find any useful document or sample.

There is a new way of doing this as per this change record
add the following into the respective files
THEMENAME.info.yml
libraries-extend:
  core/drupal.ajax:
    - THEMENAME/throbber

THEMENAME.libraries.yml
throbber:
  css:
    css/throbber.css: {}
  js:
    js/throbber.js: {}
  dependencies:
    - core/jquery
    - core/drupal

js/throbber.js
/**
 * @file
 * Replaced Drupal cores ajax throbber(s), see: https://www.drupal.org/node/2974681
 *
 */
(function ($, Drupal) {
  Drupal.theme.ajaxProgressThrobber = function () {
    return "
" + Drupal.t('Loading&nbsp;&hellip;', {}, {
      context: "Loading text for Drupal cores Ajax throbber (inline)"
    }) + "
";
  };

  Drupal.theme.ajaxProgressIndicatorFullscreen = function () {
    return "
" + Drupal.t('Loading&nbsp;&hellip;', {}, {
      context: "Loading text for Drupal cores Ajax throbber (fullscreen)"
    }) + "
";
  };
    // You can also customize only throbber message:
    // Drupal.theme.ajaxProgressMessage = message => '
' + message + '
';
})(jQuery, Drupal);

css/throbber.css
// optional code of your ajax-spinner classes

An alternative would be to use the ajax_loader module which lets you customize the throbber.


Change label of an exposed filter button in Views I have an exposed filter, and instead of having the button to activate it have an 'apply' label, I'd like to change it to something else. How can I do that?

This question is regarding D6. However just fyi, in Drupal 7 you can change the label much more easily by going to "Advanced" in your view edit page, then in the exposed form settings you can change the button label as well as other look and feed settings.


PHP Output in module I am creating a module that is outputting a static php page into my Drupal install. Here is my module file:

<?php

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

$items['live_amplified/hello_world'] = array(
'title' => 'Live Amplified',
// describe the page for the menu system.  site visitors will not see this
'description' => 'Simple custom hook_menu() implementation.',
// function that is called when visiting the new path
'page callback' => 'drupal_get_form',
'page arguments' => array('static_page_form'),
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
 );

return $items;
}

/**
* Implements hook_form().
*/
function static_page_form($form, &$form_state) {
// Add CSS and JS
drupal_add_css(drupal_get_path('module', 'mymodule') . '/static_page.css');
// Import your static HTML page
$form['html'] = array(
'#type' => 'item',
'#markup' => file_get_contents(drupal_get_path('module', 'mymodule') .'/static_page.php'),
);
return $form;
}

In my static_page.php I have written my HTML, but when I try to add any PHP the browser doesn't recognize it. It doesn't output anything. I have tried just echo test and still nothing.

You don't need to use a form items markup attribute just to print some HTML.
Instead,  change your menu item to a simple page function, not a drupal_get_form eg

$items['live_amplified/hello_world'] = array(
  'title' => 'Live Amplified',
  'description' => 'Simple custom hook_menu() implementation.',
  'page callback' => 'hello_world_page',
  'page arguments' => array('static_page_form'),
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
);

and add a simple function to return some markup

function hello_world_page() {
  return "Hello World";
}

But as @Adam Balsam described, if you have a lot of content and want to parse another PHP file, you would do it using file_get_contents() but Drupal already has a way of dealing with this that uses it (although it may be convoluted)

You would use hook_theme.

First you need to declare your implementation, this does two things: tells Drupal to look for a template file (the file you want to render) at some location, and it exposes your template to prerocessing for adding variables.

Declare your theme

/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'helloworld' => array(
      'template'  => 'hello-world',
      'path'      => drupal_get_path('module', 'mymodule') . '/templates',
      'arguments' => array('node' => NULL),
    ),
  );
}

Create a preprocess function to give it some variables

function mymodule_preprocess_helloworld(&$vars) {
  $vars['who'] = "World";
}

Create a template file hello-world.tpl.php in /mymodule/templates/ with the content

<h2>Hello <?php print $who; ?> </h2>

Call it from where ever you like, in this case a menu page.

function hello_world_page() {
  return theme('helloworld');
}

At first it may seem a bit convoluted but it allows you to create templates with variables and exposes theme to themeing so other modules and themes can change both the variables and the markup.


Can I display all token values available for my Drupal installation? Is there a way that I can display all possible values for tokens available on my Drupal installation? For example, I'd like to see all of the possible values for the [termalias-raw] placeholder that I use with the Pathauto module.

To see all the value a token would get, you should call the function that replaces a token with its value, passing a different value for its $object parameter.
Using pseudo-code, this is the code you should run:

foreach (get_all_nodes() as $node) {
  print token_replace("[termalias-raw]", 'node', $node);
}

"[termalias-raw]" is a token implemented by the Pathauto module that is associated with node objects.
This is the code contained in pathauto_token_list(), which is the function that lists all the token implemented by a module:

if ($type == 'node' || $type == 'all') {
  $tokens['node']['termpath'] = t('As [term], but including its supercategories separated by /.');
  $tokens['node']['termpath-raw'] = t('As [term-raw], but including its supercategories separated by /.');
  $tokens['node']['termalias'] = t('The URL alias of the taxonomy term.');
  $tokens['node']['termalias-raw'] = t('The URL alias of the taxonomy term.');
}

If you meant the list of all the tokens available, then that list is already given by the Pathauto module in the form that allows you to set the path alias for each entity supported by the module. To see it all you need to check each of the path alias types (e.g. user, node, taxonomy terms).


Create a view on a entity using criteria on another entity I'm trying to this done :

I have two entities

1) Listing Details
2) Listing Premium Settings. This entity references the first Listing Details entity.

In the second Entity I have referenced entity 1 Listing Details, added with fields for a StartDate and a EndDate.

I would like a view on Entity 1 where I will use the StartDatet and EndDate of Entity 2 as a filter.

I have tried contextual, I have tried Relationships, but I guess I do not graps the essences of both ... :-(

Anyone who can help me get this done ?

I use Drupal 8.7.
I am a newbie.

Alex

A view of entity one in relation with entity 2 referenced field may work, but maybe you can try the other way around:

Create a view of Entity 2 (Listing Premium Settings) with field titles or nid that you exclude from display (and maybe remove at the end)
Create your filters at your convenience of time
Define your relationship: content referencing the first entity
Then add the fields of entity one you wish to display in your view, using the relationship in these fields.

In that sense it might give you more control on the filters which are attached to entity 2.
In the other sense (entity 1 relationship to entity 2) it gives you more control on the fields of entity 1 to display in case of multi-value field for example.


How do I get Views PDF to Download a file? I am using views-pdf to create a 'ticket' for people. Buy a ticket and they need to keep the ticket on their phone. I am using views-pdf to generate the ticket and would like to automatically trigger the download.

At the moment I have the following, which is not working:

function yhivepasses_views_pre_render(&$view) {
 if ($view->name != YOGAHIVE_PASSES_VIEW_NAME || $view->current_display != YOGAHIVE_PASSES_VIEW_DISPLAY) {
 return;
  }

//'Content-Disposition' => $disposition . '; filename="' . mime_header_encode($name) . '"',
  drupal_add_http_header('Content-Disposition', 'attachment; filename="yogahivepasses.pdf"');
}

The headers are returned from TCPDF. The argument 'D' for download needs to be passed from views to TCPDF.

To do this I created a menu entry.

function yhivepasses_menu() {
  $items['yhivepasses/download/yogahive_passes_user_balance/pdf_1/user/%'] = array(
      'title' => 'YogaHive Passes',
      'page callback' => '_yhivepasses_views_pdf_download',
      'page arguments' => array(2,5,5),
      'access arguments' => array('access checkout'),
  );

Called the view manually.

function _yhivepasses_views_pdf_download($view_id, $views_display, $arguments) {
  if (!empty($view_id)) {
    $view = views_get_view($view_id);
    if (!is_object($view)) {
       drupal_set_message("Sorry, couldn't load your YogaHive Passes.", 'error');
       return FALSE;
     }

    $view->set_arguments(preg_split("/\r\n|\n|\r/", $arguments));

  if (!$view->set_display($views_display)) {
    $views_display = 'pdf_1';
    if (!$view->set_display('pdf_1')) {
      return FALSE;
    }
  }

  $view->pre_execute();

  $display = $view->display[$views_display];
  if ($display->display_plugin == 'pdf' && isset($display->handler)) {
    // arguments '' and I
    // Setup rules to take you to the 'completed' page and then do a redirect.
    //header('refresh:0;url=' . $base_url . '/user/14');
     $display->handler->execute('', 'D');
     $display->handler->post_execute();
    }
  }
}

The way that views-pdf calls views, I don't see a way to set the argument 'D'. There are no hooks, just a conditional call.


Save tags in parent and children of vocabulary with shs module How can I save my tags in parent and children of vocabulary with the shs module?

When I save my tag in children with the shs module, I want to show my content in parent and children path.

on taxonomy/term/% view, enter contextual filter

  "Has taxonomy term ID (with depth)"

and change the depth settings to -1 and children view will take parent tag nodes too.


Reference with content types I want to show one content type content in another content type. Like one content type have Title, text field 1, text field 2, picture and i want to be able show in another content type. Is this possible? Thanks.

Two module you can use to accomplish your requirement (1) entity reference and (2) node reference. Both directly added field to your content type as field which would be reference to another content type.

Select "entity reference" or "reference" in data type select of cck field.


How to define event listener in the service? In Drupal 8 is possible to use event subscriber that is the separate class that defines the callback that should be called on the defined event. See  Event Systems Overview & How To Subscribe To and Dispatch Events

But I'm wondering how to define event listener that will trigger the method of the service on the desired event?

here Symfony references:

Events and Event Listeners

Built-in Symfony Events

If I understood correctly, I think you are asking about implementing minimalistic single responsibility event listeners declared in the YML config file, like in this Java example:

class MyListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    myTextArea.append('Hello from MyListener');
  }
}

That is not possible since this is this what the EventDispatcher actually does:

    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (is_string($params)) {
                $this->addListener($eventName, array($subscriber, $params));
            } elseif (is_string($params[0])) {
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }

You can still have your separate ActionListener's, but you would have to write some code to call them from your implementation of EventSubscriberInterface.


Feeds and pipe | separated values I am trying to use Feeds to import data from a CSV file. However, the file I've been provided with, even though its type is "Microsoft Excel Comma Separated Values File (.csv)", the values are separated by a pipe | character instead!

Will this work? Or will it corrupt the database?

The reason I ask this is because in the Select a parser section one of the options is CSV parser (parse data in comma separated value format) and that is the only one that I can see would suit me... except for my pipe separated values format ...

This won't work out of the box because Feeds is expecting a CSV but you can convert this to a proper CSV file using the Feeds Tamper module to modify the data before passing it to feeds.

However, the easier way to do this would be to just load the file back into Microsoft Excel as a delimited file, and then export it back as a proper CSV.


Increment field value in update query I am converting some module from d5 to d7, and in old code there is an update query like this:

<?php
db_query("UPDATE {a_table} SET count = count + 1 WHERE field1 = %d", $some_value);

As we see, it is incrementing a field value (AFAIK it is a mysql feature).
But, if I use new style of update it won't work.

<?php
db_update('a_table')
    ->fields(array('count' => 'count + 1',))
    ->condition('field1', $some_value)
    ->execute();

Are there any workaround within new style of db update without running an extra query to get existing field value to increment it?

You can do it by adding an expression to the query:

db_update('a_table')
  ->expression('count', 'count + 1')
  ->condition('field1', $some_value)
  ->execute();


Deleting field collection bundle programmatically from core I have a field collection bundle that I want to remove from my site. I was googling how to do that and  came upon these instructions, but they seem to be from the ECK module, and only apply to entities created by eck. The company I work for has a module review process and this module doesn't have a stable release yet.

So, ideally there would be a way for me to do this from core, or at least the field collection module, without extra modules. Is there?

Edit "No, you can't" is a perfectly acceptable answer. If that's the case I would like to stop chasing down blind alleys.

So apparently what I needed was field_delete_field(), and then a field_purge_batch().


How to not have "-None-" as default in the entity reference display widget I spend hours to  figure this out but no result.   I want to auto-populate a
field using entity references and views.

A field has a user entity reference
Using filters, I made a view narrowing down the results to 1 (the result I
want to populate the field with)
I linked the field with the search result using "Views : ..." as a
reference method.

The only thing that's preventing me from succeeding is that the widget always
shows 2 results instead of 1 (SEE SCREENSHOT):
- None -   (Default)
My result  (Dreece in the screenshot)

so the "-None-" is preventing me from succeeding to do the auto-populate.

Any way to (NON PROGRAMMATICALLY) ommit the "-None-" (or put it as the second
option)?
- By configuring the View
- By using View arguments?

Many thanks in advance!!!

As soon as you make this field required it will have no - None - option anymore.


relation users to orders I want to create a list of users with their orders. I know I can create it with the Views module, but when I select user as view type, there is no relation I can use to get their orders.

Some users may not have any order. I want the list to include also those users without any order.

You can try to write a custom module that implements hook_views_data_alter() to programmatically define a relationship. See also the example code for hook_views_data().


jquery in select (views module) -- change submit click to link This is regular Views selector exposed to user:

This is a part of block, attached to Panel on main page. I want to create links "show expiring" and "show latest" but I need to learn what function is fired while clicking Apply. Anyone knows where can I find it? Debugging it with Chrome is tricky, a lot of JS files…

Is there a way of previewing all javascript acitvity?

The image above shows an exposed form generated by Views in the file views_plugin_exposed_form.inc.  Line 242 in the function exposed_form_alter reads       $form['#attached']['js'][] = drupal_get_path('module', 'ctools') . '/js/auto-submit.js'; so the js looks to be in ctools however, I believe that script is being called whenever a change is made on the form.  If you want to modify the form note that views is managing the form in this file. Selecting the 'Apply' button calls exposed_form_validate and exposed_form_submit which are tapping into the Drupal form API (php not JS). Go to api.drupal.org to find out more about the various hooks available to modify the forms


Passing a node refernce id to a form via hook_form_alter() using Drupal 7

I'm trying to write a module that alters the node add form of a certain content type. This content type has a node reference field that normally displays as a drop-down. I'm also attaching this node add form to the bottom of the content it references, what I'm trying to do is populate the node reference field by using hook_form_alter() and passing in arg(1) of the page (passing it the nid of node I want it to reference).

I'm trying to figure out exactly how to do this. I've tried to do a drupal_set_message('<pre>'. print_r($form, TRUE) .'</pre>'); on the form to see how exactly to pass in the node reference, but it just prints out a huge nested array, and I'm unable to really figure out how I would format that as input I know it's going to look something like this;

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "my_node_form")
    {
        $form['title']['required'] = FALSE;
        $form['node_reference_field_name']['nid'] = arg(1);
    }

}

but I'm still really confused on the actual syntax

ok, figured this out incase anyone is interested, may only work for my use case but perhaps it will help someone else.

function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "rating_node_form")
    {
        // dont require title
        $form['title']['required'] = FALSE;
        // validate
        $form['#validate'][] = 'mymodule_form_validate';
        // call after form is built
        $form['#after_build'][] = 'mymodule_after_build';
    }
}

function mymodule_after_build($form, &$form_state) {
       //set the nid to the argument of the nide you are viewing
       $form['field_bar_name']['und']['nid']['#value'][0] = arg(1);
       //set the default value
       $form['field_bar_name']['und'][0]['nid']['#default_value'] = arg(1);
       //set form value
       $form['field_bar_name']['und'][0]['nid']['#value'] = arg(1);
       return $form;
}


Override labels in REST Export view I have a REST EXPORT view getting fields values of a node. I want to override the labels of these fields in the response returned.
For example:- the returned response like this

[
    {
        "question_title": "How are you?",
}
]

I want the response like this

[
    {
        "questionTitle": "How are you?",
}
]

I tried to create label from the view but it doesn't affect.

In your view's row style options you can rename any exposed field's label. The form labels those fields as alias.

This is screenshot from another view I was working on, but should give you an idea.


When I edit a display within a view, it changes other displays too I have a question about the way displays in views work:

I have a view that has 8 different displays. Each display shows content of the same content type, but with different taxonomy terms associated with each (so one display would be something like Research Topic 1, another would be Research Topic 2, and so on).

The issue is that with two of the displays, when I edit one, the other automatically takes the same changes. All other ones work fine, except two. What I'm editing is the type of research (which as I said I'm using taxonomy terms to decide what is what). When I select one research type on display X, it changes the research type in display Y to be the same.

I'm not the one who originally set up this view, so I'm not really sure what was differently, if anything, to the others to make them work fine. Any help is appreciated!

Edit: One additional thing I just noticed is that "FILTER CRITERIA" for the two displays that seem to be connected is not italicized, but that heading in Views for all of the other displays within this block are italicized. No idea what this means, but just adding this info in case it's helpful.

Never mind! I figured it out... Each display was still overriding the others, but I found where to change that and everything is good!

For anyone else with the same question:
When you click on a filter criteria, you can select options in the drop down at the top of this overlay which specifies whether you would like to apply the changes to all displays or just this page.


How do I conditionally change the print.css stylesheet to use media = all I added this to my template.php, but it doesn't appear to be working.  I've also placed this code in theme_preprocess_html(),

<?php
  function theme_process_html(&$variables) {
    if ($_GET['print'] == 'true'){
      $variables['css']['sites/all/themes/mytheme/css/print.css']['media'] = 'all';
    }
  }
?>

I ended up using hook_css_alter(&$css)

<?php
  function MYMODULE_css_alter(&$css) {
    if (isset($_GET['print']) && $_GET['print'] == 'true') {
      $css[path_to_theme().'/css/print.css']['media'] = 'all';
    }
  }
?>


Link to outlook: protocol in Views In my website, I'm creating a dynamic external link to open email from Outlook using outlook:{Entry ID} link. It should be like:

outlook:000000006CD8BD6F1761654D9AD70F841783C591070062F134BA8C073B4296C8467090C20CF200000089D837000010EBA743D9305C4891225FE3E347AE1800003B82DF840000

I tried to use:

"Rewrite the output of this field": open outlook

AND/OR

Output this field as a link, with link path: outlook:[guid] with options: "Use absolute path" and "External server URL" enabled.

The problem is no matter I use in Views field rewrite, the anchor's href outlook: replaced with http://localhost/ or http://localhost:8080/pms/outlook%3A

What do I need to do to generate the link correctly in format outlook:[guid]?

The problem is that the URL code in Drupal doesn't recognise your "outlook:" prefix, and so is trying to make it a valid version of a protocol it does know. Option (2) explicitly invokes the URL code, so it is not surprising that it changes the href.

I am slightly surprised that the rewrite version didn't work, and can only assume you had other options set in the View which caused this -- or that the page was cached.

If you cannot get the rewrite to work, I suggest you override the field with a view-specific field template (see "theme information" in the theme config), in which you can do whatever you wish.


Auto Load next Post like qz.com How the functionality of auto loading the next post when you reach the end of a content is reached.
This functionality is seen in Quartz which is built on Wordpress. Most probably they are using the Auto Load Next Post plugin.

Is there any module or a way by which this can be replicated in Drupal (Drupal 8 if possible)?

If you want to go a site builder approach, one solution here is Views Infinite Scroll.

  Views infinite scroll allows you to load and display pages of any view
  inline, using AJAX (this has been called infinite scrolling, load
  more, autopaging, endless pages and more). The pager can be triggered
  with the press of a button or automatically as the user scrolls to the
  bottom of the view's content.

The caveat with this approach is you'd need to rely on a Views page configured with an Infinite Scroll pager set with the Automatically Load Content option. In other words, a static URL showing paged full content. That's pretty close to the functionality, but not perfect replication.


How to get file from managed_filed in drupal 8 generate image style and use as background image for a div I had created a form filed to upload an image on a themes settings page like this

$form ['ad_tv']['tv_adbackground'] = array(
    '#type'     => 'managed_file',
    '#title'    => t('Hintergrundbild'),
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://theme/backgrounds/',
    '#default_value' => theme_get_setting('tv_adbackground'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),

),

Now I like to know

with preprocess function to use in mytheme.theme to make sure the file gets overwritten, if a new one is uploaded.
how to add the path of the uploaded file or its image style to add the path as background image to a div with a css id called advertisement

I hape that this is not to much for one question. I am new to drupal 8. So any help will be welcome-

thank you.

Untested, but you should be able to do this:

$style = Drupal\image\Entity\ImageStyle::load(IMAGESTYLENAME);

$url = $style->buildUrl(theme_get_setting('tv_adbackground'));

$element['background'] = [
  '#prefix' => '
',
  '#suffix' => '
',
  // Force rendering of this element
  '#markup' => '',
];

You'll need to change IMAGESTYLENAME to the actual image style you want to apply.


Can't disable css caching and aggregation I've recently installed some modules including wysiyg, ckeditor, ajax comment, b2 nice comments.

I then noticed that my css files became cached and aggregated when inspect my pages.
I unistalled all the modules and double checked the options in the performance menu which were correctly disabled.

The weirdest thing is that I restored the files and DB to an older version and it didn't help.
I ported the site to another directory within the server (under a different domain) and the problem disappeared.

Anyone with similar experiences or ideas as to what might be the cause ?

Does your theme use the core Color module? I believe that module compiles and caches CSS files with the updated color values whenever the theme color pallet is changed. Just an idea.


Fatal error: Allowed Memory Size of (X Size) when running drush migrate-upgrade I'm trying to use drupal migration module with drush to migrate a database. I'm getting this error below.
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /Applications/XAMPP/xamppfiles/htdocs/drupal-eight-iom/core/modules/migrate_drupal/src/Plugin/migrate/source/DrupalSqlBase.php on line 76

I have already tried editing the memory_limit on php.ini file

memory_limit=5024MB

Not sure what else I need to do in order to make it work. I'm using Drupal 8.4.4

$databases['default']['default'] = array (
  'database' => 'drupal-eight-iom',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$databases['upgrade']['default'] = array (
    'database' => 'drupal-seven-iom',
    'username' => 'root',
    'password' => '',
    'prefix' => '',
    'host' => '127.0.0.1',
    'port' => '3306',
    'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
    'driver' => 'mysql',
  );

$settings['install_profile'] = 'standard';
$config_directories['staging'] = 'sites/default/config';
$config_directories['sync'] = 'sites/default/files/config_zB_DnNUK68i5Owp5a8FzTiClQfp3d3jrwcy0_HuS1hNCGv9Y_Iva2Ahm8LCH-P0j0M2jwmQAsA/sync';

You need to check for the right php.ini file. Be aware, that drush is using the CLI (command line interface) version of PHP, which might use a different php.ini file than the version used by your web server.

Your above error message states, that the CLI version has a memory limit of 128MB only (which is the default value that might even be used when there is no php.ini file for your PHP version).

In Windows you can find out the used php.ini file - or the folder where it is expected - by typing the following command to your Windows command prompt:

php -i | findstr /c:"php.ini"

In Unix compatible systems you could use grep instead:

php -i | grep "php.ini"


How does one compare a date field with the non-UTC user/system time? Date field data won't always correspond to UTC. From a user perspective, these dates are assumed to be in the user's timezone.  However, it is currently not possible to store dates in timezones other than UTC, at least until Add ability to select a timezone for datetime field gets in.

So when comparing these fields to the current time, the timezones won't match because the current time is in the local timezone and the field data is in UTC. We therefore need to adjust the current time to match the incorrect date field timezone (or vice versa).

What's a good solution for this?

I've developed a method to handle the conversion, thanks to help from another answer to another question.  It requires a patch from Add DateTimePlus::getPhpDateTime() for situations that require a DateTimeInterface to work, however.

  /**
   * Fetches the current time adjusted for comparing to non-UTC date fields.
   *
   * Date field data won't always correspond to UTC. From a user perspective,
   * these dates are assumed to be in the user's timezone.  However, it is
   * currently not possible to store dates in timezones other than UTC. So when
   * comparing these fields to the current time, the timezones won't match
   * because one is the local timezone and the other is in UTC.  We therefore
   * need to adjust the current time to match the incorrect date field timezone.
   *
   * @param Drupal\Core\Datetime\DrupalDateTime $date_time
   *   The date-time object fetched from a Date field (e.g. field_date->date).
   */
  protected static function getCurrentTimeForComparingToDateFieldIncorrectlyStoredInUtc(DrupalDateTime $date_time) {
    $current_time = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
    $userTimezone = new \DateTimeZone(drupal_get_user_timezone());
    $timezone_offset = $userTimezone->getOffset($date_time->getPhpDateTime());
    $time_interval = \DateInterval::createFromDateString($timezone_offset . ' seconds');
    $current_time->add($time_interval);
    return $current_time;
  }


Add PHP code to a node Is it possible to add PHP code to a node? I have enabled the Context and Context PHP modules.

May anyone please tell me how I can do?

Enable PHP Filter module comes with Drupal core

  The PHP filter core module adds the ability to include PHP code in
  posts. PHP is a general-purpose scripting language widely-used for web
  development; the content management system used by this website has
  been developed using PHP.

The following is a guide to add a new text format filter in Drupal 7:

Navigate to the Text formats page Administer » Configuration » Content authoring » Text formats (/admin/config/content/formats).
Click Add Text Format (admin/config/content/formats/add).
Enter the following information:
Name: The name of the filter as it will appear in the administration interface.
Roles: Select one or more roles that will be able to use the format.
Enabled filters: Enable one or more filters.  Note: As filters are selected, items are added to the Filter Processing Order and Filter Settings sections.
In the Filter processing order section, drag the four-headed arrow to rearrange the order in which the filters will be applied.
In the Filter settings section, specify the settings for the selected filters. Some filters do not have settings.

Click Save Changes
WARNING: Some HTML markup should only be available to authenticated and trusted users. The PHP option should not be enabled unless it is necessary and care should be taken to limit access to a role representing trusted and knowledgeable users.


Any way to create a permissions-like sea of checkboxes? Basically I am looking for something like this (square brackets are checkboxes):

  A  B  C  D  E
1 [] [] [] [] []
2 [] [] [] [] []
3 [] [] [] [] []

Are you looking for Node Permission Grid module ?

This will give permission grid like


Getting the display value for a form option with webform 3.x while processing submissions I want to create an associative array of submitted form data and do some additional processing on the submitted data (namely send the data over http POST). I have the following code:

function webformssalesforce_form_alter(&$form, &$form_state, $form_id) {
    if (substr($form_id, 0, 20) == 'webform_client_form_') {
        // Add the submit handler after the existing Webform submit handler,
        // but before the second Webform handler. Pop off the first one and add
        // ours second.
        $first = array_shift($form['#submit']);
        array_unshift($form['#submit'], $first, 'webformssalesforce_client_submit');
      }

}

function webformssalesforce_client_submit($form, &$form_state) {
    $node = node_load($form_state['values']['details']['nid']);

    $fields =  Array();
    foreach($form_state["values"]["submitted_tree"] as $key=>$value) {
        if(! is_array ( $value)){
            $fields[$key] = $value;
        }
    }

    //do stuff with $fields

}

This works fine for text and email fields, however for select elements I get the option's safe_value instead of the display value for the select. So for example if an element has the folowing options:

1|Display value 1
2|Display value 2
3|Display value 3

How can I get the display value instead of the safe_value (Display value 2 instead of 2) for an element?

I'm pretty sure this code worked fine for me with a previous version of webform.

I've run into the same issue, could not find a predefined function and ended up writing one that loops over the select options in the text area and returns an associative array.

The basic principle is described in this article:
http://blog.raisedeyebrow.com/2009/01/displaying-webform-results-in-a-block/

For my project I used the webform_submission_insert hook instead of form_alter, but I hope it works for the variables that you have available in form_alter as well.

If it is likely that you'll need this feature more often you may want to use a function to extract the data for any textarea using the same principle.

function mymodule_webform_submission_insert($node, $submission) {

   switch ($node->title) {

    case "Test form":

    $options = array();

    // fill options field with options from select textarea via custom function;
    // field number of my particular webform select field is 12, hence:
    $options = _extract_select_options ($node->webform['components'][12]['extra']['items']);

    // output key and value of chosen select option
    $chosen = $options[$submission->data[12]['value'][0]]);
    drupal_set_message ("key / value: ".$submission->data[12]['value'][0]." / ".$chosen;

    break;
   }
}

// declare function with text area content as parameter
function _extract_select_options ($mytext) {

    $options = $pairs = $temp_array = array();

    // split text into chunks after each line-break;
    // if not visible here, use "backslash n" as explode parameter
    $pairs = explode("\n", $mytext);

    // split each line into pairs of key and value
    foreach($pairs as $pair) {
      $temp_array = explode('|', $pair);
      $options[trim($temp_array[0])] = $temp_array[1];
    }

    return $options;

}


Allow people to administer only on certain content type? Under "admin/people/permissions" there is a permission that allows users to administer all the content types.

I want to create a role that can only administer an "Article" content type.
How can I achieve this?

The menu callback for "admin/structure/types/manage/%node_type" is defined in node_menu() using the following array item:

  $items['admin/structure/types/manage/%node_type'] = array(
    'title' => 'Edit content type',
    'title callback' => 'node_type_page_title',
    'title arguments' => array(4),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_type_form', 4),
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );

There are other two menu items that follow it, but they depend from that menu item for the access callback.

  $items['admin/structure/types/manage/%node_type/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
  $items['admin/structure/types/manage/%node_type/delete'] = array(
    'title' => 'Delete',
    'page arguments' => array('node_type_delete_confirm', 4),
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );

Once you change the access callback for the first menu item, the other two will use the same access callback.

The first step, for the custom module I would implement to achieve what you want is to implement hook_permission(). node_permission() is useful as guideline to write the code you need.

function mymodule_permission() {
  $perms = array();

  foreach (node_type_get_types() as $type => $info) {
    $perms["administer $type content type"] = array(
      'title' => t('%type_name: administer content type', array('%type_name' => $info->name)),
    );
  }

  return $perms;
}

The foreach() part could be rewritten as the following code:

  foreach (node_permissions_get_configured_types() as $type) {
    $info = node_type_get_type($type);

    $perms["administer $type content type"] = array(
      'title' => t('%type_name: administer content type', array('%type_name' => $info->name)),
    );
  }

The difference is that node_permissions_get_configured_types() is using some Drupal variables that are set in a settings page. The function is used also from the Node module when creating the list of the permissions associated to a node of a content type. The documentation for the function reports the following text:

  To exclude a specific node from getting permissions defined for it, set the "node_permissions_$type" variable to 0. Core does not provide an interface for doing so; however, contrib modules may exclude their own nodes in hook_install(). Alternatively, contrib modules may configure all node types at once, or decide to apply some other hook_node_access() implementation to some or all node types.

The second step is to alter the menu item already defined by the Node module.

function mymodule_menu_alter(&$items) {
  if (isset($items['admin/structure/types/manage/%node_type']) {
    $items['admin/structure/types/manage/%node_type']['access callback'] = '_mymodule_content_type_access';
    $items['admin/structure/types/manage/%node_type']['access arguments'] = array(4);
  }
}

_mymodule_content_type_access() should contain code similar to the following one:

function _mymodule_content_type_access($type) {
  return user_access("administer {$type->type} content type");
}


Panels page won't load I have created a panels page using Panels and for some reason it takes an age to load. It seemed to have started when I added another panels page as a child of this one, and added a navigation block to the left column.

Is there any way to debug this? I've tried using Firebug to check the Net tab, but it just loads and loads. This is running on my localhost so it must be a code loop somewhere, but I've no idea how to find it.

I've checked the reports.

Drupal 7.8
Panels 7.x-3.0-alpha3
Chaos tools 7.x-1.0-rc1

I found this in my log, any ideas?

Type    theme
Date    Monday, September 19, 2011 - 12:33
User    admin
Location    http://localhost/project01/admin/structure/pages/nojs/operation/page-about_us/handlers/page_about_us_panel_context_3/content
Referrer    http://localhost/project01/admin/structure/pages/nojs/operation/page-about_us/handlers/page_about_us_panel_context_3/content
Message Theme key "panels_edit_display_form" not found.
Severity    warning
Hostname    127.0.0.1
Operations

Yes, this is an issue with the module. Fortunately there is a patch.


How to use Drupal.behaviors in Drupal 7? I have these codes in my druapl 7 theme js file (js/test.js):

 (function($) {
    alert("Hi");
    Drupal.behaviors.mythemename = {
      attach: function(context, settings) {
        alert("Bye");
      }
    };

 })(jQuery);

then I call this file using :

 drupal_add_js(drupal_get_path('theme', 'mythemename'). '/js/test.js');

in page--front.tpl.php file inside the theme folder.

But only the first alert is shown.
Why is it so? where is my problem ?

Probably to late to load the js file in the .tpl try in template.php with

YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('theme', 'mythemename'). '/js/test.js');
  }
}


Creating some views fields for a taxonomy menu with the active trail CSS classes? I have a taxonomy vocabulary which I want to use to create some navigation on my site.

Terms:

Weather
Clothes
Calendar
Sports

I want to be able to pull these terms and put them in the  navigation of the site. However, I want to be able to rewrite the links that these terms go to, so that rather than going to the taxonomy terms default page they go to:

/topic/[insert_taxonomy_term_here]/step-2

This is because I have a view with the [name] of the taxonomy term using that term as a contextual filter.

I'm having no problem creating such a menu tree in Views, but when I grab the taxonomy terms, as a views field, they are output without the standard Drupal active trail css classes, so that I cannot style them to show them as active.

Is there a way therefore to create a taxonomy menu in views in which the fields output the Drupal active trail?

D7 - with latest updates - 27th Oct 2013.

Silly me!! This is how you do it, without even thinking


How to get the destination nid from an URL object In a preprocess function I want to access the destination node id via the URL object
I cannot find any method that will return the node id for me but I can clearly see that it holds the node id. (see attached)

Any idea how I can get the node id without going the long way of generating it from the URL path?

Looks like you're using the latest Devel, 4.0.1, which sadly currently doesn't show the available methods tab unless you patch it.
If you had the available methods tab, you would've seen that you can retrieve using the public method getRouteParameters
$nid = $url_object->getRouteParameters()['node'];


What hooks are being invoked on a node edit form I'm using Drupal 6 with many modules. It often happens that I'm trying to track down which hooks are being invoked on a specific form, but up till now I've been making educated guesses. How can I figure out which hooks are being invoked on a node edit form (or other forms)?

hooks are basically functions provided by drupal to developer , so as to create a communicating medium between developer and drupal.
hooks get called or render on a page when particular action associated with them take place it is more like drupal send a message to hook "describing what action drupal is doing " and hook ask developer "drupal is doing this do you want to add more stuffs or to perform any action on this action of drupal"

so depending on action taking place hooks are invoked


Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_view() My Drupal installation has some warnings, I tried several patches, but none of them works for me. These are the warning messages:

Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_prepare_view() (line 1677 of modules/taxonomy/taxonomy.module).
Warning: Invalid argument supplied for foreach() in taxonomy_field_formatter_view() (line 1600 of modules/taxonomy/taxonomy.module).

It looks like I get those warnings randomly, I can't find a specific handling.
I think I get this message when I create/edit a node.

As per this post, this warning can be eliminated by editing the field on each file type which is having a field and unchecking Override in WYSIWYG (at /admin/structure/file-types). This happens because term reference doesn't support overridable in the WYSIWYG.

This issue at Drupal.org: #2062721: Add a white list of file fields that can be overwritten when the file is added in the wysiwyg, aiming to solve that issue. At time of writing, there is still some patch which is in Needs review status.


Where to look for a forum thread in database? In Drupal 6 forum, a user reported that her thread has suddenly disappeared.

I am wondering in which database table should I look for the thread, and what might be the cause?

I don't know how 6 version works with forum (because I've never used 6v), but in d7 forum is actually is a node (threads are node types). I thinks you can search for forum table which holds the nids of threads and node and node_type tables for actually for that nodes and thread type...

To find the node by Title:
Open your PhpMyAdmin from browser -> select your db -> open 'node' table -> switch to SQL tab -> SELECT * FROM node WHERE title = "YOUR TITLE"

EDIT:
threads are taxonomies, not node types (based on comment of Mohammad Ali Akbari)


hook_views_query_alter if date field empty sort with another field postdate I have a view that show all contents of type NEWS
NEWS has like fields :

Content = Title

Scheduler = publish-on

and in sort criteria : I want sort contents with two option :
With scheduler (publish-on = DESC)
and With post date

I want sort content with scheduler, and when scheduler field is empty he sort with post date. I have created hook views query alter
and I have a problem, how can I sort field with condition if publish_on is empty then sort with postdate

function custom_sort_views_query_alter(&$view, &$query) {

    if($view->name === 'articleview') {
        $view->query->add_where(1,'publish_on',  'NOT IN');
        $view->query->orderby[0]['field'] = "CASE WHEN publish_on IS NULL THEN created ELSE publish_on END";
        $view->query->orderby[0]['direction'] = "DESC";
        $view->query->orderby[1]['field'] = "created";
        $view->query->orderby[1]['direction'] = "DESC";
    }
}

The solution that comes to my mind now (after your question's comments) is make two queries, one query with the records that have publish_on field empty and the other with the field non empty and then use a UNION between them.

Why this? AFAIK You can't sort some records in a query based in a condition and other records based in another condition, so to achieve this you must split the records and apply the sort method separately. This is records of a condition first and records of another condition before, but you can't merge the records and the order condition.

Maybe this posts can help you:

https://stackoverflow.com/q/2258376/3653989

https://stackoverflow.com/q/19296047/3653989

https://stackoverflow.com/q/3730093/3653989

Maybe you also want to read http://www.w3schools.com/sql/sql_union.asp


Upgraded Drupal 7.37 to 7.38 using Drush and its not working. update needs a higher bootstrap level to run - Error I am new to Drupal.  I am reading a book called Definitive Guide to Drupal 7.  I had installed Drush on Windows 7 with Git as well.  It was working last week.   Since 7.38 is released I tried to update my localhost website for this particular book and I am getting an error.  I have googled this problem and I am coming up with some solutions but they are not working for me.  I have navigated to the root folder of the Drupal installation in Git before using Drush Up. I have also changed the 'host' value in settings.php to '127.0.0.1'. It was 'localhost' before.  I don't know how to fix this. Does anyone know?

Anthony@ANTHONY-PC ~
$ cd c:/wamp/www/definitiveguided7

Anthony@ANTHONY-PC /c/wamp/www/definitiveguided7 (master)
$ drush up
Command pm-update needs a higher bootstrap level to run - you will       [error]

need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'up' could not be executed.                            [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.37
 Site URI               :  http://default
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database port          :
 Database username      :  root
 Database name          :  definitiveguided7
 PHP executable         :  php
 PHP configuration      :  C:\wamp\bin\php\php5.5.12\php.ini
 PHP OS                 :  WINNT
 Drush script           :  C:\Users\Anthony\AppData\Roaming\Compose
                       r\vendor\drush\drush\drush.php
 Drush version          :  8.0-dev
 Drush temp directory   :  C:/Users/Anthony/AppData/Local/Temp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  C:\wamp\www\DefinitiveGuideD7
 Site path              :  sites/default

Make sure your Drush commands are issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site, is it?), and then retry your Drush comand ... Seems that is what is causing your problem ...

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...


How to add block template suggestions? I want to be able to create a block or place a block into a region and theme it according to the selected view mode from Panels. I have noticed a discrepancy between Custom Block and Entity Block where one form gives you the view mode to show the block in, and the other does not (Custom Block).

I want the template suggestion to be along the lines of block--provider/module--block-bundle--view-mode.html.twig but struggling to find consistency in the variables in hook_theme_suggestions_block_alter() in order to add the suggestion. At the same time, I want to enforce the template that is used no matter if the user created the block inline, or referenced an existing block via Entity Block. What keys or identifiers can I look for to make this work?

Normally a content entity has a template, like node.html.twig for node, so for custom blocks there should be block-content.html.twig. To avoid overhead it was decided to remove this template. This means you can't add template suggestions to the entity template, instead you have to add them to the block template. In this case you get the variables from the plugin when adding suggestions and you don't find the view mode or other details in a consistent way like for entities.

Additionally you use two different plugins to place the block:

Original block plugin for Custom Blocks (core)

http://cgit.drupalcode.org/drupal/tree/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php?h=8.4.x
Block plugin from Entity Block (contrib)

http://cgit.drupalcode.org/entity_block/tree/src/Plugin/Block/EntityBlock.php?h=8.x-1.x

The second method, this is using custom blocks outside of the core block content plugin is not officially supported, because the pair of both are optimized to work together.

For the second method a custom entity might be a better choice (then of course one which has a template, which is standard for entities built by Drupal Console ).

  I have noticed a discrepancy between Custom Block and Entity Block
  where one form gives you the view mode to show the block in, and the
  other does not (Custom Block).

Checking the linked code from the Custom Block plugin. It should show the view mode, if there is more than one to choose from:

$form['view_mode'] = [
  '#type' => 'select',
  '#options' => $options,
  '#title' => $this->t('View mode'),
  '#description' => $this->t('Output the block in this view mode.'),
  '#default_value' => $this->configuration['view_mode'],
  '#access' => (count($options) > 1),
];


Output both form and generated image (imagejpeg) onto same page This is my first newbie module (drupal 7). It's 'simple' but needs help x2.

Intention: To create an online image-name generator i.e, user types their name into a formfield and the browser outputs the text as a jpg image so they can right-click and save.

What I've done: 1. created one hook menu with two callback functions, one for the form and one for the image output.
2. A working form where user types in their name. 3. Able to output Image by setting name input manually through code, not by submitting the form!

What doesn't work: I created a $name variable within the form function, but using that same $name variable within the image-output function won't work. So I can't output  a text-image when users submit the form.  Also I don't know how to render both form and image output onto the same page.

I need help with: 1. How to render both form and image onto the same page?.
2: How to associate $name variable so inputted text will render upon submit button.

Frameyourname.module:

<?php

//Create simple image-generator.

//Implements hook_menu().

function frameyourname_menu() {
$items['frameyourname'] = array(
'title' => 'Frame Your Name form',
'page callback' => 'drupal_get_form',
'page arguments' => array('frameyourname_nameform'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
);

//not entirely sure what to put here.

$items['image'] = array(
'title' => 'image',
'page callback' => 'drupal_get_form',
'page arguments' => array('create_textimage'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
  );

return $items;

}

// Define a form.

function frameyourname_nameform() {
$form['user_name'] = array(
'#title' => t('Your Name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}

// Validate the form.
function frameyourname_nameform_validate($form, &$form_state) {
}

// Handle post-validation form submission.
function frameyourname_nameform_submit($form, &$form_state) {

//set name variable associated with user input and test if works.
$name = $form_state['values']['user_name'];
drupal_set_message(t('Thanks for adding your name,'.  $name));
}

// create image
function create_textimage() {

// Create a blank image and add text as per form input
$im = imagecreatetruecolor(400, 400);
$text_color = imagecolorallocate($im, 233, 14, 91);

//trying to reference $name variable not sure how.
imagestring($im, 1, 5, 5,  $name, $text_color);

// Set the content type header
drupal_add_http_header('Content-Type', 'image;jpeg');

// Output the image
imagejpeg($im);

// free from memory
imagejpeg($im);

}

If you put $form_state['rebuild'] = TRUE in your submit handler then the form's redisplayed and you have access to $form_state['values'] in the form constructor. This is typically how multi-step forms are done. So in this case something like:

if (empty($form_state['values']['user_name'])) {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
}
else {
  $form['image'] = array(
    '#theme' => 'image__nameform',
    '#path' => $path,
    '#width' => $width,
    '#height' => $height,
    '#alt' => $form_state['values']['user_name'],
  );
}

To pass the name to your image generation function you want to change its entry in hook_menu(): the path should be image/% (which says there's an argument), page callback create_textimage (because that's what generates the content) and page arguments array(1) (because the text is the second argument, and you start numbering at 0). There are more details in the documentation for hook_menu().

A few other points not directly related to the Q:

Currently the image generation function is a bit of a DOS vector (because it's a bit CPU intensive, isn't cached, doesn't require auth, and doesn't require a form submission).
You should use drupal_set_message(t('Thanks for adding your name, %name.', array('%name' => $name));. This is secure and translatable - see t() and format_string().
The function names are a bit all over the place. If your module's called frameyourname then all your functions should start with that (with a few exceptions). Also I'd suggest avoiding a path like image/% in favour of something more specific like frameyourname/%.


Does Strongarm need to be enabled on Production site using Features? I'm using Features in order to make my site content configuration exportable for purposes of staging my server. I'll be using Strongarm to make some of the site variables exposed for management in a feature.

Does the Strongarm module need to be enabled on my live production site in order for the active features to be able to present and set the variables which I have encapsulated within them?

Or, does Strongarm only need to be enabled on my dev server where and when I am creating my features components?

Yes, you need the strongarm module on production site as the module implements hook_features_revert and hook_features_rebuild which is needed to do any reverts to the variables you have featurized or to apply new variables that u have introduced in your feature.


How do I create menu links programmatically? I need to add some links to existing menu (or to new) programmatically in Drupal 8.

In order to create a menu item automatically this can be placed in a hook_update_N on the file mymodule.install and will run when the database is updated (/update.php):

use Drupal\menu_link_content\Entity\MenuLinkContent;
$items = array(
  '1' => 'Menuitem 1',
  '2' => 'Menuitem 2',
  '3' => 'Menuitem 3'
);

foreach($items as $nid => $title) {
  $menu_link = MenuLinkContent::create([
    'title' => $title,
    'link' => ['uri' => 'internal:/node/' . $nid],
    'menu_name' => 'main',
    'expanded' => TRUE,
  ]);
  $menu_link->save();
}

You can also create an entire Menu programmatically:

\Drupal::entityTypeManager()
  ->getStorage('menu')
  ->create([
    'id' => 'menu_test',
    'label' => 'Test menu',
    'description' => 'Description text',
  ])
  ->save();


I install ultimate cron and I saw that errors I have all this error but when i am running cron without cron ultimate all run perfect but with cron ultimate i got that errors... Could anyone help i really need help here:

    exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error
    or access violation: 1064 You have an error in your SQL syntax; check
    the manual that corresponds to your MySQL server version for the right
    syntax to use near '))' at line 1' in
    /var/www/html/drupal7.36/includes/database/database.inc:2171
    Stack trace:
    #0 /var/www/html/drupal7.36/includes/database/database.inc(2171): PDOStatement->execute(Array)
    #1 /var/www/html/drupal7.36/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)
    #2 /var/www/html/drupal7.36/includes/database/query.inc(858): DatabaseConnection->query('DELETE FROM {er...', Array, Array)
    #3 /var/www/html/drupal7.36/sites/all/modules/bla/includes/bla.functions.inc(245): DeleteQuery->execute()
    #4 /var/www/html/drupal7.36/sites/all/modules/bla/bla.module(56): bla_clean()
    #5 [internal function]:bla_cron()
    #6 /var/www/html/drupal7.36/sites/all/modules/ultimate_cron/ultimate_cron.module(941): call_user_func('bla_...')
    #7 [internal function]: _ultimate_cron_run_hook('bla_...', Array)
    #8 /var/www/html/drupal7.36/sites/all/modules/background_process/background_process.module(574): call_user_func_array('_ultimate_cron_...', Array)
    #9 /var/www/html/drupal7.36/sites/all/modules/background_process/background_proces
    s.module(503): background_process_service_execute('uc:error_log_ji...', false)
    #10 [internal function]: background_process_service_start('uc%3Aerror_log_...')
    #11 /var/www/html/drupal7.36/includes/menu.inc(519): call_user_func_array('background_proc...', Array)
    #12 /var/www/html/drupal7.36/index.php(21): menu_execute_active_handler()
    #13 {main}

function blabla_clean() {
  $number = variable_get('blabla_number_select');
  // Keeps values equal to the number that user had selected.
  $query = db_select('blabla', 'j')
    ->fields('j')
    ->range(0, $number)
    ->orderBy('j.timestamp', 'DESC');
  $ids = $query->execute()->fetchCol();

  // Deletes all the other values.
  db_delete('blabla')
    ->condition('wid', $ids, 'NOT IN')
    ->execute();
}

The issue isn't Ultimate cron, per se. It's your custom bla module; it's running some function called bla_clean() that's building a Delete SQL query with broken syntax. When executed, it's producing the error.

You're using the NOT IN operator incorrectly. Here's a post that demonstrates a NOT IN within a query.


How to link Profile2 fields in Views? Using Views in Drupal 7, I have listed certain fields of profiles (eg. Name, Job) and then link each field to the relevant profile. Now I am wondering how to link the fields to the relevant profile. I appreciate your hints.

I assume you add Views for User listing:

add "User: uid" field;
exclude from showing;
move to the top of field list (rearrange);
Click on field, that you want to link with user profile.
Expand: Rewrite results
Check: Output this field as a link R
In the bottom, find "Replacement patterns", user uid  pattertn: [uid]
Place it on "Link path" next text: user/[uid]
Check that link appear.


Commerce add to cart not adding product to cart I have an e-commerce site. In that, I have created product listing page using views. I have added add to cart field in the view, so the every product in the view will have add to cart button. I have enabled views caching.

When I click on add to cart button for first time it adds the product to cart. After that product is not added to cart it just reloads the page and doesn't throw any error.

After searching I found the solution https://stackoverflow.com/questions/34732300/caching-product-display-with-display-cache-and-still-be-able-to-add-products but it is not working. Kindly help me.

Go to views of the page that contain add to cart button, in advanced and in caching you find none and time based, tick none and the problem will resolved.


View with two filter groups using "OR" not aggregating correctly I have a view that I need to count the number of items currently unread. It is a list that combines slightly different entities on slightly different conditions, so I have two filter groups(using OR) on my view to select all content appropriately. This works well except for the aggregation of the results. When I set the view to aggregate by counting a nid field, it doesn't aggregate the results. Instead, it simply converts each nid result to display as "1".

Where is my attempt to aggregate this view going wrong?

My filters:

My Results:

The answer to this was actually quite simple, and the source of error was misunderstood.

The filter groups were NOT the issue at all, but rather that there were excluded fields in the view which were not set to "count" under their aggregation settings. This broke the count. If you are having this issue, make sure all fields in your aggregation view are set to "count".


How can I get Panelizer to link my panels to a specific URL instead of the Content option? This is the page that is shown when I configure a panel. How do I link the image to some other page than the content page? I am using Drupal 7. I think this question would benefit others who wish to link their images to other URLs when using Panelizer. I tried using the panels image link module, but I couldn't find any documentation and it didn't seem to do much.

I found out that I can make a user-uploaded image linkable to a fixed location that I choose. If I create a view that takes in the user-uploaded picture, and then add a link through views, Panelizer will let me place the view in a pane. This means I can have a linkable image in a pane. I have included step-by-step pictures.

This shows up upon the creation of a view. Click the add button by the fields in the left column to add the picture from a content type.

This shows you that a content node needs to be picked. In this case, it is a picture that the user uploads

Upon the selection of the picture views will ask how to display it. I have selected "Output as a link" This will then open up this part of the menu:

Here you can select the URL you want the link to go to. For example, somewhere on your site or to drupal.org :)

You then need to save everything. Then, go back to panelizer, or panels. There select a cog wheel and add content. This page should look like this:

Then, it will bring up a window where you will need to click on the views option:

Then you should see these windows:


Help needed getting out of the habit of using TWIG as my Controller and Template files I'm currently using TWIG to manipulate variables that have been created in Drupal 8. For example, I have a template that contains the following logic:

{% if item.field_main_images[0] %}
  {% if item.field_main_images[0]['#item'].entity.uri.value != "" and item.field_main_images[0]['#item'].entity.uri.value is not empty %}
    {% set main_image_uri = item.field_main_images[0]['#item'].entity.uri.value %}
    {% set main_image_zoom = main_image_uri | image_style('item_zoom') %}
  {% endif %}
{% endif %}

and

{% set featured_content = '' %}
{% if item.field_item_specification.0['#text'] is not empty %}
  {% set featured_content = item.field_item_specification %}
{% endif %}

Am I missing something here because i'm getting caught in spending a lot of time figuring out the data structures of the objects and manipulating the logic within my TWIG templates. I've got a feeling that I should be doing this in either a preprocess function on the content type or by some other means.

How could I perform this same procedure using the drupal framework i.e. symphony to create/manipulate the variables before the use of a twig template.

Can anyone shed some light on this?

Thanks in advance.

You are right, this kind of code should be in your controller or in preprocess functions.
You should generate a  render array for each twig template, to be able to have a simple :

{{ image_with_zoom }}

In your twig file. Your controller could have something like :

  $renderArray = [];
  /* @var $item \Drupal\node\Entity\Node */
  if($item->field_main_images->count()){
    $image = File::load($item->field_main_images->target_id);
    $renderArray['image_with_zoom'] = [
      '#theme' => 'image_style',
      '#style_name' => '...',
      '#uri' => $image->getFileUri(),
      '#attributes' => [
        'data-zoom-url' =>  ImageStyle::load('item_zoom')->buildUrl($image->getFileUri())
      ]
    ];
  }

Have also a look at field formatters, it allow you to get your own controls for each field you wish to display.
You can generate some skeleton with the drupal command :

$ drupal gpff

Have a look at documentation on this point, and the one in the drupal console. That's quiet important if you wish to reuse some display for a particular field as it looks like.


Form with Ajax and without I am constructing a form that is handled via Ajax. I need it to be avaible on browser where javascript isn't activated. For now, the submit part is like :

$form ['submit'] = array (
  '#type' => 'button' ,
  '#ajax' => array (
      'callback' => 'MODULE_form_ajax_callback',
      'wrapper' => 'result-div'
  ),
  '#value' => t ( 'Launch' ),
  '#weight' => 10000
);

Has anyone resolved a similar issue ?

Thanks,

try to change '#type' => 'button' to '#type' =>'submit' and then implement hook_form_submit()


Render Drupal variable in CKeditor im trying to render/display a breadcrumb in a mini panel using both with text format 'PHP code' and 'Display suite code' but it display nothing. it works when i tried with common php code;

<?php echo date("Y"); ?>

but when i tried with

 <?php print render($breadcrumb); ?>

nothing is displayed. and

<?php var_dump($breadcrumb); ?>

return NULL.
meaning it cant read drupal variable right? any workaround for this?

First thing is this its not a good practice to write the php code in CKeditor because it impact the execution of page and increase the page load time.
So it would be better to create the specific page tpl and and render all the drupal variable there.

Reason ::  Why its not rendering the drupal in CKeditor because after the complete page load its execute the content section of CKeditor and at that page has not page drupal variable (now page has only html content).

Thanks


How to use images in theme settings In Drupal 7, I am trying to put an image field to allow an image to be uploaded to the theme settings.

I am using managed file from the form API to do this. Here is my code:

  $form['footer']['footer_logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('The uploaded image will be displayed on this page using the image style choosen below.'),
  '#default_value' => variable_get('footer_logo', ''),
  '#upload_location' => 'public://footer_logo/',
);

When I call the image using theme_get_setting('footer_logo'), I just get a set of numbers. How can I get the file path of the image instead? Also, is there away to pass the image through image cache settings.

It seems that this could provide an answer to your question :

$fid = theme_get_setting('footer_logo');
$image_url = file_create_url(file_load($fid)->uri);

(but I didn't test it).