When "drush updatedb" is executed, are scripts cached by OPCache invalidated? For sites that have PHP OPCache enabled:

Does updating site using Drush require restarting the webserver to invalidate the scripts cached by OPCache?
Does Drupal core or Drush invalidate OPCache before running updates?
Is setting opcache.enable_cli to 0 a better strategy in this scenario?

Updated response to address the questions as asked.

Yes, either the web server need to be restarted or the web-server's OPCache needs to be cleared. Drush cannot clear the web-server's opcache as it is a CLI application. Instead of restarting the web server a php script with following content can be added to next to Drupal's update.php
 <?php
 opcache_reset( );
 /*
 Following measures should be taken to safeguard this file from malicious use
 a) Set filename with a long random string as a name (like 100+ characters).
 b) Check the IP address of the requester so the script can only be called from trusted networks.

 To clear cache visit this file at
 siteurl/random_long_string_eiquooR3.php
 or use curl siteurl/random_long_string_eiquooR3.php
 Check the IP address of the requester so it can only be called from trusted networks.
 */

Neither Drupal core nor Drush invalidate OPCache.

Yes, setting opcache.enable_cli to 0 is a fine, it is anyways off by default. Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

Original Answer by @greggles

Restarting the webserver works, but takes quite some time. A more efficient solution is to have a way to call opcache_reset.
Opcache must be reset by calling opcache_reset from within the web process. If you call it inside drush then it will not clear the opcache for the webserver so it won't help the problem.
Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

If you want to clear opcache as part of a deploy process, I suggest adding a file that contains opcache_reset and then you have to protect access to that file so malicious users can't easily call it:

Give it a long random string as a name (like 100+ characters).
Check the IP address of the requester it can only be called from trusted networks.


How to add active class to a specific menu only, while ignoring other menus? I have 2 conflicting menus I need to solve by adding an active class to a targeted menu only, they are a user menu and a profile and account settings menu which have overlapping links.

User Menu (in the header section of every page):

[username] (links to Profile2 page)

Account Settings  (i.e. change password, etc.)
Log out

Profile and Account Settings menu (appears in the sidebar of the profile2 and account pages):

View Profile (links to Profile2 page also)
Edit Profile
Account Settings (same link destination as "Account Settings" of User Menu)
Order History

Since I'd like to convey to my users that whenever they are in any page linked by the Profile and Account Settings menu (eg. Edit Profile)I tried using Context to set an .active class for "User Menu>Profile", which worked.

However, now that "User Menu>Profile" is active when I'm in "Edit Profile", since "View Profile" shares the same link destination as "User Menu>Profile", both "View Profile" and "Edit profile" are have an .active class, which is very undesirable.

Hence, I would like to know, if there is a way to use Context or any hooks to set an .active class for the User Menu only when I'm in the "Edit Profile" page?

Try the  following modules

1)Menu Position

  Often times site builders want certain types of content to appear in a specific position in the navigational menu. The simplest solution, adding all of that content individually to the menu system, has performance and usability issues. (Imagine hundreds of menu items added to one spot in the menu.)

  This module allows for the creation of rules that will dynamically add the current page into the menu system at the requested spots.

I've used Menu Position module for one of my project and it works great!

OR

2) Menu Trail By Path

  Menu Trail By Path sets the active-trail on menu items according to the current url.

  For example if you are at yoursite.com/blog/category1/article1
  Menu Items with these paths will get the active-trail class on them and expand accordingly.

  blog

  blog/category1

  blog/category1/article1


Multiple Drupal sites using the same code base Is it possible to use the same Drupal code base for different Drupal sites, just by changing settings.php and the database settings, and accessing it through a subdomain?

coleopterist is right.

Let's say you want mydomain.com and sub.mydomain.com to share the same codebase, you will have to put two folders in sites/ :

sites/mydomain.com/
sites/sub.mydomain.com/

If you want modules and themes to be available to all domains defined in sites/, all you have to do is to put them in all/ :

sites/all/modules/
sites/all/themes/

Then, in sites/{domain}/settings.php you can redefine the databases strings like so :

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'database_name',
      'username' => 'user_name',
      'password' => 'p4ssw0rd',
      'host' => '127.0.0.1',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
  ),
);

Note that you should launch the DrupalRoot/install.php script for each different domain to create its database tables.


How do I theme a menu to have a wrapper div with menu name? The default menu theme function doesn't output the menu name (see below).

function theme_menu_tree($variables) {
  return '
' . $variables['tree'] . '
';
}

I've inspected $variables, and that doesn't contain the menu name. Does anyone know how I can theme a menu so that its name is in a wrapper div?

theme_menu_tree() is a theme wrapper function: it's called after the render array for the menu tree is rendered, and thus, after you have a chance to modify the rendered output.

Additionally, you can't pass any arbitrary data to a theme wrapper function: it'll always receive the rendered output of the children.

So to do what you want to do, where you have a wrapper
 that has an ID, you need to modify the menu tree render array to call your own theme function that adds it.

Practical example

Let's say you're trying to do this for all menu blocks (a common use-case for menu trees): menu_block_view() populates the content of the block with menu_tree($delta), where $delta happens to be the menu name corresponding to the block.

Now, menu_tree() calls menu_tree_output(), which is where the render array that calls theme_menu_tree() is built.

So, what you want to do is modify the contents of the block after the render array is built, to replace theme_menu_tree() with your own theme function that adds your
 with ID. To do that, implement hook_block_view_alter():

/**
 * Implements hook_block_view_alter().
 */
function MYMODULE_block_view_alter(&$data, $block) {
  // Check to make sure this is a menu block
  if (in_array($block->delta, menu_get_names())) {
    // Replace the theme wrapper function with a theme function
    // and add the menu name to the render array
    unset($data['content']['#theme_wrappers']);
    $data['content']['#theme'] = 'MYMODULE_menu_tree_with_id__' . $block->delta;
    $data['content']['#menu_name'] = $block->delta;
  }
}

Replace MYMODULE with your module's short name. Once implemented, create the theme function theme_MYMODULE_menu_tree_with_id() to handle wrapper
:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme() {
  $theme = array();
  $theme['MYMODULE_menu_tree_with_id'] = array(
    'render element' => 'element',
  );
  return $theme;
}

/**
 * Returns a menu tree with an id corresonding to the menu name.
 */
function theme_MYMODULE_menu_tree_with_id($variables) {
  $output = '
';
  $output .= '
' . drupal_render_children($variables['element']) . '
';
  $output .= '
';

  return $output;
}


How to add custom operation to commerce/orders list? In Drupal 7 I want to add couple of custom operations in the Drupal Commerce's orders list (see picture below) after "delete" e.g. "Shipping List" and "Invoice" which would open external URLs in a new window. How can I achieve this? I tried to modify some files under sites\all\modules\commerce\modules\order\includes\views but I didn't see any change in the view. Why?

The proper way to add new operations is to define them as menu items. Here is a snippet from the payment module, responsible for the payment operation listed in the screenshot:

  // Payment tab on orders.
  $items['admin/commerce/orders/%commerce_order/payment'] = array(
    'title' => 'Payment',
    'page callback' => 'commerce_payment_ui_order_tab',
    'page arguments' => array(3),
    'access callback' => 'commerce_payment_transaction_order_access',
    'access arguments' => array('view', 3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'includes/commerce_payment_ui.admin.inc',
  );

The key part being this line right here:

'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,

In fact, in most (maybe all?) places where you see this list of operations or tasks in Drupal Commerce 1.x, they will be defined this way. Another example of this being the transaction listing screen. Payment modules can add new contextual menu items for things like credits, captures, etc:


Drupal 7 - How to apply Image Styles to a User uploaded logo for a theme I have need to be apply an Image Style setting to the logo uploaded at appearance/settings/THEME_NAME

Use Case is: The theme will be used across multiple unique instances within the organization and associated groups, each with different branding. The installation will be via an Install Profile including preset Image Styles.
The logo will need to be set by the individual installing the site.  It is a requirement that this individual will not need the skill to modify a tpl file in order to set the logo path/size or use any image editing software to modify the logo's dimensions pre upload.

... where to begin?

I suspect there are two routes:

Modify the existing logo field via page.tpl.php to use a predefined image style.
OR Add a new Image field to the Theme's settings form and calling that in page.tpl.php

Either task is pushing my Drupal ability so before I begin I thought I would ask for opinions on my assumed solutions above or better yet, actual solutions to setting image styles for the logo upload. :)

Thanks in advance,
Nick

You should be able to alter the logo-path in hook_preprocess_page and replace the logo path with the path of the transformed logo:

function mytheme_preprocess_page(&$variables) {
  $variables['logo'] = image_style_url('my_image_style', $variables['logo']);
}

Didn't try it out, but it should work somehow this way.

edit: there is a LOT of "logo" in my first sentence ;)


Switch style plugin of a view based on results I would like to create a view, which would display it's result with style plugin Unformatted if there is only 1 result, but would use Bootstrap Accordion style plugin, if there are more of them. I tried to do it like this:

    name == 'some_view_name') {
        if (count($view->result) > 1) {
          $view->style_plugin = 'ViewsBootstrapAccordionPluginStyle';
          $view->style_plugin->plugin_name = 'views_bootstrap_accordion_plugin_style';
          $view->style_plugin->options['title_field'] = 'title';
          $view->style_plugin->definition['path'] = 'sites/all/modules/views_bootstrap/plugins/accordion';
          $view->style_plugin->definition['theme path'] = 'sites/all/modules/views_bootstrap/templates/accordion';
          $view->style_plugin->definition['file'] = 'ViewsBootstrapAccordionPluginStyle.inc';
          $view->style_plugin->definition['theme file'] = 'theme.inc';

        }
      }
    }

The result is this error:

Fatal error: Call to a member function render() on a non-object in .../sites/all/modules/views/theme/theme.inc on line 49

What am I doing wrong?

EDIT: Probably almost everything. $view->style_plugin has to be an object, that was the reason of the error above. So I modified the code to this:

<?php
function my_module_views_pre_render(&$view) {
  if ($view->name == 'my_view') {
    if (count($view->result) > 1) {
      $bs_accordion_style = new ViewsBootstrapAccordionPluginStyle;
      $bs_accordion_style->plugin_name = 'views_bootstrap_accordion_plugin_style';
      $bs_accordion_style->options['title_field'] = 'title';
      $bs_accordion_style->definition['path'] = 'sites/all/modules/views_bootstrap/plugins/accordion';
      $bs_accordion_style->definition['theme path'] = 'sites/all/modules/views_bootstrap/templates/accordion';
      $bs_accordion_style->definition['file'] = 'ViewsBootstrapAccordionPluginStyle.inc';
      $bs_accordion_style->definition['theme file'] = 'theme.inc';
      $bs_accordion_style->options['grouping'] = array();
      $bs_accordion_style->row_plugin = $view->style_plugin->row_plugin;
      $bs_accordion_style->definition['theme'] = 'views_bootstrap_accordion_plugin_style';
      $bs_accordion_style->view = $view->style_plugin->view;
      $bs_accordion_style->display = $view->style_plugin->display;
      $view->style_plugin = $bs_accordion_style;
      $view->style_options['title_field'] = 'title';
    }
  }
}

That almost works. It results in this error (1 per view result):

Recoverable fatal error: Object of class stdClass could not be converted to string in include() (line 21 of .../sites/all/modules/views_bootstrap/templates/accordion/views-bootstrap-accordion-plugin-style.tpl.php)

How can I correct this?

I have finally discovered a workaround, that may be the solution for some. I display the view using Panels. Using visibility rule, there is possibility to limit visibility of view based on number of results of that view. The steps could be:

Create a Contextual filter for your view for field Content:Nid. This should correspond to argument of your Ctools Page (so that path of a page is similar to something/%nid). You may need to add Relationship, if you want to display content, that is related to the content with nid.
Create a Context display for your view.
Create a 2 separate displays (Content panes) for your view - for one result and multiple results.
Create a new Relationship based on your view for your Panel (at the Contexts tab).
Add both your content panes to the panel.
Add Visibility rules to both panes. You should choose PHP-based filtering and enter something like:

if (count($contexts['relationship_view_from_argument:name-of-your-view-ctools_context_1_1']->output['rows'])==1) {
return TRUE;
}


Display a code snippet based on a taxonomy term I am trying to build a node file for a content type in Drupal 7.59. I have for example a field for a taxonomy term. There is only 2 terms Expert and Guest.
I want to display something on the node if this term reference choice is marked as Expert.

So I need to figure out how to write a line that checks for the value of the taxonomy term and then if it matches expert then it displays something but if it is guest it doesn't.

The field I have setup in my content type is:

Name of field: author type
Machine Name: field_author_type
Field Type: Term reference

The root taxonomy term is Author Type and the two terms are Expert and Guest.
Does anyone know how to accomplish this? I hovered over the taxonomy term I wanted to reference and it was /taxonomy/term/57/ Is 57 the actual number or do I find it elsewhere?

So far I have this which is not much and it doesn't work so it is wrong. I am really sucky at php.

<?php if ($content['field_authors_type']->taxonomy[57]): ?>
    Put what you want to display here
<?php endif; ?>

The value you're looking for would be stored like so

$content["field_authors_type"]["#items"][0]["tid"]

You could, if you wanted to be tidier, put this if statement in your theme's template.php in a template_preprocess_node or template_preprocess_page function (more on that here: https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x).

You would store your boolean value $variables['author_is_expert'] and then in your node.tpl.php, you can just use if ($author_is_expert)


Drupal 7 and taxonomy views - sorting by number in URLs How can I tell Drupal 7 that 99 should go AFTER 100 when sorting items (descending) according to a number in URL or in Title?

I have this taxonomy view for magazine articles. Published issues range from 90 to 120, for now. Sorted ascending, the list goes from 100 to 120 and then 90, 91, and so on. Descending, I get 99, 98, 97.... 91, 90, 120, 119 and so on.

Sorting by posting date is not an option, since we're moving to the new Drupal site lots of old content and new issues will be loaded before very old ones.

Your data is being sorted alphabetically rather than numerically.

The simplest solution would be to store the 'Issue numbers' as an integer rather than as a sting.  Views will sort numeric fields the way you're looking to sort them without any fuss.

This obviously won't work if you ever have issue numbers that contain anything but but numbers.


How can I enter a custom maintenance mode message for a non-English D8 site? I am playing around with a D8 site (8.0.0-beta6) and having trouble locating where some of the controls have gone. During the initial installation procedure I selected a non-English localization (Turkish). Subsequently putting the site into maintenance mode does indeed show the Turkish localized default maintenance message.

The trouble is I want a custom message. Entering one in the box on the maintenance page (I'm viewing the Administrator site using the same default locale) has no effect on the message displayed. Apparently this message changes the English only because if I add /en to by site URL I get the English maintenance mode page and header, but with my custom Turkish message below it.

Where does one change custom localized maintenance mode messages?

This function should have worked as expected. There is not some feature somewhere else or another way this should have been done. The result described is the consequence of this bug in the Drupal 8 core. As of this writing a patch has been proposed but not settled on. Such are the consequences of playing around with beta releases!

In the mean time the only way to may a D8 site behave is to hack it using one of the following methods:

Manually implement one of the patches described in that issue.
Manually override the core template file (core\modules\system\templates\maintenance-page.html.twig).
Use the Interface Translation module to access the internal localization strings. Override the default maintenance mode string for the target language.

Eventually when that issue is closed and another release cycle happens it should be fixed and providing a custom message from the Admin page will work again as expected.


How to use Views to make a Block that displays a field from the author's profile? using Drupal 7.

I have added a field in the user account settings called "author summary" (field_author_summary)

When a user is editing their profile, they can enter a brief description of themselves into this field.

Now, the goal is to display this information as a block, directly under the content they are the author of.

I can't figure out the proper contextual filters and/or relationships.

Any ideas?

Thanks!\

I assumed that you have create a block view. (In case if you want to know how to create, check the revisions of this answer)

Add Author Relationship

Add Fitter Criteria : User: Current with author relationship

select Is the logged in User - yes. Click on Apply.

It pulls a field from a node (the author of the current node) and display it in a block


custom fivestar icons I am having an issue loading my custom icons for the Fivestar module; Here are the steps I am taking, I am hoping someone can point out what I am missing.

first I hook into the fivestar widget to add in my new theme.

function my_module_fivestar_widgets() {
  $module_path = drupal_get_path('module', 'my_module');
  $widgets = array(
    $module_path . '/images/bonestars/bonestar.css' => 'bone_stars',
  );

   return $widgets;
}

This bonestar.css is pretty much a complete copy of the basic theme. Inside the css I link to my images instead of basic, so everything so far seems safe.

Next I go to the views configuration and click under Fields, Field: Rating. I click the SHOWSTAR DISPLAY OPTIONS to select which star I want to use. I see my custom stars visually:

I select it and save it and apply to all.

So then I go to my view to check if the new star theme has been loaded, but it now loads basic. So I clear the cache as well, nothing.

I am obviously loading the images or something, but it doesn't translate to my view. What am I missing? I also test this on views, blocks, etc it never loads it on the actual site. Only in the settings as seen above.

When I added my custom fivestar, I saw a similar issue, you do not have your CSS listed  but check to see if in the css you copied, check to see if all instances of the .fivestar- class has your custom star name after the hyphen.  i.e. .fivestar-bone_stars
Also of note, I answered this on another person's post here is a really nice tutorial on adding custom stars using file_scan_directory so that all you have to do is add a new folder and update the css and the hook will automatically pick it up.

Custom fivestar widget does not display custom icons


How can I add folders to my template directory and have Twig find them? I was listening to a Drupal Developer on youtube and one of the suggestions he has, is that when you go into a template folder, create some subdirectories for easier management, like this:

Templates
->Blocks
->Fields
 ->YourField.html.twig
->Nodes

So I want to do the same thing for my template folder, however when I do that, I get this error:

  Twig\Error\LoaderError: Template "modules/custom/task/templates/field--expire-date.html.twig" is not defined.

Now granted, I learned with Drupal that Twig + Theming Templates is different than Twig + Module Templates. I am using my own module.

Is there a way for me to tell Twig there is another subdirectory (Ex: Fields Folder), so it can find the code?

In your "task" module you must have a task_theme function where you've defined your templates. In there you'll need to update with your new paths too. e.g.

This

'template' => "field--expire-date.html.twig"

becomes:

'template' => "fields/field--expire-date.html.twig"


Override core Js file Working on my theme
I need to override a core Js file ..\core\modules\contextual\js\contextual.js
My code from theme.info
libraries-override:
  contextual/drupal.contextual-links:
    js:
      js/contextual.js: js/override/contextual.js

The problem is that the loading order of this component js files did change after the override which cause script errors :

So how can override file js core and still same order file?

Thanks can be done with with the hook_js_alter function

    function hook_js_alter(&$javascript) {
    $javascript['js/contextual.js']['data'] = drupal_get_path('theme', 'THEMENAME') . 'js/override/contextual.js';
    }


How to change views pager with View All links I am using the full pager in views module. I am displaying 40 items per page. The full pager display links like this

1 2 3 4 5 next last
I want to change it to this

View All 1 2 3 4

How will I do this? Any idea about this?

The only way I can think of you achieving such a thing would be to create another display page in addition to the display page which already has a pager. And using html/CSS add a link to the footer of the views with pager called View all linking to the display page you created that shows all content.


Creating a Views Search Page AND Block (not just a search block and results page) I have a site with a box on the home page (only) that has a search box. I also have a 'search' link available on all pages of the site, in the navigation. The search link takes the user to a page called 'Search' where the search box appears (again) and allows them to do searches there. I've built the search for that page so the search box appears and the results display only after the user types in a search.

The main question I have is this: how do I create a block for the home page that ONLY displays the search box (results of such search still showing on the results page I've created in Views)?

I know how to expose the View as a block but this doesn't solve my issue because I want the search box itself to still show on the results page too.

Consider using a block with php filter to display the exposed search box in a block.

Example below is based on Search API with blocks exposed. I'm taking a guess you're using Search API based on your description.

For Search API:

$view = views_get_view('your_view_here');
$view->set_display('Page');
$view->init_handlers();
$exposed_form = $view->display_handler->get_plugin('exposed_form');
print $exposed_form->render_exposed_form(true);

For Drupal's Core Search:

$block = module_invoke('search', 'block_view');
print render($block['content']);


Getting session variable in view contextual filter drupal 8 I am new to Drupal 8. I get group_id in session variable just like that $_SESSION['groupbysession']['group_id'] = $path[2];. now i want to get that session variable in view Contextual filters.I have no idea how to do this. I also use view extra module for this but doesn't work for me.Thanks in advance

You'll need to create a custom module and pass the value Group ID value using hook_views_pre_view

Example:

/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') { // target a specific view
    // if you want you could make it even more specific by adding ex: "&& $display_id == 'block_1')"
    $group_id = $_SESSION['groupbysession']['group_id'];
    $args[0] = $group_id; // set argument
  }
}


How can I override template_preprocess_file_link function? I want to print file size near file link in file-link.html.twig template.
To do so I need something like {{ filesize }} variable avaiable in template.

I tried to override template_preprocess_file_link() with an override function in mytheme.theme like mytheme_preprocess_file_link() but I get this error:

The website encountered an unexpected error. Please try again later.
Error: Class 'File' not found in tofacile_preprocess_file_link() (line 12 of themes/custom/mytheme/mytheme.theme)

It seems like a class missing... should I add "use Drupal\File\SomethingXXX" declaration??

Thanks

This is my code:

<?php

/**
 * @file
 * Functions to support theming in the Tofacile theme.
 */

function tofacile_preprocess_file_link(&$variables){
  $file = $variables['file'];
  $options = [];
  $file_entity = $file instanceof File ? $file : File::load($file->fid);

  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $url = file_create_url($file_entity
    ->getFileUri());
  $variables['#cache']['contexts'][] = 'url.site';
  $mime_type = $file
    ->getMimeType();

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options['attributes']['type'] = $mime_type . '; length=' . $file
      ->getSize();

  // Use the description as the link text if available.
  if (empty($variables['description'])) {
    $link_text = $file_entity
      ->getFilename();
  }
  else {
    $link_text = $variables['description'];
    $options['attributes']['title'] = $file_entity
      ->getFilename();
  }

  // Classes to add to the file field for icons.
  $classes = [
    'file',
    // Add a specific class for each and every mime type.
    'file--mime-' . strtr($mime_type, [
      '/' => '-',
      '.' => '-',
    ]),
    // Add a more general class for groups of well known MIME types.
    'file--' . file_icon_class($mime_type),
  ];

  // Set file classes to the options array.
  $variables['attributes'] = new Attribute($variables['attributes']);
  $variables['attributes']
    ->addClass($classes);
  $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));
}

Yes, seems you need to add:

use Drupal\file\Entity\File;

to the begin of your mytheme.theme file. You can also do something like:

$file_entity = $file instanceof \Drupal\file\Entity\File ? $file :
\Drupal\file\Entity\File::load($file->fid);

And you will have the same problem with Attribute and Url. You need to import the classes with the complet namespace in your file. https://secure.php.net/manual/en/language.namespaces.importing.php


I lost permission to access admin/content for user 1 I uninstalled several contributed modules of my site and suddenly I lost the permission to access admin/content for user 1.

As far as I know this is not related to any contributed module.

When I try to access this page admin/content I get a message "You are not authorized to visit this page.".

How can I trace this? I run cron, clear caches and even run sites/all/modules/registry_rebuild/registry_rebuild.php to rebuild registry.

Is Drupal7 using the Commerce Kickstart distribution (I disabled all commerce modules)

Update1: I just rebuild permission at: admin/reports/status/rebuild but problem persit.

Also there are these error messages:

Notice: Trying to get property of non-object in user_access() (line 808 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 820 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 821 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 827 of /home/temporal-13/www/modules/user/user.module).
Notice: Trying to get property of non-object in user_access() (line 830 of /home/temporal-13/www/modules/user/user.module).

Solved: the problem was the module: admin_views I just disabled it and the problem was gone.


What hook to alter the result of a view? In a custom module, I have a custom entity for which a view shows the following values:

Contact is the ID of another entity (Person) containing some fields, such as Email. Adresse courriel is a Custom text field defined in the view.

What hook should I use to achieve the following task?

Query the Person entity with the Contact value to retrieve the Email field value
Update Adresse courriel in the view output

1- Firstly you need to add a relationship to the Person entity to have the fields available.

2- then use hook_views_query_alter() to change the fields values.


How do I create a link? Say I am extending The blockBase class to create a custom block, and I am implementing the blockBuild method to create some markup for my block. Something like this:

 class YourModuleBlock extends BlockBase {

   /**
     * Implements \Drupal\block\BlockBase::blockBuild().
     */
     public function build() {
      return array(
        '#markup' => 'This is a block!',
      );
     }
   }

If I wanted to provide a link in this markup, in D7 I would have used the l function, but this is no longer available (see here). So, I need to make available the new D8 method for generating links. I could just use an <a> tag, but this was never best practice in D7.

So, what is the right method to use for creating links and how do I make it available to my function?

\Drupal::l is deprecated.
Maybe this case will be useful for somebody

  use Drupal\Core\Url;
  use Drupal\Core\Link;
  $url = Url::fromRoute('entity.node.edit_form', array('node' => NID));
  $project_link = Link::fromTextAndUrl(t('Open Project'), $url);
  $project_link = $project_link->toRenderable();
  // If you need some attributes.
  $project_link['#attributes'] = array('class' => array('button', 'button-action', 'button--primary', 'button--small'));
  print render($project_link);


Creating a system account used by a module: Is setting the password with drupal_random_bytes() too excessive, or is there a better method? I am planning to create a module that would use a system account similar to the Community user seen on Stack Exchange sites. As the system account would have permissions that normal users don't have, I would like to avoid somebody logs in with that account, and get permissions that a site maintainer would have.

Is using drupal_random_bytes() to create a password a good method, or is it too excessive, and I should use a different method? In any case, I was thinking of periodically changing the password; I guess this means I could use a faster way to generate the password, as long as the password is still random, and with at least X characters.

As you probably know, another option is to use user_password() to get the password string.

When Drupal hashes it, e.g during user_save(), with user_hash_password(), drupal_random_bytes() is used as part of the _password_generate_salt() calculation.

Just thought it worth mentioning.

You may also be interested in preventing login through the UI by that account with a user_login validation handler.


Allow users to sort stories by date or content type What is the easiest way to allow users to sort a story view by content type or date? Is there a module that would allow you to do so? The idea would be to have a drop down list containing the different content types and a calendar widget (or perhaps also drop down lists) which would allow users to determine a date range.

If this can only be achieved programmatically, no need to provide much detail -- I suspect it would be a rather long explanation and don't want to take that much of anyone's time.

i think you might be confusedly mixing a few different concepts?

"story" is one of the default/example content types distributed with Drupal and is nothing special, ie. not quite sure what you mean by "story view".

I assume from the way that you're phrasing your question that you're new to Drupal, have you discovered Views and CCK?

exposing filters is relatively easy in Views 2 and 3, but exposing sort options in general is more difficult in Views 2 (you'll probably need some basic PHP knowledge to achieve this) but can be done through the UI in Views 3.

popup calendar widgets for date fields exist in the Date module once you install the jQuery UI module.

if you want a calendar widget that is "inline" (doesn't popup from a dropdown menu) then you'll likely have to do a little coding, but it isn't very hard as jquery UI provides a good API for inserting calendars into your page.


How do I fix the errors I get after removing the comment field from a content type? After I removed the comment field from the user interface, and uninstalled the Comments module, I can't open any Article node.

In the Drupal log, I find this message.

  InvalidArgumentException: Field comment is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 580 of core/lib/Drupal/Core/Entity/ContentEntityBase.php).
  Drupal\Core\Entity\ContentEntityBase->get("comment") (Line: 17)
  gavias_sanbro_preprocess_node(Array, "node", Array) (Line: 287)
  Drupal\Core\Theme\ThemeManager->render("node", Array) (Line: 437)
  Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
  Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
  Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent{closure}() (Line: 582)
  Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
  Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object,
  Object) (Line: 117)
  Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
  Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, "kernel.view", Object)
  call_user_func(Array, Object, "kernel.view", Object) (Line: 111)
  Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch("kernel.view", Object) (Line: 156)
  Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
  Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
  Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
  Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
  Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
  Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
  Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
  Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 657)
  Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

How can I fix this issue?

Given your error stacktrace:

Check function gavias_sanbro_preprocess_node() (Line: 287 in your gavias_sanbro.theme theme file).

This preprocessing function obviously tries to access the comment field without checking, whether it exists. As you uninstalled the field, it is causing your exception.

You may comment out, remove, or alter the code accordingly.


Is there a 'text or user reference' module? Currently, I'm planning on using a text field for full names (added fields field_profile_full_name and field_profile_partner) on user entities, so that one user can link to another. However, I might not get matching entries in autocomplete (which rules out user references). What I want is this:

A match to text entered in field_profile_partner is found in field_profile_full_name: return/use the text in field_profile_full_name.
A match is not found: use the text the user entered in field_profile_partner, without creating a new user.

I know that a 'text or node reference' module exists for Drupal 6 and 7, but I've been unable to find a module that does the same thing for user references. Does such a module exist or will I have to clone and adapt 'text or node reference'? Can I configure entityreference to give me this functionality?

Note: I know that I could write a custom form and autocomplete page to handle this, but the functionality needs to be on the user account/registration form. If this can be done in hook_form_alter, please provide it as I've had no luck getting that hook to work whenever I implement it on anything.

The Entity reference module will relate any Drupal entities. These include:

Nodes
Users
Taxonomy Terms

So should be perfect for your needs.


Webform submission tokens in emails I am trying to print the webform submission label and value from tokens in confirmation email. The problem is that the label of the form element is not appearing, only the value.
Tried with:

[webform_submission:values:email]
[webform_submission:values:email:withlabel]
[webform_submission:values:format:html]

When I print all the elements with [webform_submission:values] , I am able to see also the labels, but the formatting is not so good, so I want to print the values line by line.

My solution is simply manually typing out relevant labels for each line.
I just use "Custom body"

For example:

Name: [webform_submission:values:navn:value]

Email: [webform_submission:values:email:value]

Date: [current-date:html_date]

Unless you change your form often i find that to be the easiest way to format it exactly as you want it.


How do I can change the default description of elements? I'm trying to change the default descriptions in different pages like (add users). I tried devel themer to find out where there descriptions are came from but it showed nothing. for example look at this picture (add user) :

how do I can change the texts displayed by red line?

Update

I tested this code in template.php

function MYTHEME_form_alter(&$form, &$form_state, $form_id){
if($form_id == "user_register_form"){
    $form['account']['name'] = array(
            '#title' => t('New username'),
            '#description' => t('New description'),
    );
    }
}

you can find the descriptions at user.module under user directory (in modules directory)

you can find those descriptions under user_account_form function

Ex, E-mail address field description below.

$form['account']['mail'] = array(
    '#type' => 'textfield',
    '#title' => t('E-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('A valid e-mail address. All e-mails from the system will be sent to this address. The e-mail address is not made public and will only be used if you wish to receive a new password or wish to receive certain news or notifications by e-mail.'),
    '#required' => TRUE,
    '#default_value' => (!$register ? $account->mail : ''),
  );

But it's better to  Use hook_form_alter to achieve it


How do I use a term as contextual filter correctly? I'm using Drupal 8.
I have a book content type that uses a vocabulary called "book type" as an entity reference field.
I have basic page content type which also uses the the vocabulary "book type" as an entity reference field.
So both of the content types are using the same vocabulary.
What I'm trying to do is filter the books by the chosen book type on the basic page content type, but I just can't figure it out. Here's what I tried.

This is the book content type, which uses the vocabulary "book type" in an entity reference field

This is the basic page content type which also use the vocabulary "book type" in an entity reference field

This is my second try with the help of prkos:

You don't need Relationships for matching through ER fields, IDs are enough so it's enough to use the ER field Contextual matching directly.
Instead of the ID Contextual filter add the Contextual filter for the ER field and configure it:
When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms by vocabulary
[Your vocabulary]
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[Your vocabulary]
Set other options according to your needs.
You can test it by entering a Taxonomy ID into the Views Preview field, you should get only the nodes that reference that term.
When you place the Block in a theme region also configure the Contextual option, it won't work without it.


Import image using feeds and image path? With Drupal 7, I am using feeds to import an XML file. That file has a relative image path I can import, but not the image itself.

How can I save the image to the node itself instead of saving the image path?

I believe it should work automatically, but you need to use a valid path schema, for example: public://images/myimage.jpg. Otherwise Feeds needs to know the absolute path to these images. If needed, use Feeds Tamper to correct image paths.


Input field not submitted in form when added through JS I have a form that is processed first by an external service through JS and afterwards adds an input field to the form:

$('#my-form').once('submit').submit(function(e) {
  // some processing
...
  form.append($('<input type="hidden" name="token" />').attr('value', token.id));
  form.unbind();
  form.submit();
});

The field is added and also has the correct value. But when it is submitted the field is not present in neither my
 public function validateForm(array &$form, FormStateInterface $form_state) nor in public function submitForm(array &$form, FormStateInterface $form_state).

I already tried using a textfield instead of type hidden, and hide it with css, but same result

You can add a hidden field in buildForm() like below

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
  :
  :
  $form['token'] = [
    '#type' => 'hidden',
    '#default_value' => ''
  ];
  :
  :
}

or, if you're not building the form yourself, i.e. you're altering an already existing form, you can add the hidden field via hook_form_alter or hook_form_FORM_ID_alter.

Then update value of it using JS if needed


Clean URLs cannot be enabled I'm stuck on this issue, I've followed a variety of idea and tutorials trying to fix the issue, most which follow a similar path to this (http://stevenmcmurry.com/howto/2014_07/enabling-clean-urls-drupal-ubuntu-1404-lts). I'm running off of Apache2 on Ubuntu.

Currently my 000-default.conf looks like this:

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port t$
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        <Directory /var/www/html/>
    AllowOverride All
    Order Allow,Deny
    Allow from all
</Directory>
# error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

</VirtualHost>

But I'm still running into the issue of clean URL's not allowed to be enabled. The odd thing I'm trying to work on is at the moment, I can't see the .htaccess in the drupal site root.

Has anyone run across a situation like this?

Thanks!

Mostly .htaccess is hidden While viewing cpanel click to show hidden files also, Else download .htaccess file and put it on root directory


Advanced Aggregation: Should I disable core's aggregation? I know that AdvAgg's bundler will, by default, disable core's grouping logic, but I'm unclear as to whether core's aggregation should be enabled or disabled (at admin/config/development/performance) for AdvAgg to be able to aggregate files in the first place.

Basically, I can't tell if AdvAgg is actually aggregating things itself (and thus core should probably be disabled under admin/config/development/performance), or if AdvAgg is taking core's aggregated files and only handling the bundling aspect of aggregation, in which case core's aggregation would need to be enabled. I suspect the former is the case, but I can find no explicit information on this.

Can anyone tell me what the general best practice here is?

Should I disable core's aggregation?

No; AdvAgg uses the core aggregation setting as part of its own on/off switch. If core aggregation is disabled, AdvAgg aggregation is implicitly disabled.

In fact if you do disable it, you get this helpful error in the status report:

You can tell whether or not AdvAgg is producing your files from the path - it will contain /advagg_(css|js)/.


How to access current langcode in theme? I use Integrity theme and want to make the slider images i18n aware.

I want to get the current langcode in the

function _integrity_get_home_block_contents

Previously it worked like this:

   global $language;
   $lang_id = $language->language;

What do I do now?

Here's how to do the same in Drupal 8:

$language = \Drupal::languageManager()->getCurrentLanguage();
// Will return "en".
$shortcode = $language->getId());
// Will return "English".
$language_name = $language->getName();

Read more here.


Farbtastic color picker to change the background color of text field input? I have taken this JS from the field_example module. I am attaching it to a form textfield element so that when a user brings focus to it the Farbtastic color picker widget pops up and allows the user to populate the field with the chosen hexadecimal color code. It works as expected. I was also expecting the background of the field to dynamically match the chosen color like this. However, it does not. In the linked example the text also turns black/white depending on the chosen color. This feature is also present in the color module.

I've tried adding to the code below, but nothing I try works. How can I adapt the JS below to achieve this? Thanks.

JS

/**
 * @file
 * Farbtastic color picker.
 */

/**
 * Show farbtastic colorpicker widget.
 */
(function ($) {
  Drupal.behaviors.my_color_picker = {
    attach: function(context) {

      $(".edit-my-color-picker").live("focus", function(event) {
        var edit_field = this;
        var picker = $(this).closest('div').parent().find(".my-color-picker");

        // Hide all color pickers except this one.
        $(".my-color-picker").hide();
        $(picker).show();
        $.farbtastic(picker, function(color) {
          edit_field.value = color;
        }).setColor(edit_field.value);
      });

    }
  }
})(jQuery);

Form element

'color' => array(
  '#type' => 'textfield',
  '#title' => t('Color'),
  '#size' => 8,
  '#suffix' => '

',
  '#attributes' => array(
    'class' => array(
      'edit-my-color-picker',
    ),
  ),
  '#attached' => array(
    'library' => array(
      array(
        'system',
        'farbtastic',
      ),
    ),
    'js' => array(
      drupal_get_path('module', 'my_module ') . '/color-picker.js',
    ),
  ),
),

Something like this?

/**
 * Show farbtastic colorpicker widget.
 */
(function ($) {
  Drupal.behaviors.my_color_picker = {
    attach: function(context) {

      $(".edit-my-color-picker", context).on("focus", function(event) {
        var edit_field = $(this);
        var picker = edit_field.closest('div').parent().find(".my-color-picker");

        // Hide all color pickers except this one.
        $(".my-color-picker").hide();
        $(picker).show();
        $.farbtastic(picker, function(color) {
          edit_field.val(color);
          // background color, may need to add # to color.
          $(edit_field).css("background-color", color);
        }).setColor(edit_field.value);
      });

    }
  }
})(jQuery);

Notice I added 'context' to the original selector and changed 'live' to 'on'. Live function is deprecated as of jquery 1.7.
I also changed it so the edit_field variable stores the jquery object.

Drupal does already have a couple of color fields, on of which is HERE


How do I save a managed_file to a user profile in a hook_submit I'm trying to save a file that the user has uploaded using my form.

My form:

$form['fifth']['field_cv'] = array(
        '#title' => t('CV'),
        '#type' => 'managed_file',
        '#size' => 19,
        '#upload_location' => 'public://',
    );

My validator using hook_validate:

$file = file_load($form_state['values']['fifth']['field_cv']);
// Change status to permanent.
if($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'popover', 'document', $file->fid);
}
else {
    form_set_error('CV', t('Er is geen cv geüpload'));
}

So now in hook_submit how do I add this to the user? Do I need to create an extra database field for this? And should I save only the $fid ( file id ) in this field?

OR

Is there a better way so drupal takes care of this and also revisions of this field are saved?

building this in D7

I'm not sure how your collecting this CV (apart of registration process, on your own custom page, apart of the user profile page... whatever).

I would add a field to User Accounts at /admin/config/people/accounts/fields, or maybe install the Profile2 module for D7 if you have alot of types of Users.

After you call file_save($file) if you use the Devel module you'll see that $file should have a new value fid so you can then load a user account (or Profile2 profile) and give the CV $file->fid as the File field value.


How do I iterate through views result with pagination in a template file? I am using Drupal 7.8, built a custom cck type, populated it with content, and created a view with full pager of 10 items per page.

I'm modifying the views theme Row Style Output - views-view-fields.tpl.php to do something, but every-time I try to collect the entire views result set, I only get the first 10.

ie.
foreach($view->result as $id => $data) {
   // track $data->field
}

How do I bypass the pagination limits so that in my views template I have access to all the results (which is over 20+)?

Here is an example layout of my cck type -

CCK TYPE: Videos; CCK FIELDs: title, body, url, date_recorded

date_recorded is a custom date format which only has Month, Year.

The view filters and groups these fields by date_recorded, and uses full pager for 10 items like so :

Feb 2012
- Video 1
- Video 2

Dec 2011
- Video 3
- VIdeo 4

...

PS - This is the 2nd part of a question that began here - Alternative ways to group results of a view by CCK field?

Set up a second display on your view or a new view that has no pagination or limit on the number of items displayed and use views_get_view_result to retrieve the object.


Setup voting/rating on content to require a "reason" field Is there a way to setup content voting/rating on Drupal 7 in such way that the user must provide a reason for their vote/rating?

There are probably many different ways to create a feature where a comment is required along with voting. I guess it all depends on which method you're using for the voting part.

You could use the Fivestar module to Set up fivestar widget for User/Author rating with comment on any content type. 7X. Here you use allow for rating to be available on each new comment. You can use the usual comment field permissions to require input on both the voting field and the comment text area.

There are more ways to create something similar with the Fivestar module, it all depends on your particular needs.

Another module that can be used for voting is Flag. You can add Fields to Flags just like you can on a Content type: Attaching fields to flags (Flag 3.x). This way Flags are used for the voting part, and the Text area field created on the Flag is used to type in the reason. You can configure both the Flag and the Text area field on the Flag to be required based on Roles and Permissions.

Basically it's all about attaching a Text field to your voting widget and setting up permissions to make it required so the form can't be saved if it's empty.


Programatically create 'Send this user a a private message link' for user pages I know that this question had been asked several times, but it seems like all existing answers only apply to ealier versions of Privatemsg module. I am running 7.x-2.x-dev and I would like to programatically render the "Send this user a private message" link. The PHP code is supposed to be the $block['content'] of a programatically created block that will be displayed on user pages.

Somebody suggested to useif ($account = menu_get_object('user') ) {
      if ($url = privatemsg_get_link(array($account))) {
        $block['content'] = l(t('Send this user a private message'), $url, array('query' => drupal_get_destination()));
      }
}but this is doing absolutely nothing.

I also want that the link is only displayed if the viewed user has enabled the "Enable private messages" option in his/her account settings and if the viewing user has permission to send messages. Any ideas how to achieve this?

Hope this will help you,

In Drupal 7, you can use privatemsg_get_link.

privatemsg_get_link - Returns a link to send message form for a specific users.

  if ($enabled_private_messages) {//check user private message settings
    if ($account = menu_get_object('user')) {// Get user object. You can also use user_load to get user object.
      if (is_object($account) && privatemsg_user_access('write privatemsg')) {
        if ($url = privatemsg_get_link(array($account))) {
          return l(t('contact user'), $url, array('query' => drupal_get_destination()));
        }
      }
    }
  }


Published checkbox field displaying in form footer instead of node options In d8.4:

The Published checkbox field, which is part of the publishing options set of fields, is displaying at the bottom of the node edit form instead of with the other publishing options fields.

See screenshot:

I've tried reposition using the Field Group module and also unsetting the form with unset($form['options']['status']); and other variations with no success.

All I'd like is for that field to be included in the promotion options fieldset with the rest of the options.

The field is displaying in div.layout-region-node-footer - I' can't track down where that themeing is taking place.

Any help would be appreciated.

NodeForm.php defaults the position to the 'footer' group:

$form['status']['#group'] = 'footer';

In a custom module or your theme, this can be set to the 'main' section:

/*
* Implements hook_form_BASE_FORM_ID_alter()
* @param     Array $form, Object $form_state, Array $form_id
* @return    Array $form
*/
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state,  $form_id) {

    // NodeForm.php defaults this to 'footer'.
    // Set to 'main' so we can reposition it in 'Manage form display'.
    $form['status']['#group'] = 'main';

  return $form;
}

After this, it can be repositioned in 'Manage form display'.


How can I extract info from the user_profile array So I know that the $user_profile is basically an array. And when I use the DSM command with devel I saw all that info in the array, but how on earth do I begin extracting and displaying data from that?

I'm still not too keen on php, trying to learn as I go and on the side. I understand the concepts of an array and how to get top level stuff. But for those items embedded in other arrays embedded in yet more arrays, I'm not sure how to get to those and display them.

For a simple instance I just want to take the username of the profile currently being views and display it on a custom user-profile.tpl page. And I see it with devel, but I don't know how to get it.

In drupal 7 on the user-profile.tpl.php to which you refer the whole user object is loaded so you can output the different pieces you see in devel by doing this (a modification of the default user-profile.tpl.php you've copied to your theme):

Default:

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>

Modified:

<div class="profile"<?php print $attributes; ?>>
  <?php print render($user->name); ?>
  <?php print render($user->signature); ?>
  <?php print render($user->timezone); ?>
  //and so on...

On Drupal 6 the only difference is

<?php print $user->name; ?>
//dropping the render wrapper (which is good practice in D7 but is not used in 6)

As the questioner mentioned in the comments the above will display the currently logged in user's info.  To get the info of the user's page you are visiting (ex. YOUR_BASE_URL/user/2) you can do this (this will also work with aliased user pages):

<?php
   /*call this ($user_page_object) whatever you want but it is ill advised to
     call it $user as that will conflict with the $user object for the currently
     logged in user*/
   $user_page_object = user_load(arg(1));
?>
<div class="profile"<?php print $attributes; ?>>
   <?php print render($user_page_object->name); ?>
   <?php print render($user_page_object->signature); ?>
   <?php print render($user_page_object->timezone); ?>
   //and so on...

And to access additional fields you may have added you can drill into the $user_profile array which contains those fields. (Which would've been added here admin/config/people/accounts/fields).

I recommend using the devel module to kpr or dpm (I prefer kpr) to look into those two vars, ie:

<?php
kpr($user_page_object);
kpr($user_profile);
?>


Configure visibility of block based on URL parameters Is it possible to display a block only on a URL without any parameters? E.g. on:

my.site.org/search

but not on:

my.site.org/search?q=term

When I configure a block ('/admin/structure/block/manage/myblock') and set visibility for pages at: '/search' (see the picture), then the block is displayed on the page '/search?q=term' as well.

You can use condition_query it will give you an extra box where you can put query parameters like q=term


Show all terms of a vocaboulary I have this function that I used in a similar situation (Drupal show all terms of different vocabulary) that prints the terms of a node with a corresponding parent (if applicable). In my template.php file:

function theme479_print_terms($node, $vid = NULL, $ordered_list = TRUE) {
     $vocabularies = taxonomy_get_vocabularies();
     if ($ordered_list) $output .= '
'; //checks to see if you want an ordered list
     if ($vid) { //checks to see if you've passed a number with vid, prints just that vid
        $output = '
';
        foreach($vocabularies as $vocabulary) {
         if ($vocabulary->vid == $vid) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= 'vid . '">';
             if ($ordered_list) $output .= '
vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = 'tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '
';
             $output .= '';
           }
         }
       }
     }
     else {
       $output = '
';
       foreach($vocabularies as $vocabulary) {
         if ($vocabularies) {
           $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
           if ($terms) {
             $links = array();
             $output .= '
vid . '">';
             if ($ordered_list) $output .= '
vid . '">' . $vocabulary->name . ': ';
             foreach ($terms as $term) {
              // Check for terms parent, if found assign to $parent variable
              if ($get_parents = taxonomy_get_parents($term->tid, 'tid')) {
                foreach ($get_parents as $parents) {
                  $parent = $parents->name . '/';
                }
              }
               $links[] = 'tid . '">' . l($parent . $term->name, taxonomy_term_path($term), array('rel' => 'tag', 'title' => strip_tags($term->description))) .'';
             }
             $output .= implode(', ', $links);
             if ($ordered_list) $output .= '
';
             $output .= '
';
           }
         }
       }
     }
     if ($ordered_list) $output .= '
';
     $output .= '
';
     return $output;
}

I have this vocabulary structure:

Foods

Fruits
Fruit_with_seeds

This function only shows:

Fruits

Fruit_with_seeds

Is it possible to show the entire hierarchy of a vocabulary?

I'm not sure what exactly you are looking for. The taxonomy terms for a node are normally nested inside $node->taxonomy. If you want all the terms "above" the terms inside the node, you should take a look at taxonomy_get_tree().
To the code above: I would urge you to seperate the tree-logic from the output; first create the array, then render the output.


Field:REWRITE , Contextual filters Views 3 i am pretty new to drupal 7 , and i have managed to create a view (conferences_details) with a contextual filter Content:Nid, the link to the view is now conference_details/%
How then do i include node id to the title field in the page that links to the respective
conference_details/% view page.?
I have tried to REWRITE output field:Title as link using:
conference_details/%nid
conference_details/%Nid
conference_details/[%nid]
conference_details/[Nid]
conference_details/[nid]
with no luck. Can you please help. on how to do this . what i m trying to do

You should call Content: Nid (Nid) field above the conference_details field,
as showing below

Than only [nid] will be available for REPLACEMENT PATTERNS for Rewrite the output of this field as Output this field as a link

edit the Content: Nid (Nid) configuration


How to hook theme of the main system menu in drupal 7 to display only some of the elements? I want to modify the main system menu in Drupal 7. Actually I want to display only some specific elements of the menu and hide some other specific elements, in a given case (which I will implement by a if or switch statement in a function).

What is the easiest way to do this ? And how to do it ? Can you give me an example ?

I have read that using hook_theme or hook_menu can be done, but I have no idea how to do this.

There are different levels to alter the system menu. If you want to add a top level container like drupal commerce does for the admin shop section, you need to add a menu item with hook menu like this:

// Top level "Store" container.
$items['admin/commerce'] = array(
  'title' => 'Store',
  'description' => 'Administer your store.',
  'page callback' => 'system_admin_menu_block_page',
  'access arguments' => array('access administration pages'),
  'file path' => drupal_get_path('module', 'system'),
  'file' => 'system.admin.inc',
  'weight' => -7,
);

system_admin_menu_block_page is what will do the job, of making it a part of the system menu.

If you want to make the menu appear under one of the sections, like configuration etc, you just need to adjust your path in hook_menu, fx

$items['admin/config/section'] = array(...);

Every time you want to create a section that should hold other menu items, simply add

'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
'file' => 'system.admin.inc',
'file path' => drupal_get_path('module', 'system'),

When creating a menu item in a section, just create a normal menu item.

Update
Since the menu structure is cached, you can't alter the menu by a per user scenario. But there are still some methods available.

Since menus are only displayed if the user has access, you could create a custom access control function for all the menus and put your logic in there.
You could also try to do this in the theming layer, and alter the output to only display the desired menus. I haven't tried this in Drupal 7, but generally, altering the output of menus this way is hard, as the menu system is quite complex.

If you need to alter the menus, to change the access control, you should use hook_menu_alter.


Outputting a link as a button in node.tpl.php I am trying to rewrite the output of node.tpl.php.

I am using field link. I cannot figure out how to get the field to render as a button. I did find that the field is output as an array

I tried this but it just makes the link just a link to the page I am on:

<a class="btn btn-danger btn-lg" href="<?php print render ($content[field_amazon_link][LANGUAGE_NONE][0]['display_url']); ?>">Buy Now

The devel module gives me this info. Keep in mind php is my week area. This is my first time rewriting a node file as I used to have a helper and he has moved on.

field_amazon_link (Array, 1 element)

0 (Array, 5 elements)
    url (String, 142 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
    title (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
    attributes (Array, 1 element)
    html (Boolean) FALSE
    display_url (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...

And this is from the object devel tool
 field_amazon_link (Array, 1 element)

und (Array, 1 element)
    0 (Array, 5 elements)
        url (String, 142 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
        title (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re...
        attributes (Array, 1 element)
        html (Boolean) FALSE
        display_url (String, 83 characters ) https://www.amazon.com/gp/product/B00ZGUBN3C/re..

This is what ultimately worked for me. I don't really understand it completely, but if anyone can shed some light on why it worked, I would really like to know.

<a class="btn btn-danger btn-lg" target="_blank" href="<?php print $content['field_amazon_link']['#items']['0']['url']; ?>">Buy Now


Drupal Settings for PHPStorm I want to try to work with PHPStorm Debug.

I already installed debug on my Mac and changed the php.ini File. Furthermore, I installed the Debug Helper for Chrome and created a Projekt on PHPStorm.

If I start Debug, my PHPStorm will find a connection, but I had the Problem that PHPStorm always jumps into my "index.php" file no matter where I set my breakpoint.

I always have to push the "play" button, but again, it runs always through the "index.php" file and my site (I work with VM) will not load before I push "play".

What do I have to do so PHPStorm only jumps to my breakpoint?

Updated

Attached my PHPStorm Settings:

Relevant for PHPStorm 10:

Disable the Force break at the first line when a script is outside the project setting. This is accessible under Settings:

  Languages & Frameworks > PHP > Debug > Xdebug

I also disable Force break at the first line when no path mappings specified.


How to sign-in a user based on custom HTTP headers in Drupal 8? I would like to sign-in a user based on some custom headers in the HTTP Request.
Let's say i have an administrator account in Drupal with the login "admin".
If i send a request to Drupal with a custom header (X-USER-NAME: admin), i would like to be logged in with this user.
I tried to develop a custom authentication module to deal with this use-case like so :
  public function applies(Request $request) {
    $name = $request->headers->get('X-USER-NAME');

    return isset($name);
  }

  /**
   * @inheritDoc
   */
  public function authenticate(Request $request) {
    $name = $request->headers->get('X-USER-NAME');
    $user = user_load_by_name($name);

    return $user;
  }

I then alter system routes so i can access them with my new authentication method with an event subscriber :
class AdminRouteSubscriber extends \Drupal\Core\Routing\RouteSubscriberBase {

  /**
   * @inheritDoc
   */
  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      $path = $route->getPath();
      if (
        ($path == '/admin' || strpos($path, '/admin/') === 0)
      || ($path == '/node' || strpos($path, '/node/') === 0)
      || ($path == '/user' || strpos($path, '/user/') === 0)
      ) {
        $route->setOption('_auth', ['headers_auth', 'cookie']);
      }
    }
  }

}

I can now access a route to add a new content (let's say a new article), but when i submit the form to create this new content, i get the following error : "The form has become outdated. Press the back button, copy any unsaved work in the form, and then reload the page.".
With my new authentication method, no cookie is set in the answer. I guess that there is some kind of CSRF token verification when submitting the form.
I am a newbie in the Drupal world, am I on the good way or should I use a different approach ?
Thank you for your help :)

That sounds like a very insecure way of allowing admin access to your site.  Seems like a hacker just has to fake the header in the request to get access.
That said, you probably want to look at the various http authentication modules for Drupal 8 (E.g. google drupal 8 http authentication).  Some quick starter links about this in core are:
https://www.drupal.org/docs/8/core/modules/basic_auth/overview
https://www.drupal.org/docs/8/api/authentication-api/overview
As with most open source systems, the best way to figure out how to do something like this is to find code that does something similar and modify it to meet your needs.


Gift Wrap Option Ubercart 3 on Drupal 7 I would like to add a global gift wrap option to our checkout pane on Ubercart 3 (running on Drupal 7).

It is an option that can apply to any product and has a fixed price no matter how many products are purchased.

I do not want to add it as an attribute to individual products or product classes, but would like to add a simple yes/no radio button to all checkouts.  If yes is selected, the fixed amount is added to the order.

What is the simplest/best way to implement this?

Another approach would be to create a Gift Wrap product class.    Create a node of this custom type with the price of your gift wrap option.     Then create a view of the custom Gift Wrap entity and display it prominently as a block on your cart and checkout pages.


How do I display tokens in a block using PHP code? What is the way to use tokens in PHP code?
I need to show the user profile picture URL, but the following code doesn't work.

<?php
  echo "[current-user:picture:url]";
?>

How do I display tokens in a block? I am using Drupal 7.

I dont recommend using PHP in a block for  many reasons.

I would recommend you to use proper implementation of hook_block_view and hook_block_info to do you custom PHP codes in there.


EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile I was doing some work on my custom module which hooks into and modifies Drupal Commerce, and all of a sudden the checkout page wont load and I get this error:

Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of /var/www/test.dev/htdocs/includes/entity.inc).
EntityMalformedException: Missing bundle property on entity of type commerce_customer_profile. in entity_extract_ids() (line 7693 of /var/www/test.dev/htdocs/includes/common.inc).

and I have no idea how to fix it! I commented out what I had changed and nothing worked. I even did a git stash on all of my work to revert the changes and still nothing. My only guess is that somehow the database got messed up. How can I fix this? If I have to mess with the database, where do I start?

When you declare an entity and function entity_get_info($entity_type = NULL) is called, the next function cache_set("entity_info:$langcode", $entity_info)  is also called which stores the entity info in the cache table, so probably your change is cached in the database.

If you're  executing drush cc all and you have the same message error again, you can try several more things:

You can call this function entity_info_cache_clear()
https://api.drupal.org/api/drupal/includes!common.inc/function/entity_info_cache_clear/7.
Try executing SELECT cid FROM cache WHERE cid LIKE 'entity_info%' from MySQL command line and then DELETE FROM cache WHERE cid="entity_info:en" -> "en" or whatever depending or your language config.
Try truncating the cache tables:

You can do:

drush sqlc with

SHOW TABLES LIKE 'cache_%';

TRUNCATE cache_tablename;

in order to remove the cached data where entity info is stored. The content of this tables are regenerated programatically when you make a request.

That probably should works


Is there a way to manage a vocabulary with drag&drop when there are more than 100 terms? In Drupal 7, out of the box, it looks like the manage vocabulary page at  /admin/structure/taxonomy/myvocabulary handles 100 terms.  My vocabulary has about 500 terms, and I'd like to rearrange it into a parent and child structure.  Ideally, I'd like to get it all on one page to manage; is there a way to do this?

Otherwise, how am I supposed to reorganise a vocabulary spread out over 4-5 admin screens?

Have you looked at taxonomy manager?

https://www.drupal.org/project/taxonomy_manager


Import Users from D6 to D7 without directly accessing database I have to import users from a drupal 6 site to a drupal 7 one. I'd use https://www.drupal.org/project/migrate_d2d but i have several limitations on what i can do on the databases:

I can't access the drupal 6 DB from the drupal 7 installation
I don't have ssh access on the D7 server, i can interact with the database only from phpmyadmin
I can't create new databases on the D7 DB (i can create new tables though), and i can import sql files only to a maximum of 10MB. I can't upload a file on the server then import it from local either.
I have no limitations on the D6 database

In addition, user roles are different from the 2 sites so i need to map them before importing.
I think the best solution is to export data from the D6 site in some format and the import it on the D7 site but i don't know how to do it

Views data export module is perfectly capable of exporting your users to CSV file. You would use Views to define what you want to have exported, so you can export anything. You can also use Views GUI to define mappings, if you want. It is a powerful toolset, and VDO uses all that power.

When you will have your users in CSV, you can use User Import to import them. Pretty obvious, isn't it? For mapping, User Import can

  Match CSV columns to account and profile fields

So if you didn't manage to do it on the Views level, you can always edit CSV when you'll have it locally, or try to do it on import... So many options, I'm sure at least one will work.

Last but not least, make sure your users will get mails with "new password required" explanation, as D6 and D7 stores passwords in incompatible ways.


What is the token for [random:hash:?]? I created a marketplace there are two fields pue the product reference.

a "Store Reference" field that the store owner fills.
a "SKU" field I want it to be unique and generated automatically.

On Drupal Commerce I want the sku of my products to be generated automatically and that this code is unique.

I want a sequence of numbers and random letters, for example a single sku of 12 characters (number and letter).

There is a hash token in "Explore Available Tokens." and "Random". What is it used for ?

Can he meet my needs? Can it generate a unique code that will never be reused?

There are several store owners who can create products at the same time, the same sku must not be generated.

It's a token for generating a random string. When you look into the implementation, you can see it's the result of hashing 55 random bytes with your selected hashing algorithm (the ? part of random:hash:?).

Will it meet your uniqueness needs? Yes.

Since we're talking pseudo-randomness here and the fact that hashing algorithms can produce collisions, there's a possibility of the same string being generated but it's very unlikely (unless you have a massive number of SKUs being generated).

In the unlikely event that Commerce & the AutoSKU don't have the logic to prevent SKU collision (which should be there as its a unique attribute), you can always add more patterns in the token (e.g. UID) to lessen the collision possibility to effectively zero, for the number of SKUs needed by your store.


Drupal 6 Webforms sends duplicate emails A user fills out a webform that I created and it gets emailed me. Sometimes I get duplicate emails when they fill it out. I'm thinking that this is because they are hitting the submit button multiple times.

Is there a way to avoid these duplicate emails from happening? I use the smtp authentication support module and gmail to send the request out. Perhaps it's taking too long connect with gmail and the user is getting impatient, thus feeling the need to press the button continuously.

Your can deactive the submit button after it was clicked with custom javascript.

I write a sample below:

Drupal.behaviors.FormSubmitDisable = function (context) {
  $('YOUR BUTTON ID').click(function () {
    $(this).attr("disabled", "true");
  });
};


Track how many times a JSON file is requested from other websites I developed a mobile site using html and angularjs, which displays all of data from my Drupal site. From a view that output JSON data. All data collect good from JSON, but i can't create a popular item list.

Since, drupal not update node view by json request. So, i think, if i collect total request of each json/view, i can filter by this from my mobile site. So, i need to display how many times this json/view is requested from other domain/website like statistics module.

Does any method to track how many times a specific JSON/VIEW is called or requested from another domain/website?

There is a core module for that Statistics. On the configuration of this module (admin/config/system/statistics) you can ask for 'Count content views' who should work on every page drupal display (so your json).

There are a lot of custom module to extends statistics.

A little warning : Angular may be cache your json, so if your user go two times on a page you can loose this data. Maybe smarter to do this on the angular side.


How to use views argument in drupal? I am using views arguments for filtering jobs list.

I am taking state as argument.

Previously, state argument was accepting single value and it was filtering jobs correctly.

Now I made state field multivalued it means it accepts multiple states as input separated by comma.

here is my code for assigning arguments

$arg[0]=$filters['title_nodes'];
$arg[1]=$filters['company'];
$arg[2]=$filters['city'];
$arg[3]=$filters['state'];
$arg[4]=$filters['zip'];
$arg[5]=$filters['types'];
$arg[6]=$filters['categories'];
$arg[7]=$filters['industries'];
$arg[8]=$filters['beverages'];
$arg[9]=$filters['user'];

previously, $arg[3]=$filters['state']; this $arg[3] is filled with single state as New York etc. and for single value filter was working fine.

now, $arg[3]=$filters['state']; this argument is containing multiple states.

because of multiple states jobs are not getting filtered.

now suppose we entered 3 states, then in $arg[3]  3 states get stored and for each job,

argument checks whether there is any job who is having all 3 states in single job which is not possible.

Now how can I make this filter works for multiple states??

Thanks in advance.

any help will be appreciated.

If this is a contextual filter, you can specify AND or OR logic for the multi-values.

Views says:

  Allow multiple values

  If selected, users can enter multiple values in the form of 1+2+3 (for
  OR) or 1,2,3 (for AND).

So your querstring would have &state=CA+NY+TX to OR California, New York, and Texas states.


problem with printing multiple cck value inside node-type.tpl.php I am printing out this thing inside node-mytype.tpl.php (D6):

$dots = '';
$i = 0;
foreach($node->field_authors as $item) {
    $i = $i + 1;
    if ($i < count($node->field_authors)) { $dots = ',  '; } else { $dots = '.  '; };
    print '<span>'. $item['view'].$dots.'</span>';
}

Can somebody explain to me, why in this case printing $item['view'] == succesfully printing cck field values? Shouldn't it be like $item[i]['view']?

When i'm printing cck multiple values im usually do it this way:

print $node->field_authors[0]['view'];
print $node->field_authors[1]['view']; // if 2 values

Explain to me please, i would really appreciate it...

Your code uses foreach which takes $node->field_authors[0,1,etc] and relays that value through $item.  If you want to know the key for the current field inside your foreach loop, rewrite the code like this:

$dots = '';
$i = 0;
foreach($node->field_authors as $key => $item) {
    $i++;
    if ($i < count($node->field_authors)) { $dots = ',  '; } else { $dots = '.  '; };
    print '<span>'. $node->field_authors[$key]['view'].$dots.'</span>';
    // note: $node->field_authors[$key] is the same as $item['view']
}


Multiple copies of Views filter form (exposed filters) I know in views you have the option to expose the filters form as a block, but doing so removes the exposed form from the view page.  Is there any way to expose the filters form as a block and keep the exposed form in the view as well?

For example, is there a way to see

at the top of my view, but on every other page have an exposed form block like

in the side bar?

This would be helpful as when a user is on  a view page, he/she will be primarily concentrating on the main content and would look for a search there (instead of in a block on the side of the page).  However, users should be able to search the view from any page on the site (enter block).

Currently I have a custom module creating a block to act as the exposed form block while in Views I have Expose form in block set to "No".  Is there an easier way to handle this?

This hack works very well but there's no need for a hack if you have seperate displays from your view. My search results were displayed as a "Page" display and you also have the "Default" display.

On the page you would click "Exposed form in a block" then click "Override" on the right hand side. Set this to "No" (so the form now displays on the search page). In the "Default" display, have "Exposed form in a block" set to "Yes" - so by default it produces a block, but you also get the form to appear on the search page as well.

Thanks guys,
Garry.


Add additional fields to the postal address How can I add additional fields to the Address Field module's Postal address field? I would like to add a field for the county.

The default fields for the United States are the following.

I'm pretty sure there is a configuration in the field settings. If not in there I'd look at the module's config screen.


How to upload files to the sites/default/files place without going to the Cpanel backend just through admin backend? How to upload files to the sites/default/files folder without going to the Cpanel backend, just through the admin backend?

I need to put there a set of Ubercart images to make a bulk product import via feeds and .csv sheet.

If you want to upload files from UI you can use the elFinder file manager module. I've checked this module. Seems it's what you're looking for.
You can upload multiple files from admin UI itself. You can access the URL like follows

http://example.com/elfinder

Features

  Integrated with WYSIWYG API  capable editors: CKEditor, FCKeditor, TinyMCE, BUEditor (D6), jWYSIWYG (D6), YUI, WYMeditor
  Multiple file upload
  File copying/moving with Drag & Drop support
  Quick file and directory rename
  Image resizing
  Lightbox-preview
  Contect menu with generic file/directory operations
  Inline text file editing
  Favories directory list
  Directory selection history
  Working with archives
  File descriptions

screenshot


How to add "Agree to terms" checkbox in Drupal 8 form I've tried several solutions starting from the Boolean checkbox field in the Drupal 8 contact form to this answer, this answer and even this module but none of them work for me.

Basically I just want to display a checkbox which displays the text, "I agree to the terms and conditions of this site", and the words "terms and conditions" needs to be linked to its respective page on the site - to open in a new tab.

Any ideas on how this could be achieved in Drupal 8, via code or even a module is greatly appreciated

This is the code which I tried using in the .theme file

function <theme_name>_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'field_config_edit_form':
      $form['default_value']['widget'][1] = array(
        '#type' => 'checkbox',
        '#title' => t('Your checkbox'),
        '#size' => 10,
        '#maxlength' => 255,
        '#default_value' => 1,
        '#required' => TRUE,
        '#description' => '<p>' . t('Your checkbox altered.') . '</p>',
    );
    break;
  }
}

And I need this done on all contact forms of the site

Your code was D7 and what should a checkbox do with #size and #maxlength? :)

This answer presumes you have the Devel submodule Kint installed.

/**
 * Implements hook_form_alter().
 */
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  ksm($form_id); // Remove when done.

  if ($form_id == 'MY_FORM_ID') {

    $form['tos'] = [
      '#type'          => 'checkbox',
      '#title'         => t('Terms and Conditions'),
      '#required'      => TRUE,
      '#default_value' => TRUE,
    ];
  }
}

Check out this Introduction to Form API.


How to add block to "add/edit" content page? is there a way to add views block to add/edit content pages? I have two content types and one of them has Taxonomy term baste with unique terms (one term per node), when creating new node I want to have block with unused terms. I tried to accomplish this using Markup module but no success, and Display suite and Panels didn't worked.

Here's how to display a block on node add/edit pages in Drupal 8:

Go to Structure -> Blocks.  Select the block layout page for the theme you use to add/edit nodes. This is usually the admin theme, but it may also be the standard theme for your site if you want to display the block to non-admin users. If you want to show the block to both admin and non-admin users, you may need to configure the block settings (as described below) for both the admin theme and the standard theme.

On the block layout page, click Edit on the block you want to display.

Under Visibility, click Pages.

In the text field, enter:

/node/add/*
/node/*/edit

For Drupal 7, don't use the first slash:

node/add/*
node/*/edit

The * is a wildcard that says "any content/value can go here."

Then check the radio button for Show for the listed pages.

If you also want to limit the block to only show for certain content types, you can use the Content types option above Pages.


How to add attributes to forms? I am trying to style the registration/login forms so far I have copied all the files from \drupal\core\themes\stable\templates\form\ to themes\mytheme\template\form.

Inside this folder, for example there is input.html.twig which has the following code.

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

My question is how can I add a specific class name to this input, so I can apply styles to it in my css file

You can use the addClass() method of the attribute class:

{%
  set classes = [
    'my-class-1',
    'my-class-2',
  ]
%}

<input{{ attributes.addClass(classes) }}>

You can either pass an array like the example above or pass a single class in the method directly: attributes.addClass('my-class').

For reference see the Drupal docs: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates


EventSubscriber called on specific node type or path I'm trying to set an event that will launch function that loads some data from outside server and print it to javascript div element. I tried many ways but I can't figure out how to make this event be called only on for a specific node type.

Code I got so far:

class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onRespond',27]; //so far it works on respond but on every page
    return $events;
  }

  public function onRespond(FilterResponseEvent $event) {
    //do some stuff
  }

}

I managed to do it but I feel it could be done much better.

class eSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[KernelEvents::TERMINATE][] = ['onRespond',27];
    return $events;
  }

  public function onRespond(PostResponseEvent $event) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();
    $name = $user->getUsername();

    $output = [];
    if (isset($node) && isset($name)) {

      $nodeType = $node->getType();
      $soap_response = new classThatHandleRequests();
      $output = $soap_response -> get_clients_fv($name);
      echo('<script>var JSONarray = ' . print_r($output,1) . ';</script>');
    }
  }
}


Is possible to sort a views field that is generated by custom views handler? I have a view field that is generated by a views handler.
The logic inside the render method is as following:

function render($class) {

  if (class_hasnt_started($class)) return 'Registered';

  if (user_completed_entire_course($class)) return 'Completed';

  if (user_completed_some_classes($class)) return 'Attended x of y';

}

My question is, can such a field be sorted?

For a Table display, use the style options to make the field sortable.


How to get the calculated sell price for the current user? Is there a simple way to get the calculated sell price for the current user?

I try to get it from an implementation of hook_field_formatter_view.

Context: I use multiple rules to alter the base price. Work find but I want to alter the displayed price on product page. Sadly, from my hook implementation, the only price I get is the base price.

Find the tips:
Add this to the array return by my_price_formatters_field_formatter_info() :

'settings' => array(
    'calculation' => TRUE,
  ),

Like this:

/**
 * Implements hook_field_formatter_info().
 */
function my_price_formatters_field_formatter_info() {
    return array(
    'commerce_price_for_me' => array(
      'label' => 'Price my way',
      'field types' => array('commerce_price'),
      'settings' => array(
        'calculation' => TRUE,
      ),
    ),
  );
}

Then add this function:

/**
 * Implements hook_field_formatter_settings_form().
 */
function my_price_formatters_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $element = array();

  switch($display['type']) {
    case 'commerce_price_for_me':
      $element['calculation'] = array(
        '#type' => 'checkbox',
        '#value' => TRUE,
        '#title' => t('Show calculated price'),
        '#default_value' => empty($settings['calculation']) ? 'TRUE' : $settings['calculation'],
      );
      break;
  }
  return $element;
}

And this one too:

/**
 * Implements hook_field_formatter_settings_summary().
 */
function my_price_formatters_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();

  switch ($display['type']) {
    case 'commerce_price_for_me':
      if ($settings['calculation'] == TRUE){
        $summary[] = 'Show calculated price.';
      } else {
        $summary[] = 'Show base price.';
      }
    break;
  }
  return implode('<br />', $summary);
}

Then amount (in $items or $entity) will be the calculated price.

And that's all folks.


payment method in commerce I want to make a payment method, that works with web services. I made set of rules that decrease the money from the bank. at last the bank give me a code that it notices whether the payment is successful or not.for example 1 or 0. I want that if the code is 1 for example, Drupal thinks that payment is successful, and when the code is 0, means payment failure. and affect stock to decrease or increase by the returned code. how can I do that? is there any simple sample of on-site payment method ? thanks

This page has everything you need to know, including example payment method modules you can use as reference implementations:

http://www.drupalcommerce.org/developer-guide/utilizing-core-apis/writing-payment-method-module


Showing nested links in Drupal but still add classes to list elements Very new to Drupal and a bit confused.

In order to render a menu in my theme I've been using this:

print theme('links', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links'))));

That works a treat and gives me an extra class on the first and last list items, which I need for styling. It doesn't, however, show any of the nested sub menus.
So I found this that again, worked like a charm Show all nested menu links in Drupal 7 and shows all the top-level links in the main menu and the nested ones too.
This doesn't give me the extra classes on the first and last list items which I need.
Is there any way to use the code from the answer above and give the extra classes on the list items?

Thanks muchly

Check out the Menu Attributes module. Here is a quote about it (from the module's project page):

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
You want to give a menu item an ID so you can easily select it using jQuery
You want to add additional classes or styles to a menu item


Where are display settings for nodes stored in the DB? I need to manually update the display settings for my content types. I have a lot of content types and I don't want to have to do it one-by-one using the UI. Where can I show/hide fields for Default and teaser displays for content types directly in the DB?

With basic Drupal, the db table is field_config_instance, all in the "data" column.

With Display suite, you should also look at ds_fields, ds_field_settings, ds_layout_settings.

(Use drush sqlc for a mysql commandline, and then "describe ds_field_settings;" etc.)

This being said, you really want to look for API functions. Look at:

field_ui_display_overview_form_submit()
For display suite I'm not completely sure where you need to look.. But again, submit handlers are usually a good place to look.