How to translate "New custom content" in a panel? I have a lot of panels to which I have added bits of text/HTML using the "New custom content" option of the Panels module.

By default, such text does not show up on the Translate Interface screen.  How should I go about translating them?

Two approaches I have found are:

Changing the custom content text format to PHP code and printing the string(s) of text using t().  This then allows me to translate the strings on the Translate Interface screen, but I worry that injecting PHP code like this is a bad precedent.
Since I only have two languages, I can add a second piece of custom content that is localized in the other language.  Then, I can add a visibility rule to each piece of custom content in Panels and set each piece to show only when the user's language matches the content language.  This works but it is time consuming and ugly on the backend.  It would be even worse if I decide to add more languages to my site in the future, which I may do.

Is there a more efficient, maintainable way to translate such custom content?

First of all, I would like to explain why this doesn't "just work", so that you have been given fair warning before I give you new problems. :)
Consider a custom content pane content like:

Welcome %user:name, you have %field_num_messages new messages waiting.

The text here would be substituted before passed to t(), meaning that for each variation of user and number of messages, you would get an entirely new string to translate. For such panes, go with having two separate panes.

A long term solution is slowly being worked on here: Translatable panel titles: Implement i18n_strings but focuses on the pane titles initially.

Generally speaking, the solution is to avoid custom content panes, but I also realize that using them can be very convenient at times.

Finally, here's a piece of code I've used to "force" pane titles to become translatable. I will attempt to later modify it better to your situation, but I figured having a useful answer quickly was better than not. :) You should be able to use $pane to figure out if this is a custom pane, and then pass the text through t().

/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}


Drupal form submission to another page Below is my form and form submission function. The form is displayed in page-front.tpl.php. Using this code i could print $_POST variable in the front page. But i would like to submit to some other page say page-result.tpl.php. How could i do that without using $_session variables

    function q_search_form($form_state) {

$form['category'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 2 => 'Automotive', 1 => 'Real Estate'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '

Select Category	',
    '#suffix' => '
'
);
$form['city'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 'kozhikode' => 'Kozhikode', 'kochi' => 'Kochi'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '
City	',
    '#suffix' => '
'
);
$form['property'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 18 => 'Land and House', 17 => 'Land'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '
Property	',
    '#suffix' => '
'
);
$form['wanto'] = array(
    '#type' => 'select',
    '#options' => array('' => 'Any', 'sell' => 'Sell', 'buy' => 'Buy'),
    '#attributes' => array('class' => 'drop-box'),
    '#prefix' => '
Want to	',
    '#suffix' => '
'
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
    '#attributes' => array('id' => 'Search', 'class' => 'srch-button'),
    '#prefix' => '
Advance Search	',
    '#suffix' => '

'
);

return $form;
}

  function q_search_form_submit($form, &$form_state) {
    $wantto = $form_state['values']['wanto'];
    $property = $form_state['values']['property'];
    $city = $form_state['values']['city'];
    $category = $form_state['values']['category'];

    $sql = ' SELECT A.nid FROM node A
        LEFT JOIN content_type_item B ON A.vid = B.vid
        LEFT JOIN term_node C ON A.vid = C.vid
        LEFT JOIN term_hierarchy D ON D.tid = C.tid
        WHERE A.type = "item"
        AND B.field_tr_type_value = "'.$wantto.'"
        AND B.field_city_value = "'.$city.'"
        AND D.parent = '.$category.'
        AND C.tid = '.$property.'
      ';
   $result = db_query($sql);
  while ($row = db_fetch_array($result)) {
     $output['srch_result_nid'][] = $row['nid'];
    }

  $form_state['rebuild'] = TRUE;

  }

In your form_submit, add $form_state['redirect'] = <your_url>, at the end.


How to get term from alias I've to get the taxonomy_term tid from the alias ('/alias/of/my/term')

Is there a way to do this without making a query on url_alias table?

The only way to avoid a query is if the alias is already in the cache. Rather than worry about that yourself, it's best to use the API (even more so in Drupal 8 as path alias storage is pluggable and may not be in the database):

Drupal 7, using drupal_get_normal_path() :

$system_path = drupal_get_normal_path($path_alias, $langcode);

Drupal 8, using the path alias manager service:

$system_path = \Drupal::service('path.alias_manager')->getPathByAlias($path_alias, $langcode);

As always it's preferable to inject the service into the consuming class if context allows.

Both methods will get you the system path, e.g. taxonomy/term/1, from which you can extract the term ID.


Use custom content entity theme suggestions in own module? I have a custom content entity called 'offer'.
I've added template_preprocess_offer() and offer_theme() to the  offer.module file.
function offer_theme($existing, $type, $theme, $path) {
  return [
    'offer' => [
      'render element' => 'elements',
    ],
  ];
}

function template_preprocess_offer(array &$variables) {
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

In modules/custom/offer/templates/offer.twig.html, I successfully render the entity.
Next, I've added theme suggestions because I've added a view mode 'full' via the UI.
/**
 * Adds template possibility for view modes
 * Implements hook_provider_theme_suggestions_hook_alter
 */
function offer_theme_suggestions_offer_alter( array &$suggestions, array $vars, $hook ) {
  if ( $offer = $vars['elements']['#offer'] ) {
    if (isset($vars['elements']['#view_mode'])) {
      $suggestions[] = 'offer__' . $vars['elements']['#view_mode'];
    }
  }
}

After clearing caches:
<!-- THEME DEBUG --> <!-- THEME HOOK: 'offer' --> <!-- FILE NAME SUGGESTIONS: * offer--full.html.twig x offer.html.twig --> <!-- BEGIN OUTPUT from 'modules/custom/offer/templates/offer.html.twig' -->

This only works if I place a offer--full.html.twig inside the theme's templates folder. It doesn't work in the custom module template folder. Inside modules/custom/offer/templates, the template file with the view mode won't get used. While the template suggestions suggests offer--full.html.twig, offer.html.twig is used instead.
Why does it happen? How can I solve it?
Edit: I'm on drupal 9. My custom entity has no bundles. I've made sure the id inside @ContentEntityType is "offer".

To make a theme suggestion work in the module folder you need an additional theme hook:
function offer_theme($existing, $type, $theme, $path) {
  return [
    'offer' => [
      'render element' => 'elements',
    ],
    'offer__full' => [
      'base hook' => 'offer',
    ],
  ];
}


Views, Contextual Filters, and Path Alias First, a disclaimer:  I am less than a year into learning Drupal just to give you a frame of reference.  I am probably using incorrect terminology in my searches so if there is an answer out there, a point in the right direction would be greatly appreciated.

I am building a site that will have multiple "categories."  In each category, there will be page content.  So, my URL will (should) look like this:

www.example.com/category/page

All of my pages have been put into their respective subdirectories which are named for their categories.  For example:

widgets/page1  (node 10)
widgets/page2 (node 13)
widgets/page3 (node 24)
services/page1 (node 12)
services/page2 (node 15)
services/page3 (node 17)

If I type the url /widgets/page1 I get the "article" not the view.  If I type in the url with node id:

www.example.com/widgets/13

The view works perfectly and shows me widgets/page2

I created a page view for widges and set its path to "widgets"  so the url would be:

www.example.com/widgets

I have created a view that displays all my relevant info.  I also created an "attachment" that shows me related content from the same category.  This actually works quite well - it displays all the relevant content with linkable titles.

The problem that I am running into is when I click on one of the titles (or type the link directly) it no longer goes through the page view.

How do I structure this so that all links go through the views?  I am missing something, I just don't know what.

Screenshot of my Views Page

Ok, under Fields, click on the Title, then tick "Link this field to the original piece of content", then under "Rewrite results" tick "Output this field as a link", then in Link Path below it try "widgets/[nid]" then save obviously!


How can I get the responsive image style id from a FileFieldItemList I am trying to get the machine name of the responsive image style attached to a field. I am not able to get this from the settings attached; it seems it is not accessible from the object in any way.

How can I get the responsive image style ID from a FileFieldItemList?

This setting is not a field setting. Because a field can be part of different displays. You have to look for this setting in a view mode. For example if you configure the image field of the article with a responsive image style, your view mode would contain something like this:

core.entity_view_display.node.article.default:
  content:
    field_image:
      type: responsive_image
      weight: 0
      settings:
        responsive_image_style: *responsive_image_style_id*


How to determine if a script is started by cron? I have a script that run in some cases when some event occur. It also run when cron run (cron.php) or the "Run cron button" from admin panel is clicked.

How can I determine that from script that is started by drupal cron.php?

You may check your $_SERVER globals in the script.

A better way, I think, would be to pass a parameter with your call to the script that separates the caller (I.e when you call it from the HOOK_cron(), add a myFunc(..., $caller="cron") to your call. And declare myFunc(..., $caller=null) as default parameter.

If this is not possible, you may set a session variable in HOOK_cron and check that in your script.


Enable new modules dependencies on deploy How can I automatically enable new dependency added on a custom feature (or standard modules) with drush?

After getting the new code, my deployment script basically run:

drush cc all
drush fra

But I need to visit the admin/structure/features page if I added new dependencies otherwise those modules are not enabled. How can I avoid it? Is there a drush command? I can't use drush en thenewmodule because I want to keep my deployment script generic.

There is a feature request issue in a Drush queue, just stumbled on it. In donquixote's Drux project are commands you need:

  drux-enable-dependencies (dep-en) - Download and enable dependencies of existing modules.
  drux-find-obsolete (obs) - Find modules that are not direct or indirect dependencies of the modules given as arguments
  drux-generate (obs-gen) - Generate a list of dependencies[] = .. to copy+paste into a module info file.
  drux-list-dependencies (dep) - List dependencies that would be enabled with drush dep-en. (The help text seems to be wrong).

So for the task at hand, drush dep-en should do the job.

You can download it here.

UPDATE:
Now available on github: https://github.com/donquixote/drupal-drux

Alternatives, part I

As pointed out by Jesse Pinho in another answer, you can also run drush fr DEPENDENT_MODULE.

Or you can run drush en DEPENDENT_MODULE.

The difference is that for these commands you need to know the "DEPENDENT_MODULE" which has the added dependencies.

With drush dep-en you can just run the command without any arguments, and it will check all enabled modules for dependencies.

Alternatives, part II

Instead of such drush commands in combination with dependencies, you could also use hook_update_N() to enable additional modules. This seems a common technique for Drupal 7 projects.

See the answer by reubidium.


Drupal fullcalendar integration -> JSON Formatting? I am working on a custom fullcalendar (http://fullcalendar.io/) implemenation for a custom module of mine.

I have created an hook_menu that will provide the json output that contains the events that need to be placed onto the calendar:

function mymodule_fullcalendar_measurement_jsonfeed() {
$json = array(
 '0' => array(
   'id' => '182',
   'title'=>'My Event',
   'start'=>'2015-02-16 13:00:00',
   'end'=>'2015-02-16 16:00:00',
   'description' => 'event desc',)
 );

  $jsonstring = drupal_json_encode($json);
  drupal_json_output($jsonstring);
}

And an ajax call to the hook_menu like below:

events : '/my_module_fullcalendar/jsonfeed',

This returns a json string like this:

 [{"id":"182","title":"My Event","start":"2015-02-16 13:00:00","end":"2015-02-16 16:00:00","description":"event desc"}]

The fullcalendar does not recognise this format, because it expects an event object.

I tried to use eventDataTransform to convert this into a correctly formatted object (as stated here: http://fullcalendar.io/docs/event_data/eventDataTransform/), but not luck so far.

I'm pretty sure that this is a formatting problem, because when i change the full calendar jquery events property like this:

events: my_events

And use a variable to create a dummy object:

        var my_events = {
      events: [
        {
          title: 'event 1',
          start: '2015-01-04',
          color: 'tomato'
        },
        {
          title: 'event 2',
          start: '2015-01-09'
        },
        {
          title: 'event 3',
          start: '2015-01-09'
        }
      ],

Everything works perfectly...

For the record i am working with full calendar 2.2.7

Thanks so much!

The solution was pretty straight forward actually.

I replaced the jscon encode and json output like this:

drupal_json_encode($json);
drupal_json_output($json);

And now it runs smooth :-)


Different theme of Media module audio player in Firefox and IE and chrome I installed Media module, and there is a content type for audio files. The Manage display of the audio field is Audio. But the player has different themes in different browsers. This is what Firefox displays

This is for IE

and it is chrome

What is the problem? why do they have not the same theme?

thanks

If I am not mistaken, these are the native displays for the HTML5 <audio> element in different browsers. I don't think the Media module has anything to do with it, it probably only displays the markup without adding any theming.


One-time URL to change a user's field value How can I create a one-time URL (sent through email messages) users can use to change the value of a custom field?

Unfortunately Drupal requires that users reset their passwords when using the one time login link.

The easiest way to avoid that would be to use a module like URL Login, which generates login links for each of your users. There are a couple of modules which cater for similar use cases so you'll need to find out which one works best for you.

You can then use LogginToboggan to redirect your users to your custom page where they can edit the custom field. You may need to create a custom User Role depending on the need for access control.


Is there something equivalent to template_preprocess_search_results()? I just realized that template_preprocess_search_results() function has been left out in Drupal 8 for some reasons, although template_preprocess_search_result() (for single results) is still there.

I need to be able to manipulate the search results prior to rendering as I would with template_preprocess_search_results() in Drupal 7.

You can create a new module and inside your YOUR_MODULE.module file put this code:

function YOUR_MODULE_preprocess_item_list__search_results(&$variables) {
  //to use dpm() you nedd the devel module
  dpm($variables['items']);
}

Install your module and you will see the output in the search result


Content Filter based on Heirarchical Taxonomies I have one taxonomy named "Project Parameters" with hierarchical select and another taxonomy names "Project Sub Parameters" with hierarchical select.

I Want to filter the content with those taxonomies like on selection of Project parameter display its sub parameters and click on sub parameters with ajax call i need content filter

I Had created view and with contextual filter i achieve that but that load the page. I want to do same functionality with ajax only, No page reload.

Is it Possible? Please Help Me.. I am stuck since last 2 days.

Create views for

Project parameters
Project sub parameters with contexual filter of project parameter taxonomy id with filter criteria
Content view with contexual filter of project sub parameters taxonomy id.

After Create these views you can call ajax api and pass those conexutal filter on ajax for particular view like,

$view = views_get_view('viewname'); //viewname is the view machine name
$view->set_display("block_1"); //block_1 is the view display name
$view->set_arguments($tid); //$tid is the argument to pass
$view->pre_execute();
$view->execute();
$content = $view->render();

I got the success by this way.

Hope this answer help somebody.


Move "Items per page" selector to the top of the content This is my problem of the day.
I would like to display the Items per page at the top of the content block.

I'm working on a View Block, this is an Exposed Filter with "Better Exposed Filter".
For now, I'm doing this the dirty way with jQuery and a unstable DOMSubtreeModified bind.
I have a twig with {{ exposed }}, but Drupal doesn't suggest me any deeper twig and if I had one, it wouldn't access the Content div I guess. So I have no idea about how to do this.

Here is the div organisation :

    div.exposed-block

        form.views-exposed-form

            Filter-1
            Filter-2
            Items-per-page (select)

    div.view-block (with my content)

So, the idea is to move Items-per-page to div.view-block.
Or into another that I can create, here is the twig part :

    {{ exposed }}

    {{ rows }}

How would you do this ?

Thanks in advance.

This is the answer I got from a forum.

    {{ exposed | without ('items_per_page') }}

    {{ exposed | without('my_first_other_filter', 'my_second_other_filter') }}
    {{ rows }}


Webform submit button does not work I have created a webform block. After I enter all the info in the webform, I clicked the Submit button. Nothing happens. Do you know why the Submmit button is not working?

This webform block's submit button works: http://godrupal.info/?q=contact-us

Actual webform node's submit button works : http://godrupal.info/?q=node/16. Then I created block of the node/16 but then this webform blocks's submit button does not work: http://godrupal.info/?q=plan-an-event

if you look into your console log you will see the following errors

this happens when you hide a required field.

I had a look at your markup and found that you have the above 4 fields display set as none; and at the same time also has attribute required.

So remove the required attribute or apply novalidate on submitting form.


Use form in the content type who use a form in a node?
for example
I want to create a content type that show in this, my product , description , ....
and bottom on this node have a form to get comment and price recommended of user.

I test Webform but not in use for me!

who to create this content type?

It depends on what exactly you want to do. Maybe you just make one contenttype for your product and let users comment this product with nodecomments. This way you can make an extra contentype for your comments with extra fields (e.g. price.). There is no need in displaying these comments afterwards. But why does the webform-module not work for you?


Filter two vocabularies in Drupal 7 I want to do a similar filter like at this page:
http://www.nasdaq.com/screening/companies-by-industry.aspx?industry=Technology

I have two vocabularies. Countries and Industryes.
We chose an industry, and then we choose from what country we want the company.
It show me a firms, witch are in one industrie, an example Technologies and in one country, an example Afrika. Not all countries, not all industries. Can someone help me with this? I´m sorry for my english. I will be grateful for any help. I use Drupal 7.

This is not a standardfeature of Taxonomy. In fact, it is not a part of the concept Taxonomy, regardless of using Drupal at all.

However, you can achieve this, somehow with Drupal taxonomies, when you abuse them as Facets.

For that, you need to set up your views and provide quite some hacks, amongst others, you need to add some PHP to your views.

From a birdseye, here is what you do:

You create views that list only nodes with term X as parameter: /mypage/12 to show only pages with term 12.
You allow Drilling down in that list, by nesting the parameters: /mypage/12/35 to show only nodes with BOTH term 12 AND term 35.
You abuse the views header to present links with options: links to the nested options: on mypage/12 it would show, amongst others, a link to term 35, a link to /mypage/12/35.
The code to select these options can be simplified by making a second view: a view that lists all options nested under 12.
In the header of the first, node, view, you then place some PHP that fetches and renders these links.

For a long and detailed howto, I think burningbird has a good manual


Commerce Customizable product (Example: add/remove topics for pizza) I'm trying to find a way to give the chance to the customers to "customize
" their products.

Straight example:
Luigi has got a Pizzeria and he would like to sell his pizze online where customers can add or remove topics.

Is there a way to get this option with the basic function of Drupal commerce?
Maybe playing around with products and rules?

This could be very useful for a lot of website type.

I found this module Commerce Customizable Products , it seems to do half of the job. I can add my topics and then with rules I can update the price. It looks like i cannot show the basic topics. Every pizza has to start empty.

Is there anyone who was had experience with it? Any suggestion?

If someone wanted to build a module, I would like to help with it.

Thanks in advance.

12/09/2012 UPGRADE ---------------------

Using Customizable Products I've created a new line item with a term reference field.
It will be visible in the product page and will show all the term from that taxonomy.
In the product I've got the term field(manage display: hidden) where the editor can select the pizza toppings.

Now, because the line item will print all the terms I would like to create a function that checks the term in the product and puts a flag on the right line item term.

Then, because customers can add and remove toppings from the pizza, in the view I would like to create another function that check if the user has unflagged the basic toppings and print the sign " - " before the toppings.

So the pizzeria will receive:
Pizza:

-ham

+salami

Ham was in the basic toppings.

What API can I use to get this work?

I think this Josh Millar video will help.

Customizable Product with Drupal Commerce: Pizza Store


D7 dynamic views by user input First of all I want to let you know that I am a newbie with Drupal so maybe this question isn't good or even not possible to apply with Drupal.

I got a custom content type that includes in it a lot of fields and among them there are a date field and a list field.

My goal is that a pop window will flow when user enters my site, then he will submit a date and a value that the list contains, and he will get into a page that will display the nodes that include the same input he puts in.

Can someone explain me how to do it?

Thanks in advance :)

This is a broad question that it pretty much requires some proficiency with several aspects of Drupal.

In short, first I would recommend you that you find a ready theme which features some kind of pop-up as you require. Alternatively, you would need to theme a pop-up region by yourself.

Then, you need Views module with exposed filters in a block, which you would add to this specific region.


How to insert a new column into mysql field data table? How would I insert a new column into mysql field data table? For example, if I have a field (myfield) with the mysql table field_data_field_myfield having the following columns'entity_type', 'entity_id', 'revision_id', 'bundle', 'delta', 'language', 'myfield_value' and 'myfield_format'...how could I add the column mynewcolumn as type varchar?

For adding new column in table, please check this discussion Correct way to add custom column to user table?.

Please check this discussion also https://www.drupal.org/node/2616250


How do I have menu linked content not on main page? My web site is the first drupal site I have made.  And after I made it, I left it to do other work -- like write the blogs for the site.  I cannot remember how I set up the content pages that link to menu selection that do not appear as content on the main page.

The best way to explain what I am talking about is with a screen capture.  I have added menu items to my main menu.  I do not remember how I did it in the past.  I want to add content and have it linked to the main menu (this option is available to me when I create the content) but I do not want them to appear as stories on the main page.

The circled areas in this screen shot shows the menu item I just added and the corresponding item on the main page that I do not want to be there.  How do I remove it from the main page?

I am thinking that perhaps I should not have added it as a "content" but something else? If so, what and how?

http://www.arguemax.com/images/problems/12-6-2015/Capture_001.PNG

When you create the Content, be sure to uncheck "Promoted to front page" in the option menu shown at the bottom, under Published options. See image.

If you want this option by default for a specific content type (for example, for Articles) you will need to go to Structure > Content types and edit that content type's Publishing options to uncheck Promoted to front page. This will become the default option when you create a new Article.


Updating settings.php breaks website hosted from subfolder This is somewhat linked to this question.  I have 2 Drupal 7 sites hosted in subfolders, one of which is intended to be a production site (public_html/site1) and the other is the testing site (public_html/site1-test).

The main url (i.e., site1.com) should be shown when accessing the production site.  When I go to my main url, it shows correctly.  However, all links and content are shown via the subfolder (e.g., site1.com/site1/content/... rather than site1/content).

To facilitate the change, I updated the $base_url variable in the settings.php file to serve the base URL (i.e., site1.com) and that completely breaks the site.  The theme stops showing, logins don't work, etc.

Is there a way around this problem?  The main site should mask off the subfolder in the url, however I don't think I can do that without updating the $base_url

Try setting your base URL in settings.php like

$base_url = 'http://site1.com';  // NO trailing slash!

And in your .htaccess file set RewriteBase to:

RewriteBase /site1

or

RewriteBase /site1-test


Why do I need to remove old files first when upgrading Drupal or its modules? I'm in the process of updating my Drupal version 7.41 to 7.43 and started o follow the guide Update procedure (minor version change) where it says

  Remove all old core files and directories, except for the 'sites' directory, the original install profile in the 'profiles' directory and any custom files you added elsewhere.

and I was wondering why they wanted to have me erasing everything first, can't I just copy all the new content into my ftp folder except the sites/ directory?

Thanks

By deleting all the directories you're ensuring no files are left over that shouldn't be there anymore. A simple overwrite won't always do that.


Picture linked to user's profile in user-picture.tpl.php D7: In my user-picture.tpl.php template I have the following code:

<div class="user-image">
  <?php
    $user = user_load($account->uid);
    print theme('image_style', array('style_name' => 'square', 'path' => $user->picture->uri));
  ?>
</div>

This short snippet sets the default, site wide, for the user picture.

When using views, linking the picture is easy. But when not using views, how can I change this so that the picture is linked to the user's profile?

Any help on this would be greatly appreciated. :)

template_preprocess_user_picture() uses the following code.

  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath) && $style = variable_get('user_picture_style', '')) {
        $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

Assuming you just want to use a specific image style for the image, and hard code it in your theme, I would use the following code for mytheme_preprocess_user_picture(). (Replace mytheme with the short name of the theme.)

  $variables ['user_picture'] = '';
  if (variable_get('user_pictures', 0)) {
    $account = $variables['account'];
    if (!empty($account->picture)) {
      if (is_numeric($account->picture)) {
        $account->picture = file_load($account->picture);
      }
      if (!empty($account->picture->uri)) {
        $filepath = $account->picture->uri;
      }
    }
    elseif (variable_get('user_picture_default', '')) {
      $filepath = variable_get('user_picture_default', '');
    }
    if (isset($filepath)) {
      $alt = t("@user's picture", array('@user' => format_username($account)));
      if (module_exists('image') && file_valid_uri($filepath)) {
        $variables['user_picture'] = theme('image_style', array('style_name' => 'square', 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      else {
        $variables['user_picture'] = theme('image', array('path' => $filepath, 'alt' => $alt, 'title' => $alt));
      }
      if (!empty($account->uid) && user_access('access user profiles')) {
        $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
        $variables['user_picture'] = l($variables ['user_picture'], "user/$account->uid", $attributes);
      }
    }
  }

Doing so, the template file would just need to print $user_picture.

Keep in mind that the image style used for the user image is contained in a Drupal variable. I would investigate on how to change that variable for the theme you are using, even though you would then need to change it back for the other themes, in the case your theme is not anymore the active one.


How to permit one sub admin to change passwords of other certain users? I'ld like to make a sub admin be able to change other user's passwords depending on other user's role or uid.

The sub admin should be able to type the password by himself. Emailing a generated password is unfortunatley no optionn since the aimed user accounts will be used by a quite loose group of people (teachers and pupils, sub admin wants to change password every school year).

Until now there are only very few different accounts where that needs to happen. So can I maybe do that with uids?

Is it maybe possible to build a block that provides a form with password fields of the desired users? What hooks or forms would I need to use or alter then?

Any idea and/or explanation is very much appreciated!

Thanks to arpitr and my coworker J., I finally did it with a form on a page which is accessible only to selected roles via hook_permission(). The desired array() of uid=>name of that certain role to pass on as select list #option comes from db_select(), which definitely was the most difficult thing to get:

function _get_users_by_role($role_name) {
  $query = db_select('users', 'u')
    ->fields('u', array('uid', 'name'));

  $query->innerJoin('users_roles', 'ur', 'u.uid = ur.uid');
  $query->innerJoin('role', 'r', 'ur.rid = r.rid');
  $query->condition('r.name', $role_name);

  $result = $query->execute()->fetchAllKeyed();

  return ($result) ? $result : array();
}

For those interested in the custom block approach arpitr proposed, check the accepted answer on How can I display a change password form on its own? for a even more detailed description.


How do I translate a view's "Menu tab" I am on Drupal 7.56 on a multilingual site.

I have created a view that contains tab menu links. Almost all the site it available now in two languages. But I still can't translate those view tab menu links.

I use those tabs to let users access some information via their account area

Example : in a view that contents articles (that I want to user to see only those they created) I add a menu link this way :

link       : "user/%/myarticles".
Menu name  : My Articles
Menu type  : menu tab
Menu "Menu : User menu

I have translated the view but I can not find any way to translate the "Menu name", not even in "admin/config/regional/translate/translate".

Users will see "My Articles" in both languages when I want them to see it written in the correct language in each case.

How do I present the user with only the correctly translated tab?

The first steps when dealing with translations, particularly with user entered strings like Views Tabs labels, is to clear the cache and visit the page showing the string in question but make sure you visit in a language other than English!

The visit to that page with the interface in another language will trigger Drupal to refresh the Translate Interface list, and you should be able to find the new string when doing a search there (admin/config/regional/translate/translate).

Remember that the Translate Interface search is case sensitive! You have to enter "My Articles" and not "my articles" or any other case style.

If that search still isn't giving you any results, it may be you're missing a module that enables those strings to be included in translations. Make sure you have "String translation" or perhaps even "Variable translation" enabled.

If you've just enabled "String translation", similar to above, visit the page in another language then search for the string in Translate interface.


How to capture git's output in drush make? We use drush to clone a number of git-repositories during build. Most of the time this "just works", but on (a rare) occasion, a cloning fails.

Unfortunately, all that we get from drush in such cases is:

  Unable to clone repository                                 [error]

The DRUSH_BACKEND piece of JSON is shown, but claims no error ("error":null):

DRUSH_BACKEND:{"type":"notice","message":"Command dispatch complete","timestamp":1411582254.5773,"memory":10891736,"error":null,"packet":"log"}

The actual error message generated by the git-executable is not shown. Is there a way to change that? Simply adding --debug to drush's command line does not do it...

This question may not even be drush-make specific -- the spawning of external programs and capturing their stdout/stderr may be a generic drush thing...

Thank you!

Ok, the short answer is: it is not possible. Not at the moment. Although the code in includes/exec.inc is prepared to output the captured stdout and stderr of the command, it will only do so, if DRUSH_DEBUG is set:

  exec($command . ' 2>&1', $output, $result);
  _drush_shell_exec_output_set($output);

  if (drush_get_context('DRUSH_DEBUG')) {
    foreach ($output as $line) {
      drush_print($line, 2);
    }
  }

The only way to set DRUSH_DEBUG is by giving the --debug flag on drush command-line (it can not be set from drushrc.php). Sadly, in a number of cases -- including git-invocations -- the top-level drush invokes a child drush to do the actual work. It is doing so without passing the --debug flag to it...

I filed a ticket with drush-maintainers and implemented a work-around. We replaced the real git executable with a shell-wrapper, which captures stderr of the real git (and some other info, like environment veriables) into a log-file, then feeds the captured stderr to its own descriptor 2 -- just in case the caller cares. Then, if the real git's exit-code is 0, the log is deleted, otherwise it is retained for investigation.


How to add password reset link to user page? Is there an easy way to add a password reset button to the user page in drupal 8? For user management I need the admin to be able to send password recovery link to users AFTER the user account is created. This button should only be visible to admins.

You can create a custom module for that:

modules/custom/resetpassmodule/resetpassmodule.info.yml

name: 'resetPassModule'
type: module
description: 'Reset Password link for administrators'
core: 8.x
package: 'Custom'

modules/custom/resetpassmodule/resetpassmodule.module

<?php

/**
 * @file
 * Contains resetpassmodule.module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;

/**
 * Implements hook_help().
 */
function resetpassmodule_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    // Main module help for the resetpassmodule module.
    case 'help.page.resetpassmodule':
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('Reset Password link for administrators') . '
';
      return $output;

    default:
  }
}

/**
 * Alter the user edit form
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function resetpassmodule_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

  //Load the current user roles
  $user = \Drupal::currentUser()->getRoles();
  // Only show the reset link button if the user is administrator.
  if(in_array("administrator", $user)) {

    //Add the reset button to the form.
    $form['actions']['sendresetlink'] = [
      '#type' => 'submit',
      '#weight' => 999,
      '#limit_validation_errors' => [],
      '#button_type' => 'danger',
      '#submit' => [
        'resetpassmodule_send_reset_link_to_account_form'
      ],
      '#value' => t('Sent reset link to account email'),
    ];
  }

}

/**
 * Custom submit handler for the password reset button
 *
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function resetpassmodule_send_reset_link_to_account_form(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  // Load the user entity of the form.
  $account = $form_state->getFormObject()->getEntity();

  // Create a timestamp.
  $timestamp = \Drupal::time()->getRequestTime();
  // Set the redirect location after the user of the one time login.
  $path = '' ;

  // Create login link from route (Copy pasted this from the drush package)
  $link = Url::fromRoute(
    'user.reset.login',
    [
      'uid' => $account->id(),
      'timestamp' => $timestamp,
      'hash' => user_pass_rehash($account, $timestamp),
    ],
    [
      'absolute' => true,
      'query' => $path ? ['destination' => $path] : [],
      'language' => \Drupal::languageManager()->getLanguage($account->getPreferredLangcode()),
    ]
  )->toString();

  // Genereate mail.
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'resetpassmodule';
  $key = 'user_reset_links'; // Replace with Your key
  $to = $account->getEmail();
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

  // Set the message and the subject.
  $params['message'] = $link;
  $params['title'] = "One time login link";

  // Send mail and collect the result.
  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] != true) {
    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
    drupal_set_message($message, 'error');
    \Drupal::logger('mail-log')->error($message);
    return;
  }

  $message = t('An email notification has been sent to @email ', array('@email' => $to));
  drupal_set_message($message);
  \Drupal::logger('mail-log')->notice($message);

}

/**
 * Implements hook_mail().
 */
function resetpassmodule_mail($key, &$message, $params) {
$options = array(
  'langcode' => $message['langcode'],
);
  switch ($key) {
    case 'user_reset_links':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Your mail subject Here: @title', array('@title' => $params['title']), $options);
      $message['body'][] = Html::escape($params['message']);
      break;
  }
}


How to adjust weight of profile 2 fields I added some fields to the default user registration form. I then installed the Profile 2 Module through which I added three (3) fields- "first name", "surname" and "place of work".

Is there a way to make the first name and surname fields appear above the default user registration fields while the place of work appears below it?

Thank you.

You will have to use the Drupal Form API to achieve that.

You basically need to alter the structure of the form before it gets rendered.

If you are using the Profile2 module, the best way to go about it would be to implement hook_form_profile2_edit_PROFILE_TYPE_form_alter()in a custom module.

You will then need to transform the $form array as needed (change field weights, and field positions).

For example:

function MODULE_NAME_form_profile2_edit_YOUR_PROFILE_TYPE_form_alter(&$form, &$form_state) {
  // Apply transformations to $form
  // e.g. change field weights
  $form['your_custom_profile_type']['place_of_work']['#weight'] = '-10';

  // e.g. copy field into new position
  $form['account']['place_of_work'] = $form['your_custom_profile_type']['place_of_work'];

  // Add a custom pre_render function to prevent the field from showing up again in the form
  $form['#pre_render'][] = 'MODULE_NAME_pre_render';
}

The pre_render function could look like this:

function MODULE_NAME_pre_render(&$form) {
  // Prevent custom field from displaying twice
  unset($form['your_custom_profile_type']['place_of_work']);
  return $form;
}


some cck fields of content type not displayed (corresponding elements also not showing in devtool) Out of the blue it happened that a custom content type won't display some of the cck fields I constructed for the custom content type. This happens when I just visit the a full node of that content type.
When I go see in firebug, I also notice that the HTML elements to those custom made fields are entirely missing.

I checked the display options under admin->content
type->customcontenttype and everything looks the way it should.
I checked view permissions and those are also set for anonymous and
admin roles.

Does this sound familiar to someone that cck fields cease to be displayed in full node?

You say you enabled all modules under CCK which means you probably have Content Permissions enabled.

Content Permissions module gives you per-cck-field view/edit permissions (which are all off by default!). Check that you have the correct permissions set for your fields or disable the module if you don't need that granular control.


Blank browser after clearing the cache I migrated a site from windows xampp to ubuntu. It was working fine. But once I cleared the cache, the browser is showing blank screen.I tried going to different urls . I also tried clean urls but nothing is coming. All I can see is a white/blank browser.

The White Screen of Death (Completely Blank Page) is a good starting point to takle down the problem.

For D7, extension=php_domxml.dll in php.ini must be commented out. With that dll enabled, I got a blank screen too in Windows.
Check with your php configuration in your linux server.


How do I apply a discount for the second and successive items only if the quantity for those items is higher than 1? Using Commerce Discount and Commerce Discount Extra modules there is no problem to set discount rule conditions for product type and quantity. This way I can set up 20% off discount that is applied for a cart line item when this line item has specific product type and quantity more than one. 20% off discount is then calculated for this line item and multiplied by quantity.
However, my need is to apply such discount not to each item from line item quantity. I simply want to exclude applying discount for one (first one) on the basis: 0,2*(n-1)*X where n is qty and X is product base price.
The problem is that line item discount type in Commerce Discount module is calculating before quantity calculation (only for qty of 1) and proper price component is added to line item price.
The solution I've tried was to divide calculated discount (0.2*X/n) but the result calculated for quatity 3 or 6 or 9 is inaccurate (wrong, decimal number).
Is there a hook or other solution that can allow me to "return" the part of discount that should not be applied, or am I simply missing something and there is a more natural way to achieve what I described (for example,  the order discount rule)?

You should be able to do this out of the box if you have the Commerce Discount Extra module installed. The offer type to use is Per-quantity product discount (% off). This offer type (and the other per-quantity offer types) was created to support BOGO style offers (buy 1, get 1 free), but we developed them to support any type of discount for any number of matching products.

In your case, you'd set the "Buy #" to 1 and the "Get up to #" to a very high number... whatever you consider reasonable for the quantity you'd expect to discount. This will result in the creation of a new discount line item.

Note that the pattern for matching products will be SKU based or product category based.


I need a starting pointo to write a Views Form handler to show a Bulk Operation view field in each row instead of a single button? I have a view with a VBO field to execute a bulk operation (Get Vouchers) over nodes.

Each row has a radiobutton (I need a single selection), once you select a node you click the button "Get Vouchers" to execute the bulk operation. So far so good.

I need to show a button "Get Vouchers" in each row instead like you see in the capture below.

As Bojan Zivanovic said I need to write a  Views Form handler but I need starting pointo to write it.

VBO doesn't support that.
Furthermore, in that case you probably don't even need VBO, just write a custom Views Form handler that shows the button in each row.


Any working techniques or examples for a multistep AJAX enabled node form There's an AJAX enabled multistep form in the examples module and another in Chaos Tools (ctools_ajax_sample.module) In both cases the form is built in the function and doesn't use the default core node form.

Closer to what I'm after is a multistep node form using hook_form_FORM_ID_alter() but this one isn't AJAX.

Is it possible to use hook_form_alter() to create a multistep node form that is AJAX enabled, or should I build my multistep form independently, then use drupal_form_submit() or a new node object to save the data?

Drupal 7

I think trying to use multistep, ajax and the core node form may be quite tricky. I am not going to say impossible, but I think it would be a lot of work.

I would think using a custom form and saving the node as you suggest may be easier, what you'll loose with this is the flexibility of having it integrated, so if you add a new field to the node, you will need to change your form.


What do Contextual Filters filter against? I've been banging my head against a wall trying to understand contextual filters for about 6 months now so I thought I'd give up and finally ask. Most recently I read this article on cofiguring contextual filters, which renewed my confusion and frustration on this topic.
Normally in query or procedural languages when you filter something, you specify 2 or 3 things;

The value to filter (e.g. "blonde")
The place to look for the values (e.g. the "hair color" column)
Optionally, the operator to use.

My understanding is that contextual filters only use the "equal to" operator, so I'll leave out 3.
For example, if I wanted to filter a nodes table on all nodes whose value in the title column is equal to the contents of the my_title variable, then in SQL I'd write something like this;
SELECT * FROM nodes WHERE title = @my_title

There's a left hand side (title) and right hand side (my_title). But in the Contextual views section of the view I can only pick the dynamic value to check against (the equivalent of my_title) but where do I pick what I'm actually filtering on (ie. the title column)?

As far as I can tell this is telling the filter to filter on the ID of the current page. Which is fine, but what am I filtering? What are the left and right hand operators to the filtering operation?

Generally speaking, a view is used to show data for a list of entities. View filters are used to select (or filter) which entities are handled by the view; contextual filters are used to select the entities basing on the values passed in the URL.
For example, the Files view that comes with Drupal 8 has two pages: one whose path is /admin/content/files and one whose path is /admin/content/files/usage/%.

The second page shows data (the entity label and the entity type for the entity containing a reference to the file; the module managing the file relationship; the number of times the file is used by the entity) for the file whose ID is passed in the view path.

When I visit /admin/content/files/usage/3 on the test site I created, the view shows the following data.

On /admin/content/files/usage/2, the view shows the following data.

Using as another example a default view that is already enabled on /admin/structure/views, the Taxonomy term view has a page shown on /taxonomy/term/% which uses the Content: Has taxonomy term ID contextual filter.

It shows all the nodes using the taxonomy term whose ID is passed in the URL. In the test site I am using, /taxonomy/term/1 shows all the nodes using the taxonomy term whose ID is 1 (the test taxonomy term), while /taxonomy/term/2 shows all the nodes using the taxonomy term whose ID is 2 (the view taxonomy term).

Contextual filters are still filters, as they select (or filter) the entities from which the data is taken. The difference is that their values are passed from the view URL, not from a form like the filters set in the Filter criteria section.
The number of entities from which the data is taken and what entities are handled by the contextual filter is hard-coded in the class implementing the contextual filter: Content: Has taxonomy term ID selects all the nodes using the taxonomy term whose ID is equal to the value passed in the URL, which could be zero or more than one node, while Content: ID selects only the node whose ID is passed in the URL; User: Created selects all the user accounts that have been created at the time passed in the URL.
The category of the contextual filter (another value set by the the class implementing the contextual filter), which is shown in the contextual filter name, helps to understand which entities a contextual filter selects: Content: Has taxonomy term ID and Content: ID select nodes, while User: Created selects users.


How to link to live chat TawkTo module pop up window with Drupal 7? I have Tawkto module installed, and I want to create link on my main menu for:

"Live Chat"

The link is:

  <a href="javascript:void(Tawk_API.toggle())"> Click to Chat </a>

Now this works fine on static HTML pages, but when I paste it in field for main menu, it doesn't work.

I've tried:

 /javascript:void(Tawk_API.toggle())

And:

 javascript:void(Tawk_API.toggle())

How can I do this?

The site with Livechat is:

www.vuxi.com

You can easily achieve this by using Void Menu module.

Download & Install Void Menu module.
Go to http://www.yoursite.com/admin/config/user-interface/void_menu
Set javascript:void(Tawk_API.toggle()) as value for HTML value for <void2>
Then go to main menu configuration and set menu Path as <void2>


is it possible to have multiple access callback for a menu item I am trying to add access callback to already existing access callback for a menu item.

For eg,

path = [node/nid/edit] with access callback 'AC1'.

Now is it possible for us to add another access callback to the existing AC1? I am thinking of hook menu alter but it wont overwrite the AC1.

No, it isn't. Drupal wouldn't know how to treat contradictory results*.

On the other hand, nothing stops you from calling original function inside your own. If you are unsure what is it, copy it's name to access arguments and use it inside your callback. Don't forget to back up original access arguments in sub array, if needed.

* Or rather Drupal devs would need to agree how to treat them, and have a will to bother at all.


Trying return array as page content I'm working on a module in Drupal 7.  I have three different forms set up with hook_form.  I would like to display the three forms on one page along with some html to organize the forms and apply some css to change the look a little bit.  What I have right now is:
  function floormap_setup_page() {
    $info[0] = '
';

    $info[0] .= '
';
    $info[0] .= '
';
    $floormap_options = get_floormap_options();
    $floormap_list = '';
    foreach ($floormap_options['name'] as $key => $value){
        $span_delete = ' ' . t('Remove Floor Map') . ' ';
        $span_default = ' ' . t('Make Default') . ' ';

        $floormap_list .= '
' . $value . $span_default . $span_delete . '
';
        }
    $info[0] .= $floormap_list;
    $info[0] .= '
';
    $info[0] .= '
';

    $info[0] .= '
';
    $info[1] = drupal_get_form('setup_cameras_form');
    $info[2] = '
';

    $info[2] .= '
';
    $info[3] = drupal_get_form('set_expectations_form');
    $info[4] = '
';

    $info[4] .= '
';
    $info[4] .= '
';

    $info[4] .= '
';
  return $info;
}

Doing this displays the page how I want it, the only problem is that I get a bunch of errors along with it..
The errors look like this:

Warning: Illegal string offset '#children' in drupal_render() (line
5887 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line
5897 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#children' in drupal_render() (line
5935 of /var/www/app.local.nucloudglobal.com/includes/common.inc).
Warning: Illegal string offset '#printed' in drupal_render() (line
5942 of /var/www/app.local.nucloudglobal.com/includes/common.inc).

The entire set of errors repeats for each item in the $info array.

Render arrays look like this:

$build = array(
  '#prefix' => '
',
  '#suffix' => '
',
  'select_floormap' => array(
    '#markup' => '
Markup for the first bit
',
  ),
  // drupal_get_form() returns a render array.
  'setup_cameras_form' => drupal_get_form('setup_cameras_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'expectation_form' => drupal_get_form('set_expectations_form') + array(
    '#prefix' => '
',
    '#suffix' => '
',
  ),
  'new_floormap' => array(
    '#markup' => '

',
  ),
);

See the render array docs and What are "#" properties? for a bit more explanation.


How to disable the number that the Email Registration module puts on peoples username on registration I'm working with the email registration module and everywhere I look it says that it just uses everything before the @ sign for the username. However it adds and underscore and some number to every username. I'm not very familiar with php so if someone could tell me to disable this it would be much appreciated.

I have figured out my own problem. The module has a double fail safe for there not being duplicate usernames. Every time a new account is created it adds the uid to the end of the username so that there would be no duplicates, but if there was still a duplicate it will append a 1 or 2 on the end. Since the odds of there being 2 identical usernames from emails I am just commenting out where it adds the uid and going with just the appending a number if it ever does happen. Here is the code I commented out:

/* 070715 AS commented this out so the user id is not concatenated to the end of the user name,
this is just guaranteeing that no 2 people have the same username which has odds so small
we aren't going to worry about it.
  if (!empty($uid)) {
    // Put uid on the end of the name.
    $name = $name . '_' . $uid;
  }*/


Redirect to home after NODE_ACCESS_DENY My D7 customer uses the Workbench suite of modules to use taxonomy to allow fine-grained access to nodes successfully. But with a large amount of data to manage, sometimes they want to unpublish a node for the time being while keeping the data available in case they want to publish again. In Workbench, I've set up an "Archived" option which successfully renders that content unavailable to anonymous users. So when anonymous users visit that node, workbench, using hook_node_access() renders that node to NODE_ACCESS_DENY and it appears Drupal takes over and redirects the user to /user. That's good, but the customer wants to redirect back to root if they are anonymous.
I thought about modifying Workbench using their API but it seems to be after stepping through how Drupal handles the menu_execute_handler() that the redirection to /user occurs. I need workbench to return the DENY so I can use that as one condition to dynamically alter how Drupal renders the view in a DENY situation. But I haven't found which part of core handles this redirection.
Hunting through searches I found this suggestion which suggests to handle all 403s.

function my_module_menu() {
  $items['403redirect'] = array(
    'page callback' => 'mymodule_unpublished_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    );
return $items;
}

function mymodule_unpublished_redirect() {
    if (<TRUE>) {
        header('location:'. url('/', array('absolute' => TRUE)), TRUE, 302);
    }
}

But when visiting the node that is "Archived" redirects to /user which suggests that this function is ignored at this point. So how should I alter this redirect?

The idea of creating a menu entry to redirect in the case of a 403 is fine, except that you need to configure the core handler to point to it, which is the element missing from your question (it's mentioned in the comment you linked to).

Once you have defined your menu entry go to Administer > Site Configuration > Error Reporting and set the value of the 403 page to the corresponding path.

Now the page callback for your menu entry will be invoked whenever there is access denied, so you can supply the appropriate logic for your needs.


Alter views limit using hook_views_query_alter I've used display specified number of items for set limit in views.
I want to change limit and also display all items using hook_views_query_alter().
I've tried this:

function test_views_query_alter(&$view, &$query) {
  if ($view->name == 'sample') {
    $query->set_limit(20);
    //~ $view->set_items_per_page(20);
  }
}

But i've no luck. How to solve this?

Try using the following:

function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
    $view->set_items_per_page(2);
}


Prevent comments containing html links from beeing validated Seems very simple and I thought a module for that would be easy to find but no..
I've got a website that's beeing infested by spambots in node comments.

You're probably going to tell to disable full HTML input format, but this doesn't block comments, it just stops the links from linking; but the pollution is still there..

My normal users usually don't post any links. When I say links I mean html links:

Blah

So all I want to do is block all comments containing one or more of these html links.

I found blockanonymouslinks but this seems to only work for anonymous users. My spammers are logged-in users.

Any help would be much appreciated. Thanks!

Why can't you go for Mollom

  Mollom may block a post outright if it is from a known spammer. If
  Mollom is unsure how to classify a post, it may require the completion
  of a CAPTCHA to accept the post. Posts that do not match a "spammy"
  text pattern and do not originate from known spammers are accepted
  without the need to complete a CAPTCHA. Essentially, Mollom acts as a
  proactive content moderator that is on the job 24 hours a day, 7 days
  a week.


How to get map widget for location selection with Location / GMap I have GMap and Location modules set up and working. I have a working API key. The node with the location field can store long/lat or address data which I am using to populate a view. All of this works. The only problem I am facing is that I want the node creation form to use the GMap widget, so that users can click the map to populate the location field. I cannot, for the life of me, figure out how to enable this feature. I've checked everywhere that I can think of- any help is appreciated.

Have you checked out the Geolocation Field Module? It works with the Google Maps Api v3 and does exactly what you are trying to do. You add the map as a field/widget within your content-type. The Field stores lat/lon values.


Adding the year to the date on the blogs So, I've gone through making a view called BlogPage and a content-type of BlogEntry probably ten times now. I've created both in the simplest ways I can, and I've tried to narrow down what is causing my page to look the way it does, and I think it must be my theme. I am using the Visia theme I have purchased.

Simply, I've created the view, content of type blog-entry, newest first.

I've also added: Sort Criteria: Content: Post Date(desc).

I do love the look of the blog, but the year is not listed in the date of posting. Is there any way to do this? Is this a setting I can't find? Is this being caused by my theme?

UPDATE:

I've tried using the "Fields" option, but I can't find the "Date Format" option. This is the screen I have:

Change the date format in Regional and Language Settings to match your preference:

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

Then (assuming you are displaying fields rather than full/teaser nodes) select the date format you require from by editing the field settings in views

And specifying which of the predefined (or custom) date formats you would like to use:


Aliases stop working after composer install We have added some drush aliases for a multi-site project, the aliases were converted from the previous syntax to the Drush 9 syntax (.yml files).

I went over the documentation, and also saw the previous issues, notes and changes on this GitHub issue.

For some reason the aliases didn't work inside $ROOT/../drush/sites as documented, but did work inside $ROOT/drush/sites, and I also had to use the format of [site].alias.yml and not [site].site.yml as on the documentation.

Another thing is that @greg-1-anderson wrote on his comment that

  Only ~/.drush/sites et. al. are searched now.

So now I am really lost between the documentation, the comments, and the aliases that worked last week and were broken now after composer install.

Can someone please tell me what am I missing here?

** I've also tried to place the aliases in ~/.drush/sites/ (which didn't work).

Drush has undergone some change in behavior to simplify the implementation and increase maintainability ahead of the stable release.

Rename [site].alias.yml aliases to [site].site.yml
Spit apart [sites].aliases.yml (no longer supported) into multiple [site].site.yml files
Run drush init if you would like to maintain global alias files.

If $ROOT/../drush/sites is not working, perhaps you do not have a Composer-managed site. The actual supported locations for aliases is __DRUPAL_ROOT__/drush/sites and __PROJECT_ROOT__/drush/sites. The project root is where the composer.json file is located, which is usually at $ROOT/... It might be clearer if the documentation were updated to describe the supported locations in terms of the Drupal root and Project root, as this is now the basis for finding these directories.


How to build a link to a field_ui form? Given an entity type id of a fieldable entity type, a bundle name, and a view mode name, how do I construct a url to the respective field_ui form where this view mode can be edited?

The patterns for the route name seem to be:

entity.entity_view_display.ENTITY_TYPE_ID.view_mode
entity.entity_view_display.ENTITY_TYPE_ID.default

But it seems the parameters have custom names, e.g. /admin/structure/types/manage/{node_type}/display/{view_mode_name}, here the bundle parameter is called node_type.

Is there a generic way to build such urls to field_ui pages for any entity type?

After searching in the core files I found the pattern, see the example below:

use Drupal\Core\Url;
// The entity type can be 'node'.
$entity_type = 'taxonomy_term';

// Find the bundle entity type, e.g. 'node_type' or .
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $etm */
$etm = \Drupal::service('entity_type.manager');
$bundle_entity_type = $etm->getDefinition($entity_type)->getBundleEntityType();

if (NULL === $bundle_entity_type) {
  // Not clear what to do in this case.
  return NULL;
}

// The bundle can be 'article'.
$bundle = 'tags';
// The route, see that the $entity_type variable is used.
$route = "entity.entity_view_display.$entity_type.view_mode";
// The view mode can be 'teaser'.
$view_mode = 'full';
$a = Url::fromRoute($route, [$bundle_entity_type => $bundle, 'view_mode_name' => $view_mode])->toString();
// To use dpm() you need the Devel module.
dpm($a);


Two levels of options in add to cart form I am working with a project of sofas. Clients can choose the size and the fabric. In each fabric there are several colours.
What I need is that the client chooses the fabric and then the form shows the colors of the selected fabric so the cliente can choose too.
Is that posible?

This is not how Drupal Commerce normally works w/ attributes - you typically define all of the possible variants as SKUs, associate them all together on the Add to Cart form, and show a form with both attribute select lists shown at once. You can alter that form to your heart's content, though, hiding one select list until another is adjusted - but note that Drupal Commerce also doesn't support an attribute not having a selection out of the box. This is a technical limitation of how the form is designed to work, but there is an open issue in the queue trying to support that.


Form alter in a specific content type how can i alter/inject a form in a specific content type. I'm developing a module (product list/shopping cart) to insert a form after the body of a specific content type but right now it's showing up in all the existing content types.

The module was not initially developed by me so i'm having a bit of trouble picking up from where it was left…

Here is the part i think is relevant:

function ftf_product_form_node_form_alter(&$form, $form_state) {

  $products = db_select('ftf_product')->fields(NULL, array('pid', 'nid', 'name', 'font_ref', 'description', 'app', 'web', 'desktop',  'avangate_desktop', 'avangate_web', 'avangate_app'))->condition('nid', $form['nid']['#value'], '=');
  $result = $products->execute();
  foreach ($result as $record) {
    $defaults[] = $record;
  }

  if(empty($form_state['num_products'])) {
    $results = $products->countQuery()->execute()->fetchField();
    $form_state['num_products'] = $results;

    if($form_state['num_products']  == 0) {
      $form_state['num_products'] = 1;
    }
  }

  $form['products'] = array(
    '#type' => 'fieldset',
    '#title' => t('Typeface products'),
    '#collapsible' => TRUE,
    '#collapsed' => (($defaults[$form_state['num_products']-1]->name && !$_SESSION["collapse_typeface_product"])?TRUE:FALSE),
    '#weight' => 5,
    '#tree' => TRUE,
    '#attributes' => array('class' => array('container-inline')),
    '#prefix' => '

&nbsp;
',
    '#suffix' => '

&nbsp;
',
    '#description' => t('
Create, edit and delete products here. To add or edit Typeface Price Factors please visit the admin section.

'),
  );

function ftf_product_form_node_form_alter(&$form, $form_state) {

  if($form['#node']->type == 'YOUR_NODE_TYPE'){
    $products = db_select('ftf_product')->fields(NULL, array('pid', 'nid', 'name', 'font_ref', 'description', 'app', 'web', 'desktop',  'avangate_desktop', 'avangate_web', 'avangate_app'))->condition('nid', $form['nid']['#value'], '=');
    $result = $products->execute();
    foreach ($result as $record) {
      $defaults[] = $record;
    }

    if(empty($form_state['num_products'])) {
      $results = $products->countQuery()->execute()->fetchField();
      $form_state['num_products'] = $results;

      if($form_state['num_products']  == 0) {
        $form_state['num_products'] = 1;
      }
    }

    $form['products'] = array(
      '#type' => 'fieldset',
      '#title' => t('Typeface products'),
      '#collapsible' => TRUE,
      '#collapsed' => (($defaults[$form_state['num_products']-1]->name && !$_SESSION["collapse_typeface_product"])?TRUE:FALSE),
      '#weight' => 5,
      '#tree' => TRUE,
      '#attributes' => array('class' => array('container-inline')),
      '#prefix' => '

&nbsp;
',
      '#suffix' => '

&nbsp;
',
      '#description' => t('
Create, edit and delete products here. To add or edit Typeface Price Factors please visit the admin section.

'),
    );
  }
}


Force comment form to show I was trying to make my comments form show on a node type that has gallery assist but for some reason it doesnt have any options to change the value to make it show.

is there a module or some sort of way using hook form alter to force the default comments form to show on a node type?

You should be able to go into the Edit Content type form simply turn on comments.  Are you sure the option is not there?


How to programmatically submit a form that has a file-field using drupal_form_submit()? I'm working to allow the submission of an existing form via REST using the Services module and drupal_form_submit(). Though this is reasonably routine, the form in question takes a file-upload which is a required field.

To avoid embedding extra logic in the form itself to handle files differently under programmatic submission than under manual submission, is there a trick for getting Drupal to accept a file submitted "headlessly" via REST?

Most of this is not relevant to the answer, but for completeness, here's how I'm set up:

function mymodule_my_resource_create($data) {
    $form_state = array();
    $form_state['values'] = $data + form_state_defaults();
    drupal_form_submit('mymodule_form',$form_state);

    $errors = form_get_errors();
    $status = '200 OK';
    if (!empty($errors)) {
        $status = '400 Bad Request - submission caused errors';
    }
    drupal_add_http_header('status',$status);

    return (object)array(
        'message' => $status,
        'errors' => $errors,
    );
}

function mymodule_form($form,&$form_state) {
    return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#title' => 'Spreadsheet file',
            // '#required' => 1,
            // ^ there have been issues with this since 4.x...
            // https://www.drupal.org/node/59750
            // so this is done manually in the '#validate' function
        ),
        'reason' => array(
            '#type' => 'textfield',
            '#title' => 'Why file is being submitted',
            '#required' => 1,
        ),
        'submit' => array(
            '#value' => 'Submit',
            '#type' => 'submit',
            '#validate' => array('mymodule_form_validate_upload'),
        ),
    );
}

function mymodule_form_validate_upload($form,&$form_state) {
    if (!isset($_FILES['files']['name'] || !isset($_FILES['files']['name']['spreadsheet'])) {
        form_set_error('spreadsheet','File must be provided');
    }
}

function mymodule_services_resources() {
    return array(
        'my_resource' => array(
            'create' => array(
                'callback' => 'mymodule_my_resource_create'
                'args' => array(
                    'name' => 'post_data',
                    'type' => 'struct',
                    'description' => "Should match contents of $form_state['values'] when submitting through the UI.",
                    'source' => 'data',
                    'optional' => FALSE,
                ),
            ),
        ),
    );
}

function mymodule_actools_plugin_api($owner,$api) {
    if ($owner=='services' && $api=='services') {
        return array(
            'version' => 3,
            'file' => 'mymodule_services.inc',
            'path' => drupal_get_path('module','wos2'),
        );
    }
}

function mymodule_default_services_endpoint() {
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE;
    $endpoint->api_version = 3;
    $endpoint->name = 'my_rest';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'my_rest';
    $endpoint->authentication = array();
    $endpoint->server_settings = array();
    $endpoint->resources = array(
        'my_resource' => array(
            'operations' => array(
                'create' => array(
                    'enabled' => '1',
                ),
            ),
        ),
    );
    $endpoint->debug = 0;
    return array($endpoint);
}

This wasn't as hard as I expected; Drupal has different handling for fields with '#type' => 'file' as opposed to other types. There are two ways of solving the problem. One is simply adjusting the request-payload, expressed here as a curl command:

curl -i \
    'https://example.com/drupal/my_rest/my_resource' \
    -H 'Accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -F "files[spreadsheet]=@my_spreadsheet.xlsx" # note the weird field-name
# This automatically uses the POST method, so Drupal reads it as a 'create'

Drupal munges file-field-names by default apparently apparently to match the file.inc code. This is stated expressly in comments:

if (!isset($element['#name'])) {
    $name = array_shift($element['#parents']);
    $element['#name'] = $name;
    if ($element['#type'] == 'file') {
        // To make it easier to handle $_FILES in file.inc, we place all
        // file fields in the 'files' array. Also, we do not support
        // nested file names.
        $element['#name'] = 'files[' . $element['#name'] . ']';
    }

If you want to API-endpoint users from the implementation shown above, the other solution is to explicitly provide a '#name' value for the file-field in question, as should be obvious:

return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#name' => 'spreadsheet_file', // <-- adding this prevents name-munging
            '#title' => 'Spreadsheet file',
            // ...

Note of course that the above might have consequences for other sections of code if the file used to be expected under the old name.


Programmatically check the checkbox of an exposed filter I need to check a checkbox on an exposed filter for a view based on the url. I can't seem to figure out how to do that. If x is detected in the url, I want to set one of the fields of an exposed filter to have the status checked="checked." It seems like that would be pretty easy, but I can't seem to figure it out.

I have tried various ways through:

hook_views_pre_view()
hook_views_pre_build()
hook_form_views_exposed_form_alter() (I feel like this should be the best way.)

I've found that I can effectively alter the results through hook_views_pre_view(), but I can't figure out how to check that freaking checkbox on the exposed filter.

Varioush failed attempts via hook_form_alter():

$form["field_intended_use_target_id"]["#default_value"] = ['357'];
$form_state->input["field_intended_use_target_id"][356] = '356';
$form['field_intended_use_target_id']['widget'][0]['value']['#default_value'] = ['357'];

Can anyone please help?

I was finally able to achieve what I need via the hook_views_pre_build() hook.

Please let me know if this is wrong or if there is a better way, but from what I can tell this is the best way to achieve this.

function module_views_pre_build(ViewExecutable $view) {
  $termId = 357;
  $view->setExposedInput(['field_name' => [$termId => $termId]]);
}


OG "Add people" username predictive searching In OG7, I have given one user the role of overseer and that role has the Administer Organic groups permissions enabled so he can administer all Organic Groups on the site.

So, for each group, when my overseer goes to Group -> Add People and he attempts to input the user name, the textfield does not predict/provide suggestions of matching user names. However, this helpful effect does happen for the site administrator.

Can anyone tell me how I can enable this user name prediction effect for my overseer role?

The permission to set is "View user profiles".


Multiple nodes in one slide using views slideshow or another module I have a slideshow using views_slideshow which displays the latest post from 4 different content types, I need the slide to show multiple contents (from different content types) in one slide, when you click next there should be another slide containing 4 nodes.

This image might explain you the scenario!

The only thing I can think of is to use like Relation to tie these things together using a relation as Slideshow Content and then a field tacked onto the relation as slide number.

You should be able to then have any number of content types -- relate them to your slideshow and define the ordering as needed that content.

To ease the generation of relating (linking) things these additional relation modules may help:

Relation Add

  Small block that allows the user to add an appropriate relation from
  an entity page to any other appropriate entities, with a generic
  autocomplete for each endpoint, and relation fields.

Relation Autoconnect

  Module allows to setup invisible widget to Relation Dummy Field. This
  widget loads information (entity type and ID) about another entity
  from arguments in the path and create relation between determined and
  newly created entity.

  For example, you can use path "node/add/story/node/22" to connect new
  story content with node number 22.

Relation Select

  This module provides a field widget for creating & editing relations.

  The selection interface is based on views. Use exposed filters to
  search for entities, & select items from the view output displayed as
  a clickable drop down list.

So the idea is you have all your content on the backend -- related via a Relation and its field to grab it for a Views Slideshow later. Some of these modules attempt to make creating that (meta-)relation with your slideshow content easier.

You might be able to use like Arrange Fields or FieldGroup to make a tab for "slideshow properies" for each of your content types that shows the Relation info in the node edit form.


Drupal 7, Rules, Convert text to date and set a date field I've some string like "11/28/2012" and i want use to populate a date field in my nodes/entity. In rules i use "set a value", select the date field and add php code:

$mydate = field_get_items(($entity_type, $entity, 'field_textdate');

$value = date('m-d-Y', $mydate);

return $value;

But when i execute the rules, i get
46.397 ms Unable to modify data "node:field-datone": Invalid data value given. Be sure it matches the required data type and format.
57.754 ms Unable to evaluate action data_set.

How can i do?

field_get_items() returns an array of items – try strtotime('m-d-Y', $mydate[0]['value']);. Also, it looks like you have an extra ( on your field_get_items call:

field_get_items((

I would recommend installing the devel module, then you can add this code anywhere you'd like and get the results printed in your messages area for quick debugging and to see what data is available to you and how it's nested:

$mydate = field_get_items($entity_type, $entity, 'field_textdate');
dpm($mydate);


How do I trigger group membership was granted for a user - Group module I try to use group module in d8.

1. I created a new group type named test

2. I added 2 group as demo with admin is default group_membership.

3. in group 1 (name okok) I edited and added new user to group.

4. When I click the add member, the site redirect to another add form:

I enter the user as normal.
then click save button.

5. The result is User was added into that group.

So, What I wonder is how to know an user:

Was added to a group.
Was removed from a group.

Because I want to call another service every time that action/event was executed. For example, I want to log in to the watchdog like:

"User A has been added into group X"
"User B has been remove from group Y"

Is there any way to trigger that action/event in code.

Thanks for all your helps.

as @Jaypan suggested to me,
I used hook_ENTITY_TYPE_insert()
so my code is:
function hook_group_content_insert(GroupContentInterface $group_content) {
  if ($group_content->hasField('entity_id')
    && !$group_content->get('entity_id')->isEmpty()) {
    $users = $group_content->get('entity_id')->referencedEntities();
    $user = reset($users);
    if ($user instanceof UserInterface) {
      // Do your code here.
    }
  }
}


Can I use Corolla theme as a fixed width layout? I have a fresh install of D7 and have downloaded Corolla theme.

I go into appearance and set the page width from 100% to 944px, which works fine, but, whenever I resize the browser window, the first sidebar breaks and drops to the left of the page. I would like it to just display a horizontal scrollbar.

Is there anyway to modify this theme to do this?

Though I have not used that theme myself, it indicates on the project page that it's 'Responsive' so the sidebar is doing what its supposed to do when the browser is resized to a narrower width -- it's using a Media Query. I tried the demo and this was my experience as well. Though that might have seemed odd in the old days, now it's actually what you want for the site to work with multiple devices and screen widths. You will note that if you resize even narrower, the other sidebar goes underneath as well and this is as expected.

From the project page:

  "The new 7.x-2.x version is a subtheme of Adaptivetheme which includes
  a powerful new responsive layout engine with full support for mobile
  devices."

You may want to take a look at this for a primer on Responsive Design: http://www.alistapart.com/articles/responsive-web-design/


Instant search and ajax events I want to make a search field for a form that automatically refreshes the form as you type with the answers that match the filter, like google does it.

I looked at https://api.drupal.org/api/drupal/includes!ajax.inc/group/ajax/7 and the examples module for the ajax related stuff but I can't find all the possible ajax events listed. The only ones I know of are blur, keydown and keyup.

I thought keyup would do the trick but every time I type a letter in the textfield the ajax event will disable the textfield, only to let me type another letter after the ajax callback is finished. I can't use this.

I want something like the autocomplete Drupal incorporates, it doesn't block the textfield at every typed letter, but as far as I know the native autocomplete uses a combination of ajax events.

Can someone please give me an idea of how I can accomplish such a task?

Edit:
Just to be clear, I'm not looking to autocomplete suggestions, I know how to do that, I want to update a paged table of results with each letter typed.

Take a look at Drupal Instant Search, or Finder. Even if it isn't exactly what you want, it should be a good starting point.

Drupal Instant Search:

  It works as follows: The url for the instant is at /instant The user
  types his search word, once he finishes typing (javascript keyup) the
  module automatically submits the search word and returns the search
  results. The search results are displayed at the same page of the
  instant search.

  Instant search is also integrated with Top searches module. if Top
  searches module exists, the instant search auto-completes top search
  words.

Finder:

CHECK MODULE FIRST DUE TO THIS WARNING:

  This module is unsupported due to a security issue the maintainer
  didn’t fix.


“Realname” module is not creating “pretty URLs” for new users? I’m working on a site which I’ve taken over the development from a former employee. He has installed the module realname which, as I understand, should enable the function that a user URL is not the cryptic ID but the users first+last name, so the URL might look something like this:   www.mydomain.com/user/firstname-lastname

It work for most of the users but I’ve discovered that some of the users (especially new users) still uses the ID in the URL, so it become something like www.mydomain.com/user/eyyrdctxeec and that mess a lot of things up.

I’m suspecting that it might has something to do with the module and it only “recalculate” the names in some time interval, maybe by the CRON jobs. But I want it to create that member URL when a new user has signed up to the page.

Has anyone experienced that before and might have a solution? As I said, it isn’t me that has initially created this site so I don’t have a clear overview if the original developer have done some customization or other configuration – I’ve search to solve the problem but with no luck.

Any help or suggestions would be appreciated.

Sincere
- Mestika

congratulations on inheriting someone else's work, it was really well documented, right? ;-)

All joking aside, the realname module is used to display alternate names instead of the username.

To get the /user/firstname-lastname urls you would use the pathauto module and configure the "pattern" accordingly. Instead of "user/..." you might want to use the "member/..." to keep things a bit separated. I bet pathauto is already used on your site.

Just change the pattern, delete all user paths and re-create them in a batch.

I also suggest you check all the additionally installed modules and read up on what they are supposed to do. No worries, you'll learn quickly, just use this site a lot. And try to improve your "accept rate" a bit to get more answers ;-)


How can I invoke hook function after the block is loaded? I have created a view with content types in my Drupal 8 and for this view page I have created a customised filter. The view page is located in sites/mysite/modules/view/config/install

And the customised filter is located in sites/mysite/modules/filter/src/Plugin/Block

The issue for me is that I want to change a title of the filter in hook function in view.module . But it is loaded before the FilterBlock. How can I specify the order of the invoked files?

To change the order of which module's hook will fire first when more than one module implements the same hook you can use hook_module_implements_alter(). It was created for exactly this kind of situation.


How to alter sort handler to keep existing order intact in views I created a views page using foo plugin.When a user visit the page the city and Clinic/Hospital columns by default are being rendered alphabetically (ASC) as in below screenshot.

EDIT: Let's say for example. City is Bangalore and only for Bangalore Clinic/Hospital(C/H) column is alphabetically ordered(say Hospitals A,B,C,D...).Then user clicks on City head,then for Bangalore C/H column is alphabetically disordered(ex B,D,C,H...) but records are still correct to Bangalore city means those clinic/hospitals are located in Bangalore .Same goes for other cities too.What I want is C/H col should be ordered as earlier (alphabetical) City by City but no matter how city is ordered.

When user clicks on City head (which is sortable),the order of Clinic/Hospital goes heywire (no more alphabetical order) like below image:

Problem: How can I make my Clinic/Hospital order intact even after user clicks on City head.

Below is my views configuration:

I am using Drupal 7.41 and views 3.0

Tried so far:

function mymodule_views_query_alter(&$view, &$query) {
   if($view->name == 'list_of_doctors' && $view->current_display == 'page_1' && count($query->orderby) == 1)
    {

        $query->orderby[1] = array(
             'field' => 'field_data_field_clinic_hospital_field_clinic_hospital_value',
             'direction' => 'ASC',
            );
    }
 }

}

But after clicking City head,whole table vanishes.

As I understand you want to be able to use a secondary sort after overriding the default sort by clicking on a column header.

This can be achieved from the front-end using jQuery plugin TableSorter as described here:
https://drupal.stackexchange.com/a/125188/22915

Note this won't work for views with pagination.

It can also be achieved with some custom PHP code. Add the following to a custom module and change the CAPITALIZED words accordingly.

/**
 * Implements hook_views_query_alter().
 */
function YOUR_MODULE_NAME_views_query_alter(&$view, &$query) {
  if ($view->name === 'YOUR_VIEWS_NAME' && $view->current_display === 'YOUR_VIEWS_DISPLAY_NAME' && count($query->orderby) == 1) {
    $query->orderby[1] = array(
      'field' => 'YOUR_SECONDARY_SORT_FIELD',
      'direction' => 'ASC',
    );
  }
}

This code snippet will make sure that, no matter what column you use as main sorting, you always use a certain field as secondary sort. In your case this would be the Clinic/Hospital field (use system name in code).

Note: if the secondary sort field is not a sortable column, you can't use the query alias. So YOUR_SECONDARY_SORT_FIELD needs to be something like: 'field_data_field_name.field_name_value' instead of 'field_data_field_name_field_name_value'.


How can I render an URL path from a custom route? In my module.routing.yml (and using D8), I have a module_new route associated with the /module/name path.

I want to render this path in my module. How can I show http://example.org/module/name on a page?

Twig

You can use the route name in the twig function url():

{{ 'View my module content'|t }}

Controller

Or you can do the same in a controller:

use Drupal\Core\Url;

  $url = Url::fromRoute('module_new', [], ['absolute' => TRUE]);

  // get the path as string (not recommended)
  $path = $url->toString;

  // better put the complete url object in a render array and let the template render it
  $build['link'] = [
   '#title' => $this->t('My module content'),
   '#type' => 'link',
   '#url' => $url,
  ];

  return $build;


How do I let users view, edit or delete their own contents? I am working on a website where there will be users publishing contents.

How can I restrict users from accessing other users' contents and only able to view, edit or delete their own contents?

You can set these permissions at People > Permissions. Take a look at the 'Node' section. Also, a very practical module for specific cases is Field Permissions.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.


Webform - Replace Form title with Node title I'm working on a Job Portal where-in i created a content-type for job listing and a Job Application Webform. I need to provide a link on the job node which will be linked to the webform and upon submission,the title of job listing node will be sent as the webform title(Editable or uneditable). And in the Webform listing, the form should have the title as that of the Job node from which it is applied.

I like to know, what are the ways with which this can be achieved

In CCK there is a module called Field Reference. Enable that an you can create a field reference field, which you can link to a specific field in another node.


Conflicting drupal role ids I know that you can create user programtically and set a role:

 $roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      4 => 'Member');
$fields = array(
    'name' => $username,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => $email,
    'roles' => $roles,
    );
  //the first parameter is left blank so a new user is created
  $account = user_save('', $fields);

and this code works fine.
However, I am going to be porting this code to different sites (and back to mine, when I need to do testing on my dev site), and I'm trying to figure out if I'm going to have role id conflicts. Instead of using the above code, and I do the following instead?

$roles = array(
      DRUPAL_AUTHENTICATED_RID => 'authenticated user',
      "site-member" => 'Member');

and thereby never having to worry that I am overwriting a role?

One way can be to get role id from role name than use role, since we fetch the rid dynamically so there is no chance of conflict. An example will go like

// Helper function to get user role by username.
function get_role_by_name($name) {
  $roles = user_roles();
  return array_search($name, $roles);
}

// Role ID for Member role
$member_rid =  get_role_by_name("Member");

// Use Rid now
$roles = array(
$member_rid => 'Member');


Programmatically add cache max-age I tried setting the cache max-age to 0 in hook_views_pre_view, in hook_views_pre_build and in hook_views_query_alter but it just doesn't work.

Eg:

function my_module_views_pre_build(ViewExecutable $view) {
  $view->element['#cache']['max-age'] = 0;
}

The views caches the response until the caches are cleared.

I need to do this programatically because I need to force the views to not cache the results for more than 10 minutes based on some conditions.

Later Edit: The issue discussed in "How to use max-age" does not apply in my case. I know how to use cache tags, contexts and max-age for pages/rendered arrays and they work just fine. But for views I can't make them work.

Views has a cache plugin for no caching which you can configure in UI. Better use this method, setting a cache max-age in a hook might not be enough to disable all caching in a view. Also you can't control traffic from anonymous users by this. If you have dynamic views you want to deliver to anonymous users uninstall the Internal Page Cache and set the Cache-Control headers in /admin/config/development/performance accordingly.


Created a module that has a form: How do I display on a page? I just created a module called member_survey that just contains a simple information gathering form.

What I'd like to do is create a page with the url www.example.com/member-survey that contains the survey that i just created.

I can't for the life of me figure out how to do this. Can anyone point me in the right direction?

You should use hook_menu().

function member_survey_menu() {
  $items['member-survey'] = array(
    'title' => 'Your title',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('your_form_function'),
    'access arguments' => array('access content'),
  );
  return $items;
}

Replace your_form_function with the function that generates the form.

Replace array('access content') with your desired permissions.

You can also use the webform module instead of writing a module.


Editing CSS without module/plugin I am working on a website developed by a previous developer so I am studying how I can edit the style without source code or any extension... is there any possibility to do it?

No, that's not possible; Drupal doesn't have an interface for editing CSS out of the box.

You'll either need to get into the code, or install/develop a module like CSS Editor.


Problem when downloading large files using Storage module I'm using the Storage module to managed uploads on my website. I'm hosted on EC2, some content is sent to S3, and some stays on EC2.

Logged in users are able to transfer files to each other. One user uploads the file, and the other goes to download it.

The files that are causing problems are stocked on EC2.

A user is able to upload a large file (4 gb for example), to the server, but when someone tries to download the file, they get a file of 0b.

I checked via FTP and the file is there and complete (i downloaded it and opened it).

When moving the file to another directory (/default/files/file.zip), it works. If it is in the "/system/storage/serve/359/file.zip" it doesn't work.

--- EDIT ---

Forgot to mention that it DOES NOT happen with small files.

--- EDIT ---

Does anyone has any suggestion?

Thanks !

I would have preferred to put this into a comment, but I don't have enough rep points yet. :/

First, a few questions: What version of PHP are you using?  Does the same thing happen with small files?  Are you using symlinks?  Do your server logs show anything suspicious?

I am trying to fix a similar problem on one of my sites.  PHP 5.4 works fine, but 5.5 is choking when trying to interact with the file, which happens to be linked into a mounted filesystem.  They are on different versions of Ubuntu as well, so I am currently trying to figure out if it is a Linux kernel bug, a PHP bug, or a PEBKAC error.