Where to write public, common, utility functions in Drupal? At times you have to write little utility functions which will have a general scope (not restricted to the module you are working on) so that it can be called from anywhere in the project.

I know I can write it anywhere and include the php file from the caller, but is there a convention followed in Drupal?

For e.g. I am working on xyz.module which does xyz thing which will have a silly

function startsWith($haystack, $needle) // case-insensitive startsWith
{
    return strncasecmp($haystack, $needle, strlen($needle)) === 0;
}

Where shall I write that function?

As many API modules do, you can place your global helper functions within a dedicated module. (I'll be using MYHELPERMODULE in the following example.)

You then should follow the naming conventions:

function MYHELPERMODULE_startswith($needle, $haystack) {
  // do your magic
}

You can call this function from within all other modules, as long as your helper module is active. To assure it's active, add your helper module as dependency to the .info file of the module that is using the helper function:

dependencies[] = MYHELPERMODULE


Access to install.php on existing installation I've created an installation profile.
Once the site is created and I return to install.php I can restart the installation profile. How can the install.php file be blocked so that the Drupal already installed message is shown?
When the standard profile is used 3 variables are set in the variable table:

install_profile     s:8:"standard";
install_task     s:4:"done";
install_time     i:1323783143;

When I look at the variables table after I run my custom installation profile only one variable is set as:

install_task    s:23:"install_profile_modules";

What's the correct way to set these variables?

The issue is caused by a module that's enabled with the installation profile using the drupal_goto function on hook_user_login.

This function ends the request, therefore the profile doesn't go to the page showing 'Visit your new site'.
It goes to the URL provided in drupal_goto instead and variables are not set because the function install_finished() was never called.


Custom Mult-Step Form remove next button I have built a Multi-Step form using forms example module as a base:

https://api.drupal.org/api/examples/form_example!form_example_wizard.inc/function/form_example_wizard/7

I have a function that takes the user-inputted location on the first form and returns data for presentation on the 2nd form. If no data if returned back from the first form I want to hide the Next button. How can I do this?

You could try something like this on the second form:

if (empty($form_state['values']['location']) {
    $form['next']['#access'] = FALSE
}


Print out $view object in custom field template I've created a custom template for a field to display in my view. Based on the view theming information, I've named the file views-view-field--at-a-glance-test--page--field-track-icon.tpl.php (the view is called at-a-glance-test, the display is a page, and the field is field_track_icon.

The sample code given for a views-view-field template has the following comments:

/**
* Variables available:
  * - $view: The view object
  * - $field: The field handler object that can process the input
  * - $row: The raw SQL result that can be used
  * - $output: The processed output that will normally be used.
**/

I want to know what all is coming through in the view object, so I tried to do print_r($view). All I get is a completely blank page - there's not even a single line displayed in the rendered source. Usually this happens if there's a PHP error somewhere - am I doing something wrong? How can I print out the full contents of the view object?

EDIT

I just looked at our php error log and saw this:

  PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted
  (tried to allocate 117789481 bytes) in
  /home/www/expo/includes/theme.inc on line 1414

So obviously the view object is enormous... how else can I see what is coming through, since I have no control over our server's memory limits?

EDIT AGAIN

Per @Clive's comment below, I tried using dvm() instead of print_r, and did get some (a ridiculous amount) of output. Given that this is a template to override the display of a single field, I really want to see just the data for that particular field. So I tried dvm($field), and ended up with literally thousands of lines of nested arrays and objects. It's not pulling in just the data for this particular field, it's displaying data for the entire view, even though I passed in the field variable.

So then I tried dvm($row->field_track_icon), and got about 100 errors (Notice: Undefined property: stdClass::$field_track_icon in include() (line 28 of /home/www/expo/sites/all/themes/bluemasters/views-view-field--at-a-glance-test--page--field-track-icon.tpl.php).) The template comments state to use $data = $row->{$field->field_alias} as the format; first, what's the difference between field and field alias? I've attached a screenshot of the taxonomy term that the field I need is attached to. The field is called field_track_icon. What is the alias? Second, do I need the curly braces?

What do I need to do to get just the data for one specific field?

Try to set the memory limit in your settings.php to something like this..

ini_set('memory_limit', '128M');

The above code will override your server php.ini settings. Take note that this may result instability of server and may attract suspension of your account.

You may need to ask your hosting support if possible.


How to display the un promoted to front page link in teaser mode contextual links? I'm trying to enhance the frontpage teaser's contextual links. On front page content we click on Configure link, and it shows Edit, Delete and Node Export by default.

I'd like to also add a Unpromote from/to frontpage link.

Is this possible? If so, how can it be achieved?

Contextual links can be added by adding a menu item (e.g. hook_menu() or hook_menu_alter()) and setting context to MENU_CONTEXT_INLINE & type to MENU_LOCAL_ACTION. For node actions, you can add a menu item to the node/% route. The nid argument can be passed through so you can execute your appropriate node frontpage toggle logic.

For example:

/**
 * implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['node/%/frontpage'] = array(
    'title' => 'Toggle Frontpage Status',
    'type' => MENU_LOCAL_ACTION,
    'context' => MENU_CONTEXT_INLINE,
    'page callback' => 'MYMODULE_toggle_frontpage',
    'page arguments' => array(1),
    'access arguments' => array('administer content'),
  );
}

function MYMODULE_toggle_frontpage($nid) {
  // @TODO: Add your $node->promote switching logic.

  // Jump back to the original page containing the context menu.
  drupal_goto(drupal_get_destination());
}


Redirect example.com to example.com/node Currently I am facing ERR_TOO_MANY_REDIRECTS problem in chrome when I try to visit example.com. Since example.com/node is working fine, I want to redirect all the traffic to example.com/node for now.

How do I achieve this ?

Do you have any redirect module enabled? Might be because of that maybe Global redirect or something.

Otherwise you can redirect your homepage to pick up example.com/node by adding the path here: Default front page: URL(admin/config/system/site-information).


form ajax forget's changes made in previous ajax callback calls Why do changes don't get saved in $form, or what is it that's overriding it?

I would like to set custom class to multiple fieldsets in an ajax callback function:

if (something) {
  $form['fieldset_01']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_02']['#attributes'] = array('class' => array('custom_class'));
}
elseif (somethingelse) {
  $form['fieldset_11']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_12']['#attributes'] = array('class' => array('custom_class'));
}

return $form;

When $form is returned, the element that I have set in this call is rendered fine, with a new CSS class but the elements I have rendered in previous calls have lost this new class, as if they were rendered with default values.

EDIT: my form creation function

function mynode_form($form, &$form_state) {

$nid = $form_state['values']['nid'];

$ajax = array(
'callback' => 'mynode_ajax',
'wrapper' => 'mynode_form',
'event' => 'change',
'method' => 'replace',
);

$node = node_load($nid);
$title = $node->field_title['und'][0]['value'];

$form = array();
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['nid'] = array(
  '#value' => $nid,
  '#type' => 'hidden',
);

$form['fieldset_0'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 0',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_0']['textfield_0'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 0?'),
  '#ajax' => $ajax,
);

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 1',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_1']['textfield_1'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 1?'),
  '#ajax' => $ajax,
);

if (isset($form_state['triggering_element']['#name'])){
  $key = $form_state['triggering_element']['#name'];
  switch($key){
    case 'textfield_0':
      $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b',   'c'));
      $form['fieldset_1']['#attributes'] = array('class' => array('a',   'b'));
    break;
  }
}
else{
  //only the first time
  $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b'));
  $form['fieldset_1']['#attributes'] = array('class' => array('a', 'b'));
}
return $form;
}

AJAX callback function is meant to only tell Drupal what to update. By design all you do in it is for one call only.

Permanent changes needs to be done in main form creation function. I usually see them done in block like that:

if (!empty($form_state['values'])) {
  //here you are supposed to use these values
}


Fetching more than id's of an entity using EntityFieldQuery I have just learnt how to use the EntityFieldQuery to make simple queries.

In the example below I fetch all the comment id's for the logged-in-user.

global $user;

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'comment')
->propertyCondition('uid', $user->uid)
->addMetaData('account', user_load(1));
$result = $query->execute();
var_dump($result);
$cids = array();
if (isset($result['comment']))
$cids = array_keys($result['comment']);

  Is it possible to get the comment body and the node id where that
  comment belongs using the way i use above?

No - you need to load the comment (comment_load()) to get property and field data attached to the results of an EFQ - its job is to load IDs only.

An alternative would be mikeytown2's EntityFieldQueryExtra class, which does allow you to attach field and property data to the results of the query.


Where this javascript included? In my Drupal site I got this error in google chrome console:

GET http://domain.com/file?mq8c07 404 (Not Found)

But I can't find where this file is included, how can I find it?

The simple way is search this URL in your codes completly , if you reach bash command prompt you can  do it by grep   command .


Automated Rules Discount I have installed 'Ubercart Discount Coupons' module and managed to add a rule to configure the automated discount. But now all the normal code type discounts have stopped working....

Only when I remove the automated discount rule the normal code discounts will works.

I am struck on the production site.

Screenshots:

I guess I figured out the problem.

This Issue was in the 'Coupon module settings'.

Solution:
1. Go to: admin/store/settings/coupon
2. Enable 'Allow multiple coupons to apply to a single order.' check-box.
3. Save.

This solved my problem.

Thanks,
Anand


How to compress external images? I load external feeds and i show thumbnails from external links.

I have big problem with Google PageInsight.

Images are not in my server, they are links from feeds. How can I compress those images from feed ?

Actually darol100 is right. Since images are not on your server you cannot compress them. But you are able to cache them localy with image cache.

See this article here
https://www.drupal.org/node/251009


How can I translate string templates in Metatag module? I use Metatag module. How can I set different string templates for each site language? Or translate these templates.

Basic internationalization support can be found in the i18n module:

  All default configurations may be translated using the
  Internationalization (i18n) module. The custom strings that are
  assigned to e.g. the "Global: Front page" configuration will show up
  in the Translate Interface admin page
  (admin/config/regional/translate/translate) and may be customized per
  language.

There exists at least 1 ongoing issue in Review still with Views, Panels and other 3rd party contrib modules and the metatags module.


Why is this if statement not working in twig? It's a bidirectional D9 site where I removed dir=rtl from my theme's html.html.twig with an if statement and it's working fine. I did that to avoid an MS browsers bug ignoring position: sticky in css if there was any dir="rtl" in either html or body tags. I did so in html.html.twig with this code:
{% if html_attributes['dir'] == 'rtl' %}

{% elseif html_attributes['dir'] == 'ltr' %}

{% endif %}

So now, when the site is in English (or any LTR lang) the html tag has a dir="ltr" attribute in it but none if the dir is rtl. That's working well.
I added the dir attribute to page.html.twig #page-warpper like this:
{% apply spaceless %}
{% if html_attributes['dir'] == 'ltr' %}

{% else %}

{% endif %}
{% endapply %}

 ......

This isn't working. Only the rtl direction is applied to the #page-wrapper regardless of the site's direction/ language. I added the spaceless filter later as I thought it might be an indentation issue but no change still.
I also tried this but not working either:
{% if html_attributes['dir'] %}

{% else %}

{% endif %}

Thank you for any views.
And sure, I did drush cr after each twig edit.

The variable html_attributes is not available in a page template. To make it available copy this code from template_preprocess_html() to your page preprocess hook:
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_preprocess_page().
 */
function mytheme_preprocess_page(&$variables) {

  $variables['html_attributes'] = new Attribute();
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
  $variables['html_attributes']['lang'] = $language_interface->getId();
  $variables['html_attributes']['dir'] = $language_interface->getDirection();

}


Show if a user is logged-in or not I want to display an array of users of my site in a view.

How do I show if a user is logged-in or offline? I can not find anything to do that in sight.

You can check $user->getLastAccessedTime() in a preprocess function and set this as a variable, for example the view at /admin/structure/views/view/who_s_online determines if someone is "online" by checking if last accessed time is within the last 15 minutes.

function mymodule_preprocess_views_view(&$variables) {

  if ($variables['view']->id() == 'my_example_view') {
    /** @var $account \Drupal\user\UserInterface */
    $account = <load up your user>

    if ($account->isAuthenticated() && time() - $account->lastAccessedTime() < 900) {
      $variables['online'] = ['#markup' => 'online'];
    }
    else {
      $variables['online'] = ['#markup' => 'not online'];
    }
  }
}

And then to use 'online', you'd need to use a custom template for views-view-my-example-view.html.twig.

If you want to check a bunch of users, it may make more sense to use a view mode and use the preprocess function for the view mode.

The main point of this answer isn't how to theme views, but how to determine "online" as best as possible using Drupal.


How to find/download latest drupal version via bash? I'm trying to pull up the latest Drupal release, and download it via a bash script.

I don't have any idea on how I can do that, except that I found out I can list the files on the FTP server, and get all the filenames containing Drupal, like so:

lynx --dump http://ftp.drupal.org/files/projects/ | awk '/http/{print $2}' | grep drupal-7 > latest.txt

How I can pull the latest version from that list, and download it?

For all your command line and script needs there is Drush. To download the latest Drupal 7 with it, you simply do

drush pm-download drupal


How can I highlight only the contents that have been never published yet in the Views? The contents always need approval of administer to be published on this site.

For example,
The contents are once unpublished by Rule module when non-adimin users update them.
And then the administer publish those contents again.

I have a node View with table style.
In this view the administer wants to find "The contents that have never been published yet" easily for example, by making them hi-lighted.

Is there any way to achieve this?

To display unpublished  content using views you  have to add "Node: Published" option as "No" under "Filters".


How to make a reservation and a booking of seminars during the Commerce checkout process? I have set up my first Drupal Commerce shop that works as it should with fixed booking ("selling") of seminars.

Now these seminars (realized as line items) must not only be booked ("sold") but must also be available for reservation. It is needed that booking and reservation has to be done during the checkout process, where only booked items must be paid.

My problem is now, that I do not know how to combine booking and reservation in one line item and also how to separate it during checkout process, as both need different information and also a variable amount of input fields, depending on number of participants.

Maybe someone can give me some hints how to do it - I am stuck at the moment ...

Your usage of the terms "booking" and "reservation" seems a bit strange to me. In the context of Drupal they are often used as synonyms of each other. I am not sure if I correctly interpret the difference you make, but I think this is crucial for you to differentiate (define?) them:

Booking = item that must be payed at checkout time.
Reservation = item that you must also be able to checkout, but you don't have to pay for it (or at least not yet).

So I think your question actually consists of 2 questions:

How to integrate this in Drupal Commerce?
How to ensure availability?

Below is what I think might help you find a possible solution.
Drupal Commerce integration
You should look at the Easy Booking distribution, to check if there is anything in it similar to what you're looking for (specific to the way this distribution uses Rooms and Drupal Commerce). If you find something, it is just a matter of reusing what's appropriate in your own site, or just use that distribution (attention: it only has a beta release so far).
Here are some more details about this distribution (quotes from its project page):

... to set up a website, that will suit all your needs in managing your own hotel, inn or hostel online.
It gives a set of options for visitors to make room reservations, contact hotel administration or just follow hotel’s newsletter to be aware of all special offers and discounts.
Easy booking profile is powered by Drupal Rooms and Drupal Commerce - widely used and popular contributed decisions, which means active maintaining and timely technical support.

Check availability
Take a look at these modules, which all have a stable (not alfa or beta only) release:

Availability Calendars (Reported installs: 2.061 sites).
MERCI (Reported installs: 441 sites).
Resource Conflict (Reported installs: 329 sites).
Simple Reservation (Reported installs: 202 sites).
Room Reservations (Reported installs: 156 sites).

I've ordered the list above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module. So do your homework to pick the right one for you.


How to set shipping price to 0 when a specific field of product is enabled or has specific value I am using Drupal Commerce 7. I need to set the shipping price to zero when a field of product is enabled/checked (for example free ship field).

I know I should use Rules and Collecting shipping rates for an order event is suitable for my job, but I really don't know how to set up a condition to check if my field is enabled or has a specific value.

I can set the free ship field widget as check box with enable/disable or select box with 2 value, whichever fits my needs. But my problem is how to set the condition according the value of product field.

Thanks for your attention

How about this: In shipping calculation rule see if can get the following conditions.

Use execute php code, check in the php if can use $commerce_order
If can then loop through all product line items in the order load them check the field value.
On basis of condition return True so implement the action or false to not.


Drupal calling "is_dir" over 4000 times? After having troubles on loading time of a very important Site I installed XHPROF and looked over the statistics to see where I can improve my code.

I found something interesting that i don´t understand. Drupal calls "is_dir" over 4000 time on nearly every request and this takes about 800ms to execute. Why is that and is there a way to speed that up?

By a loading time of two to four seconds is 800ms take a big part.

When you uninstall a module, you need to disable it first in Drupal module admin. You should then uninstall it via the "Uninstall" tab there.

The same goes for themes, disable in theme admin first.

If you for example, delete the module folder on the file system without disabling the module, Drupal will continue to search for the module in the file system, which can result, among other errors, in the issue you are experiencing.

See also: Avoid re-scanning module directory when multiple modules are missing

In answer to MPD's comment, you will need to do something like

SELECT name, filename FROM system WHERE status = 1;

and cross reference that with the modules on your file system. All enabled modules, and themes too, should be present.

There's also a function ( slightly adapted ) Martin_Dresden posted here:

https://drupal.org/node/1080330#comment-6520842

function MYMODULE_init() {

    $startingtime = microtime(true);
    $o = '
Checking for dead modules ...
';
    $result = db_select('system')
      ->fields('system', array('filename'))
      ->condition('status', '1', '=')
      ->execute();
      $n = 1;
      $m = 0;
    foreach ($result as $row) {
      $path = DRUPAL_ROOT.'/'.$row->filename;
      If (!file_exists($path)) {
          $o .= "#$n $path
";
          $m++;
      }
      $n++;
    }
    $timedif =  round(microtime(true) - $startingtime,3);
    $o .= "Total of $n active modules registered in database. $m dead entries found.
";
    $o .= 'Query Time: '.$timedif.' seconds';

    drupal_set_message($o);

}

That may help debug.


How to create a combination chart with the Charts module if some X-axis values are missing? I've been searching for a solution to my problem for a while without success so maybe someone here can help me.

I've already looked at the answer to the question about "How to combine 3 line charts in a single chart, using the Views integration of the Charts module?", but that didn't help to solve my issue.

I use the Charts module to create a chart in Views using the "Chart" display format. And I'm using Highcharts as my charting library to draw the number of "Passed" nodes (in green). I also created a chart add-on to represent the number of "Failed" nodes (in red) so that I can have multiple series in the same chart.

At this moment this is the chart that I have with the problem I will describe below:

As you can see in the table above, I have 4 different dates (Run Date and Time). The chart should show the 4 dates. Instead, it only shows 3 dates and this is why: The last date doesn't have "Passed" nodes, so the chart display (the parent) does not have that value on its axis. The chart add-on, representing the 2 Faileds on the last date, is then represented on top of the first display using the 3rd date and not the 4th, giving the error.

It seems that the x-axis values are irrelevant in this module.

The chart that I want should be something like this:

I made this chart in Excel and the difference that I see (that is giving me the wrong results in Drupal) is that I don't have a "0 Passed" or "0 Failed" but instead I have no results at all.

Is there a way to get this working correctly? I tried already many charts modules available and everyone has this problem as far as I know ...

Below is also a screenprint of my view:

Note: for the table below the chart I'm using module Views Merge Rows and it's clear that the top two dates don't show the "0 Failed" or "0 Passed" (as shown in the tabular display of my first screenprint) needed to have a correct chart displayed.

EDIT: I have found the same issue here and here. Hope it helps.

If there's need to have a solution like in the second link, i.e., construct the view in a way that both series will always have all labels, I'm open to it.

Step 1

Not sure if it's your "only" problem to get your chart right, but part of your problem is, pretty sure, that you have "holes" in your data, similar to what is detailed in Comment nr 12 of Issue nr 2052429.

About the problem

To understand what that issue about "hole" is all about, consider these data to be charted:

Note that for the Types Article and for Webform, there is no row with Published = No (that is, there are no unpublished nodes for these types). So in this scenario we have 2 so called "holes" ... And that's were the trouble start:

Problem 1: a column chart for these data looks like so:

The bar for "Article" (with value 1) is wrong, that bar is actually related to the value 1 for unpublished "Book pages". And the bar for "Book page" (with value 2) should actually be the bar for the 2 unpublished "Basic pages".
Problem 2: a line chart for these data looks like so:

In this case, the line for "unpublished" suffers similar problems. So it doesn't matter what type of chart you're creating, all charts have this issue.

How to solve this problem

Upgrade to the most recent Dev version to start with (which is much better / stable then the current rc1 version). Then apply the patch attached to the issue comment mentioned above, and check if that helps in your case. If it doesn't, know that it is a prereq for sure (without that patch you won't be able to get it to work). Attention: the patch doesn't seem to apply anymore to the most recent dev version. To make it work (again), do not use the above mentioned patch, but instead use the re-rolled patch attached to in Comment nr 31 of Issue nr 2052429.

Here is how the same column chart from above looks like after applying this correction:

And this is its corresponding line chart:

... Which I believe is the chart that exactly matches the tabular data shown above.

Step 2

If upgrading to the most recent dev version and applying the patch is not sufficient, then I'd recommend you to (temporarily) disable that Views Merge Rows module you have enabled. And (temporarily) modify your view to show the values for PASSED and FAILED as 2 separated columns. And then verify if you get the correct results. That way we can verify if this Views Merge Rows module is the culprit (solve support requests is like taking away all possible causes, 1 at a time ...).

Step 3

If step 2 doesn't help either, then I recommend what's written in the "Bonus tip" of Steps to create charts using the views UI, i.e.:

  You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first.

In other words: before trying to create a chart, make sure the tabular version of it has the correct data displayed.

Step 4

If none of the previous steps helps, then you may want to check the result you get by correcting your view like so:

Create another display in the same view, let's say you name it "Runs Chart (Total)". It should be equal to all the specs of "Runs Chart (Passed)", but without the filter "Content: Test Case Run Status (Passed)". Obviously, it'll reflect the total Runs (both passed and failed). I'd make it a "line chart" (but that's a matter of personal preferences).
Adapt the "Chart settings" of "Runs Chart (Passed)" to have it use  "Runs Chart (Total)" as the parent chart.
Adapt the "Chart settings" of "Runs Chart (Failed)" to have it use  "Runs Chart (Total)" as the parent chart (instead of "Runs Chart (Passed)").

Step 5

If the work around in step 4 helps as a work around, you may want to further refine the chart settings of "Runs Chart (Total)", by using a color for the line chart that matches the background of your chart (like white?). Possibly something similar for any of it settings like "Legend" (like set it to &nbsp;?

Disclosure: I'm a co-maintainer of the Charts module (+ author of its community documentation),
I hope this does not violate the site's policy on self-promotion.


Allow user to change views template I have a view configured with a custom template. Now I need to represent the same information arranged in two different ways. What I want is for the user to have an option to change between the three different templates. This doesn't seem to out of the ordinary but I am having trouble finding an example.

Using Drupal 7.

I would build the different displays as separate blocks and then use the quicktab module.

https://drupal.org/project/quicktabs

That way, it will be very easy to switch between the blocks.

Configuration in quicktabs:

Results:


Aegir hostmaster custom profile I created a custom profile with a custom theme for Aegir. I would like to enable that theme by default when a user install hostmaster during the Aegir installation. In the Aegir installation hostmaster is installed when the user runs the below drush command

drush hostmaster-install

I would like to know is there any way to modify this command or any other way to set my custom profile as defautt one during the Aegir install process.

Thanks

The hostmaster-install command has options for --profile and --makefile.

I use these options for OpenDevShop, which has it's own makefile and profile.

You can use a URL or a path for makefile option.

    drush hostmaster-install --makefile=/path/to/mymake.make --profile=mycustomprofile


Style tabs/links that anon can't see What would it take to style tabs (of the MENU_LOCAL_TASK variety) differently for tabs that anonymous can't see.  I have various admin-only tabs that I'd like to automatically call out as admin-only tabs (so that my admins/mods can keep track of what normal visitors can and can't see).

Maybe something like a call to user_access() within the hook_menu's title_callback attribute and stuffing a css class in the menu title if anon fails?  This would mean adding this to every MENU_LOCAL_TASK though.  I was hoping for something a little more global/automated.

What about taking it one step further and having a css class on all links that would be hidden if anon were viewing the page?

Drupal 6.

My solution

Riffing on Andy's answer.

/*
 * Add css class to menu items that anonymous users don't have access to.
 */
function [themename]_menu_item_link($link)
{
    global $user;

    // Not necessary to do this for Anon
    if ($user->uid != 0) {
        // Temporarily impersonate Anon
        $original_user = $user;
        $old_state = session_save_session();
        session_save_session(false);
        $user = drupal_anonymous_user();

        // See if Anon has access to this menu item
        $map = explode('/', $link['href']);
        _menu_check_access($link, $map);

        if (! $link['access']) {
            $newStyle = array('attributes' => array('class' => 'non-admin'));
            $link['localized_options'] = array_merge($link['localized_options'],
                                                     $newStyle);
        }

        // Restore user
        $user = $original_user;
        session_save_session($old_state);
    }

    // Resume rendering of this link
    return theme_menu_item_link($link);
}

menu_local_tasks() is a good place to start looking. This calls theme_menu_item_link() which is the pertinent theme function to look at. It makes sense to do any access checks in the preprocess and you'll also need a custom theme function to handle the variables you set. You mention user_access() in the Q, but it's important to remember that the access callback could by any function. For that reason it's necessary to impersonate the anonymous user (note the link isn't specifically for anon users, but the fundamentals are the same). You can get the menu item type, access callback, and access arguments from $link. The bit of code to do the actual checks would look something like:

if ($menu_item_type & MENU_LOCAL_TASK) {
  global $user;
  $original_user = $user;
  $old_state = session_save_session();
  session_save_session(FALSE);
  $user = drupal_anonymous_user();

  if (!call_user_func_array($access_callback, $access_arguments)) {
    // Anon's don't have access to this local task
  }

  $user = $original_user;
  session_save_session($old_state);
}

A note regarding performance: none of the calls access the database, except possibly the access callback (which could do anything). user_access() caches a role's permissions, so that would only access the DB the first time. Other access callback's might not do this. It wouldn't be particularly difficult to cache the results of the access callback yourself (keyed by access callback and serialised arguments).


Create a custom function to convert a field data In Drupal 7, I can create a custom function in the template.php file. here is an example of custom function:

function myCustomFunction($arg) {
    $data_converted = $arg . 'XXXXX';
    return $data_converted;
}

...and in Drupal 7 and inside my template I can call this function with passing a specific data / field data.

In Drupal 8, it's different, and I don't see how to proceed. In my .theme file, I tried to create a custom function. In my twig template I tried to call this custom function but I get an error : function not found.

With drupal 8 how can I proceed to implement a custom function (with args) ?
Thanks for your help, and eventualy yours examples.

In Drupal 7, I can create a custom function in the template.php file

To cut a very long story short, in Drupal 7 you should ideally have been  calling that function in a preprocess function, to prepare variables for the template, rather than calling it from the template directly.

In Drupal 8 it's now Fine™ to call functions directly in the template. But now you can't use PHP directly, so you need to write a Twig extension.

It's very easy, core even has its own that you can copy from. The important thing is to register the service class with a twig.extension tag, so the system picks it up.

See this blog post for a full example.


Drupal 7 Hierarchtical Taxonomy Translations I currently have hierarchical select installed but on the pages it's it doesnt apply basic localization. I need it to use the translations i have set up in the translation database of drupal. I have searched around google but havn't had luck finding a working solution.

Any help appriciated, thanks!

You need to enable Taxonomy translation module (Comes inbuilt with the Internationalization module).

If you are not using Internationalization module, please do make use of it to translate the taxonomy related values.


Get a calculated price from Product Variation I created a promotion with offer type - Fixed amount off each matching product and applies to - Specific product. In my custom block I get the product entity and try to get the calculated price via commerce_order.price_calculator service.

commercePriceCalc = \Drupal::service('commerce_order.price_calculator');
$context = new Context(\Drupal::entityTypeManager()->getStorage('user')->load(1),
                     \Drupal::entityTypeManager()->getStorage('commerce_store')->load(1));
$prices = $commercePriceCalc->calculate($slide->field_product->entity, 1, $context);

So, calculate method returns me a PriceCalculatorResult object with 2 properties, calculatedPrice and basePrice but they are identical.

PriceCalculatorResult {#3311 ▼
  #calculatedPrice: Price {#3310 ▼
    #number: "1000.000000"
    #currencyCode: "UAH"
  }
  #basePrice: Price {#3310 ▼
    #number: "1000.000000"
    #currencyCode: "UAH"
  }
  #adjustments: []
}

As if the discount didn't apply.

Solved this problem, by passing the 4th argument $adjustment_types to the $commercePriceCalc->calculate method.

$adjustment_types = array("promotion" => "promotion");

So, the final version of the code

$commercePriceCalc = \Drupal::service('commerce_order.price_calculator');
$context = new Context(\Drupal::currentUser(),
                     \Drupal::entityTypeManager()->getStorage('commerce_store')->load($store_id));
$prices = $commercePriceCalc->calculate($slide->field_product->entity, 1, $context, $adjustment_types);


Change toolbar config to latest CKEditor toolbar groups There is a ckeditor plugin that I really want to use (Line Height), but after looking at its .js file I can see that it is configured to work with the ckeditor config.toolbarGroups concepts, which configures the toolbar like so:

CKEDITOR.editorConfig = function( config ) {
config.toolbarGroups = [
    { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
    { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
    { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
    { name: 'forms', groups: [ 'forms' ] },
    '/',
    { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
    { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
    { name: 'links', groups: [ 'links' ] },
    { name: 'insert', groups: [ 'insert' ] },
    '/',
    { name: 'styles', groups: [ 'styles' ] },
    { name: 'colors', groups: [ 'colors' ] },
    { name: 'tools', groups: [ 'tools' ] },
    { name: 'others', groups: [ 'others' ] },
    { name: 'about', groups: [ 'about' ] }
];
};

However, I use the ckeditor module, with a drupal 7 codebase, and after I install the plugin and its dependencies, the button for the lineheight plugin doesn't show up when I go to admin/config/content/ckeditor/edit/**{text format}**.

Is there a way to edit the lineheight plugin code so that it works with the ckeditor module?

editor.ui.addRichCombo( comboName, {
        label: editor.lang.lineheight.title,
        title: editor.lang.lineheight.title,
        toolbar: 'styles,' + order,
        allowedContent: style,
        requiredContent: style,
        panel: {
            css: [ CKEDITOR.skin.getPath( 'editor' ) ].concat(   config.contentsCss ),
            multiSelect: false,
            attributes: { 'aria-label': editor.lang.lineheight.title }

Or, is there a way to convert the ckeditor module to from using the method below to using the new method above?

// Toolbar definition for all buttons
Drupal.settings.cke_toolbar_DrupalFull = [
['Source'],
['Cut','Copy','Paste','PasteText','PasteFromWord','-','SpellChecker',   'Scayt'],
['Undo','Redo','Find','Replace','-','SelectAll'],
  ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','Iframe'],

'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript','- ','RemoveFormat'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl','-','Language'],
['Link','Unlink','Anchor','Linkit','LinkToNode', 'LinkToMenu'],
'/',
['Format','Font','FontSize'],
['TextColor','BGColor'],
['Maximize', 'ShowBlocks'],
['DrupalBreak', 'DrupalPageBreak']

If you use the dev version of the wysiwygmodule, you'll be able to use the latest CKEditor library with all the fancy plugins.


How to use / configure the Course Requirements module? When using the Course module, you may also want to use the Course Requirements module, so that a user cannot be enrolled in a 2nd course until a 1st course is completed.

However, it's not obvious how to actually use / configure the Course Requirements module. So how is this module supposed to be used/configured?

The Course Requirements module does not have a lot (any?) docu. But comment nr 3 of issue # 2148985 helps to make it work, i.e.:

Add a node reference field to your Course content type (to references other courses).
Go to admin/config/course/requirements and select that node reference field you just added.
Add courses through the node reference field.

After completing these steps, this is how it should work:

The courses you add in the field should block that course from being enrolled into without completing the referenced courses.
After completing a course it should also tell you what courses required that course for completion.


How to display more than 1 chart on the same page when using Google Chart Tools? I have created a simple page (in Views) listing a series of nodes. Each node has an (EVA) field showing a pie chart.

When I use the Google Chart Tools module as a Views field format, the page shows only 1 chart (to the most recent node).

It seems that I need to do something so that multiple charts can show in the same page. But what am I missing here?

Any help would be much appreciated.

I finally managed to achieve this using the dev version of the Views Dataviz module. Of course there are other solutions but these require coding so i guess this is the easiest way of showing multiple charts in the same page.


How can add extra info to the  tag? How can I add extra info like lang="ar" dir="rtl" to the <html> tag like the following?

<html{{ html_attributes }} lang="ar" dir="rtl">

You can use the following code, even though for those specific values, I would find a different way (e.g. setting the language for the shown page).

{% html_attributes.setAttribute("lang", "ar") %}
{% html_attributes.setAttribute("dir", "rtl") %}
<html{{ html_attributes }}>

Inside hook_preprocess_html(), since $variables['html_attributes'] is an Attribute object, so you can use Attribute::setAttribute().

$variables['html_attributes']->setAttribute("lang", "ar");
$variables['html_attributes']->setAttribute("dir", "rtl");


Calendar view: Making year+month exposed filter go to the right URL Using the calendar module, I've created a monthly calendar:

The built-in navigation using << Prev and Next >> links works great, and correctly navigate to the previous and next month, using URLs like:
http://example.com/calendar?field_event_date_value[value][year]=&field_event_date_value[value][month]=&date=2014-07

The 2nd navigation is the year + month select lists. I got a requirement to navigate directly to a specific year and month using a dropdown selection. So I've added an exposed filter on the "Event: start date" field (see screen below), which tries to do it but the URL gets broken on the way. I get: http://example.com/calendar?field_event_date_value%5Bvalue%5D%5Byear%5D=2014&field_event_date_value%5Bvalue%5D%5Bmonth%5D=7. However, even if I manually fix the URLs displays empty data.

I tried to put a custom date selection form using this tip, but the form doesn't print. I also tried to create a custom submit handler like this in order to create a custom redirect but views behavior doesn't change. Also, changing the form action doesn't work since the target of the redirect depends on the user's selection and it still appends the extra query parameters.

Any idea on how to fix it?

I dunno but I ended up just doing it all manually with markup and JS, probably is an easier way but yeh:

<select id="month" name="month">
  <option id="01" value="January">January</option>
  <option id="02" value="February">February</option>
  <option id="03" value="March">March</option>
  <option id="04" value="April">April</option>
  <option id="05" value="May">May</option>
  <option id="06" value="June">June</option>
  <option id="07" value="July">July</option>
  <option id="08" value="August">August</option>
  <option id="09" value="September">September</option>
  <option id="10" value="October">October</option>
  <option id="11" value="November">November</option>
  <option id="12" value="December">December</option>
</select>

<select id="year" name="year">
</select>

<button id="gotomonth">Go</button>

$('#gotomonth').click(function() {
  var month = $("#month option:selected").attr('id');
  var year = $("#year option:selected").attr('id');
  location.href = year + '-' + month;
});

var currentMonth = ("0" + (new Date().getMonth() + 1)).slice(-2);
var currentYear = new Date().getFullYear();
for (i = (currentYear - 3); i < (currentYear + 3); i++) {
  $('#year').append('<option id="' + i + '" value="' + i + '">' + i + '</option>');
}
$('#month #' + currentMonth).attr("selected", "selected");
$('#year #' + currentYear).attr("selected", "selected");


Image not found --> creates a path that doesn't exists I'm trying to make a gallery with the Galleria module.
I did everything that the install guide said (module readme) and got the module to work, one time, but then when I went to my front page and back to the gallery I got the following.

I looked in my field setting and didn't create a sub directory. Then, I checked my "File system" configuration and the public path is said to be sites/default/files.

I have no clue why it needs the other directories or where it gets that path from.

Is there someone who could explain this?

When you install Galleria, it creates the image style presets it requires, which you can find under /admin/config/media/image-styles.

If you view the images, imagecache will create the image types and store them in the file system under the appropriate direcory so they will not have to be re-created. If your file system does not have the correct permissions, the directories and files cannot be created, and the images cannot be found.

Check your logs for error messages (/admin/reports/dblog). If this is the case you need to make sure that the directory tree has the correct ownership (usually apache.apache) and the correct read.write permissions (664). If you have access to the server, use the chown -R apache.apache * and chmod -R 664 * commands to accomplish this.

Once you have verified the permission, galleria should work correctly.


Open social date format I'm working on a Open Social (Drupal 8) implementation. When adding an event you can submit the begin & end date. Is there any way to change the date format in these forms? I went through the whole system, found a lot of date format settings, non of them had any influence on this form.

Ensure you have the Field UI module enabled.

If you go to Structure > Content Types > Event > Manage form display (admin/structure/types/manage/event/form-display) then you can change the form widget that is used there.

The Date and time widget which is the default has no configuration available. However, you can also use the select list widget which allows you to specify Date part order and Time type.


CSS Over-ride sub-theme So I have got a base theme that is being used across multiple sites, but am wanting to add subtle tweaks to certain sites and was wondering what would be the best way to go about it.

I have created a sub-theme, which works fine. But, in order for it to work I need to bring all the files over from the parent theme, although I'm only changing the CSS. I thought it would use the files in the sub-theme and any files not in that folder just use the parent themes files.

To create a new subtheme, briefly:

Create a new sub-directory in sites/all/themes with the machine name of the new theme.
Create a new file in the new subdirectory with the machine name and extention .info:

  name = The human name of the new subtheme

  description = ...

  core = 7.x

  base theme = the-machine-name-of-base-theme

  stylesheets[all][] = css/subtheme-new-file-name.css

Regions are not inherited and should explicitly declared again, so copy over from base file theme info file.
Color module file colors.css needs to be copied and added too, if the base theme supports it, otherwise a nasty error occurs.
Favicon is not inherited
Settings are not inherited

All the rest stay at base theme.

More about sub-theming: Creating a sub-theme


Sending data via post and redirecting user So I made a module that needs to gather some data and redirect user and that data to a payment site.

function payment_upload_form($form, &$form_state){

$form = array();
$form['#action'] = 'www.somepaymantsite.com';
$form['#method'] = 'POST';
$form['CustomerFirstName'] = array(
    '#title' => t('First name'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#size' => 25,
);

$form['CustomerLastName'] = array(
    '#title' => t('Last name'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#size' => 25,
);
etc....

$form['customersubmit'] = array(
        '#value' => 'Pay now',
        '#type' => 'submit',
        '#submit' => array('wspay_submit'),
    );

return $form;

}

function payment_submit($form, &$form_state){
$option = array(
        'ShopID'=>'xzy',
        'ShoppingCartID' => $temp_cid,
        'TotalAmount'=> $amount,
        'Signature' => $signature,
        'ReturnURL' =>'http://some_sitecom',
        'CancelURL' => 'http://some_site.com',
        'ReturnErrorURL' => 'http://some_site.com/1',
        'CustomerFirstName' => $form_state['values']['CustomerFirstName'],
        'CustomerLastName' => $form_state['values']['CustomerLastName'],
        ....
        );

$options = array(
  'method' => 'POST',
  'data' => drupal_http_build_query($option),
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$response = drupal_http_request('www.somepaymantsite.com', $options);
 $response->redirect_url = 'www.somepaymantsite.com';

The problem is that it does not redirect me on the first go, but when I use the same ShoppingCartID it redirects me and I get an error because the ID is the same(it need's to be different every time), but the data is in the URL .
So my question is why does it not redirect the user with the data to the site when he clicks Pay now.

---------------------- EDIT -------------

How can i create a middle page in drupal that has this data and sends it like that, meaning a confirmation page :

        <form name=“pay“ action=“https://to.the.shop.something“ method=“POST“>
    <input type=“hidden“ name=“ID“ value=“some_value“>
    <input type=“hidden“ name=“ID2“ value=“some_value“>
 <input type=“hidden“ name=“ID3“ value=“some_value“>
    <input type=“submit“ value=“Pay now“>
    </form>

Your submit function name is wrong , your submit function not called at all, In Drupal if you have form name x then the submit should be x_submit, so in your case the submit function should be

payment_upload_form_submit


How to flip order of Privatemsg thread from ASC to DESC? When an individual private message thread is viewed, it displays the thread messages from oldest to newest, followed by the "Reply" field. I'd like to show the "Reply" field first, and then the thread messages from newest to oldest. How can I reverse the order of the page in this way? I cannot find anything in the code that would point me toward something to re-theme it in a descending order instead of ascending.
Something like this:

[REPLY FIELD]
[Message on Jan 6 2017 at 11:30am]
[Message on Jan 6 2017 at 11:05am]
[Message on Jan 6 2017 at 10:00am]
[Message on Jan 5 2017 at 11:45am]

...instead of the current layout/ordering, which is like this:

[Message on Jan 5 2017 at 11:45am]
[Message on Jan 6 2017 at 10:00am]
[Message on Jan 6 2017 at 11:05am]
[Message on Jan 6 2017 at 11:30am]
[REPLY FIELD]

Any other ways I can get it to work, outside of hacking the module?

There is no way to alter a module from another php file / module unless it provides a hook, luckily here they did.

I must be blind, right above it (line 1098), it says in the comments: * @see hook_query_privatemsg_messages_alter()

I found the doc hook_query_privatemsg_messages_alter. Hooks go inside modules, more specifically inside the .module file and you replace the word hook with the actual name of your module.

So create a custom module, inside of mymodule.module (Here we assume your module is called/named mymodule)

/**
 * Implements hook_query_privatemsg_messages_alter().
 */
function mymodule_query_privatemsg_messages_alter($query) {
   $query
     ->orderBy('pm.timestamp', 'DESC')
     ->orderBy('pmi.mid', 'DESC');
}

Side note:

Don't confuse hooks with templates_something_something() those go inside your template.php file. Ex: template_preprocess_node and you replace the word template with the actual name of your theme.

  No Sssweat, can I bother you for one other thing? I'd like to move the
  reply box above the message thread. I found where this is handled in
  the module (privatemsg.pages.inc, lines 892 and 926). How would I
  override those two lines (adjusting the "weight" values so that the
  reply box is a lower weight than the message thread) without hacking
  the inc file? Would it be done somehow in a custom module?

You're suppose to use hook_privatemsg_view_alter

Sadly, it does not work for reply or message; even though, when I dump dpm($content) using Devel the array it has changed the weight. Works for pager only. Looks like this is a bug.

/**
 * Implements hook_privatemsg_view_alter().
 */
function mymodule_privatemsg_view_alter($content) {

    $content['pager']['#weight'] = -3; // does not work
    $content['reply']['#weight'] = -5; // does not work
    // nor it does not work when doing $content['message']['#weight'] = -5;

}

If I comment out the $content['pager']['#weight'] = 3 and $content['reply']['#weight'] = -5; from the module, the hook works.


Computed dependent field I have a node type (actually entityform type) with a term reference field. The terms has a description field (a long text with a HTML markup). I need to display the description of a selected term on a node edit form. Is it possible to show a description immediately after user selects new term from a list?

It seems that it's very easy to implement a computed dependent field. Suppose there is a term reference (field_section) on an edit form with YOUR_FORM_ID.

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == YOUR_FORM_ID) {

    // Add an AJAX behaviour to field_section:
    // After you will select a new term on the edit form,
    // YOUR_MODULE_NAME_form_alter and
    // _YOUR_MODULE_NAME_form_section_callback will be called.
    $form['field_section'][LANGUAGE_NONE]['#ajax'] = array(
      'event' => 'change',
      'callback' => '_YOUR_MODULE_NAME_form_section_callback',
      'wrapper' => 'nomination-desc-wrapper',
      'method' => 'replace',
      'effect' => 'fade'
    );

    // Add a wrapper for our computed dependent field.
    // At the begining it will be invisible
    $form['nomination_desc_container'] = array(
      '#type' => 'hidden',
      '#weight' => 2,
      '#attributes' => array('id' => array('nomination-desc-wrapper')),
    );

    // Add a computed dependent field. It will be shown as a text
    $form['nomination_desc_container']['nomination_desc'] = array(
      '#type' => 'item',
    );

    // This code will be executed during form creation and
    // during each AJAX-call
    if (isset($form_state['values']['field_section'])) {

      // Find taxonomy term
      $tid = $form_state['values']['field_section'][LANGUAGE_NONE][0]['tid'];
      $term = taxonomy_term_load($tid);

      // Show it's description
      $form['nomination_desc_container']['nomination_desc']['#markup'] = $term->description;

      // Display description wrapper
      $form['nomination_desc_container']['#type'] = 'container';
    }
  }
}

// Just return new wrapper body
function _YOUR_MODULE_NAME_form_section_callback($form, &$form_state) {
  return $form['nomination_desc_container'];
}


Drupal 7 subtheme location best practice I currently have an Omega subtheme located as a subdirectory of the .../sites/all/themes/omega.  I think this location was a requirement for Drupal 6.  Now that we're on Drupal 7, I'm looking for the best practice on where this subtheme should be located.  Does it make sense to add it to .../sites/all/modules/custom/ or maybe create a new directory like .../sites/all/modules/themes/.

Any best practice advice would be great.

Thanks

Themes should be stored in sites/all/themes, not sites/all/modules.

You could certainly add your custom theme to sites/all/themes/custom, but what I do is just add my custom theme(s) to sites/all/themes directly.  I do this because I name my custom themes for the sites I am working on, so it's very clear that the particular theme is specific to the site.

The other reason I don't think a /custom directory is necessary is because, unlike modules, one generally only has five or six themes (at most) installed on a single site.  So there is far less possibility for confusion.


Looking for a strategy to optimize a big body field on a node I'm using Drupal 8.4.x

I have just one node with a big text on its body field (about 2.5 MB). Looking a strategy to optimize:

Page load. Does exist any "content lazy loading" module? (I can see one for D7 but without a stable release).
I'll like to create revisions on this node. I'm gonna use Diff module to see changes and also to enable visitors to see those changes. This a consuming task on a big node and not sure how to cache/optimize those Diffs.

Note: I've tought about spliting the content in different nodes (like a book) and then use something like Views Infinite Scroll but I'll find hard to implement 2 with this aproach.

Using the Paragraphs module is probably the current go-to solution for a more manageable setup than a large body field. Functionally, it's right in between a single text field and completely separate nodes. It enables you to create more manageable chunks of content that replace the traditional body field. Each chunk can be simple text, or more complex things. Each "paragraph" is an entity with fields, and the node references those entities. When editing, it feels like a more focused interface. The content creator stays on the node, so the complexity is hidden in the background.

Another strength it has is good support for revisions. In fact, it requires the Entity Reference Revisions module, and its project page suggests using the Diff module.


Where is the configuration actually saved in the system? I am new to Drupal 8. I installed the Drupal webform module. I am able to export the configuration file but unable to figure out where the configuration is actually is saved in the Drupal system.

Nowhere, most of configuration is located in database including webform.

With config module, you may find webform configuration in admin (yml) : /admin/config/development/configuration/single/export

First, select webform in configuration type, then the configuration you need to export.

NB : have a look at sources https://github.com/drupalprojects/webform/blob/8.x-5.x/src/Entity/Webform.php , most of drupal contributions are built the same way, webform extends ConfigEntityBase and these are typically stored in database (config table as a blob)


How to show an image instead of a tab title for a field group? How can I show an image instead of the tab title of a field group?

Each tab has a unique CSS id or class you can use CSS background-image and text-indent to hide the text of a field.


Drupal 8 different layouts in theme How do i create theme that has different regions for every node?

For example i want my frontpage to have different regions than some other page that represents content.

You don't want different regions for every node.

Regions should be as generic and re-usable as possible.

However you don't have to include all regions in all templates.

Your page--front.html.twigcould have a different set of regions to page.html.twig

Maybe checkout the Drupal 8 theming guide.


Creating two aliases for the same node I have a content type with a field allowing to select public or private.

I am using the Pathauto module for generating path aliases using this field, using /[node:field_evt_diffusion]/[node:title] as pattern. I am using the CAS  module to casify the /private/* path.

Is it possible to create two path aliases for the same node?

If manual steps are OK you can use this workaround:

The pathauto module always generates aliases using the first matching pattern type/condition combo. So simply create two matching patterns for your nodes. Generate URLs using the first pattern, deactivate this pattern and rerun URL alias generation (which now automatically uses the 2nd matching pattern).


How to show contextual links / quick edit links for blocks I'm building a Drupal 8 template/theme from scratch, and it is not showing the contextual editing options for my blocks when I view a site page. I.E., the little circles that are clicked to see options like "edit view," "configure block,"  etc.

I cloned the block.html.twig from the Bartik theme, so it has the attributes token that I thought was enough, like this:

<div{{ attributes.addClass(classes) }}>
 {{ title_prefix }}
 {% if label %}
   <h2{{ title_attributes }}>{{ label }}</h2>
 {% endif %}
 {{ title_suffix }}
 {% block content %}
   <div{{ content_attributes.addClass('content') }}>
     {{ content }}
   </div>
 {% endblock %}
 </div>

I can confirm the Contextual links module is active.

I have global access, so it shouldn't be a permissions issue.

Is there something more I need to do for this feature to be added in?

Per 'No Sssweat's comment above, this was due to a small syntax error in a custom javascript file, viewable in console. Once corrected, the contextual links worked as intended.


how to include main navigation twice with different display i started working with drupal 8 few days ago.
I am working on theming with Twig.
I included the main Navigation on the header, after the activation of twig debug mode , i followed the suggestion of twig and i created menu-main.html.twig contains the html respresentation of the links and i had this display:

My Problem is :
I included the Main navigation on the footer too but it appears the same way as the header but i want to change the display to be like this:

What should i do ?

Don't rely on a hardcoded class in your overridden template to style the menu, but instead rely on a container to style it (for example the containing block or region).


How can I display a block on view page, excluding paginated/paged/pager output pages? I'm trying to use Context to display a block on a view page path, e.g. /view, but exclude it from the paged output, e.g. /view?page=1. The path exclusion tools in Drupal 8 don't work with the query string (and no query string rules are available).

There's a Drupal 7 solution (hack?) for this posted on How can I show a block in a view page, excluding its paginated pages?

Any help to get something like this in Drupal 8 working would be appreciated.

The issue on Drupal.org is https://www.drupal.org/project/context/issues/2930896.

Thanks to Clive's post above, this can be accomplished with the early dev module Request Data Conditions:

https://drupal.org/project/request_data_conditions


execute a php code after a user login I see that triggers page is changed from the version 6, It's pretty wierd..
I can't find When user logs in execute a php code thing...

What I have to do is exactly that..
control some user roles depending on his location (intranet or internet)
I already have the php code developed but...can't find how to put it ....

$usr = user_load($uid);

$array_roles=array();
//supose i'm logging in from internet
    $details = array(
        'uid' => $uid,
        'roles' => array(
            21 => 'Internet'
            )
        );

foreach($usr->roles as $key=>$value)
{

 if ($key!=20 and $key!=21) // exclude internet or intranet roles
 {

  $details['roles'][$key]=$value;
 }
}

user_save($usr, $details);

The best way to execute your custom code after a user logs in is by implementing hook_user_login in a small custom module you build yourself.  Turn that php you wrote into a function then call it.

i.e.

function module_name_user_login(&$edit, $account) {
  module_name_user_function($account->uid);
}

function module_name_user_function($uid) {
$usr = user_load($uid);

$array_roles=array();
//supose i'm logging in from internet
$details = array(
    'uid' => $uid,
    'roles' => array(
        21 => 'Internet'
        )
    );
foreach($usr->roles as $key=>$value) {
  if ($key!=20 and $key!=21) {
  $details['roles'][$key]=$value;
  }
}
user_save($usr, $details);
}

More about custom modules, and modules all around can be found at The Module Developer's Guide

I would not recommend putting custom php in a trigger and action.  Keeping custom code in the database is always dangerous for people coming down the line that have to maintain your site in the future.


How do I view the user registration form (as a page/node) while signed in as Admin. I can see the user registration form fields at Administration/Configuration People/Account Settings/Manage Display/User Account, however I cannot find a way to display this information as it would appear on a Drupal page/node. What am I missing?

Hank

The user/register path in Drupal only displays a form for anonymous users. If you wish to view it as you're changing form elements, open up an anonymous tab (e.g. Igcognito in Chrome, Private Browsing in Safari, etc.) and reload the page as you make updates.


How do I make the output of a View a particular Field? Right now my View is outputting a list of Nodes by their title. I've added a 'subtitle' field to these node's Content Type and I would like to use this as my outputted result instead.

I've gone to the 'Fields' section of my View but cannot find my newly added Content Field among the options there (have cleared cache and rebuilt registry).

Would anyone know how to achieve this?

(ps: why is it called 'Views'? Wouldn't 'Queries' be more accurate?)

Turns out my Field was there in that list, but its name was different. It had adopted that name of a Paragraph it was used on. Apparently, if the Field is used in a Paragraph, the name you give it in that instance will be trump any other names you give it.

I don't know why this is or why this feature is useful.


Duplicating commerce kickstart's product types view modes I can see that Commerce Kickstart distribution has several more view modes for product types like: product in cart or node:product list, which are not listed, by default, after commerce module installation on plain Drupal.

How can I get those with only commerce module installed?

Is it some additional code or I am just missing some settings?

I found a module, Entity view modes, which seems to be good for the job but Commerce Kickstart does not have this module installed.

Thank you for advice.

In Commerce Kickstart, Commerce Kickstart Product (commerce_kickstart_product) and Commerce Kickstart Product UI (commerce_kickstart_product_ui) modules provide the extra view modes. And are not available as a separate module.

So, you can use Entity view modes (entity_view_mode) to create your custom view mode.


Site keeps redirecting to core/install.php I keep having this problem of drupal redirecting to core/install.php as shown below:

I already set the max_allowed_packet to 64MB on AWS RDS. I am not sure what else I am missing. Please help

The error in the logs is:

  Fatal error: Cannot redeclare
  _drupal_shutdown_function_handle_exception() (previously declared in /var/www/html/web/core/includes/bootstrap.inc:1066) in
  /var/www/html/vendor/drupal/core/includes/bootstrap.inc on line 1066

and the following is my composer.json

{
  "name": "xxx/yyy",
  "description": "zzz",
  "type": "project",
  "license": "GPL-2.0-or-later",
  "authors": [
    {
      "name": "QQQ EEE",
      "role": "Developer"
    }
  ],
  "repositories": [
    {
      "type": "composer",
      "url": "https://packages.drupal.org/8"
    }
  ],
  "require": {
    "php": ">=5.6",
    "aws/aws-sdk-php": "^3.108",
    "composer/installers": "^1.2",
    "cweagans/composer-patches": "^1.6.5",
    "drupal-composer/drupal-scaffold": "^2.5",
    "drupal/console": "^1.0.2",
    "drupal/core": "^8.7.0",
    "drupal/ldap": "^3.0@beta",
    "drupal/redis": "^1.1",
    "drupal/s3fs": "^3.0",
    "drush/drush": "^9.0.0",
    "predis/predis": "^1.1",
    "vlucas/phpdotenv": "^2.4",
    "webflo/drupal-finder": "^1.0.0",
    "webmozart/path-util": "^2.3",
    "zaporylie/composer-drupal-optimizations": "^1.0"
  },
  "require-dev": {
    "webflo/drupal-core-require-dev": "^8.7.0"
  },
  "conflict": {
    "drupal/drupal": "*"
  },
  "minimum-stability": "dev",
  "prefer-stable": true,
  "config": {
    "sort-packages": true
  },
  "autoload": {
    "classmap": [
      "scripts/composer/ScriptHandler.php"
    ],
    "files": ["load.environment.php"]
  },
  "scripts": {
    "pre-install-cmd": [
      "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "pre-update-cmd": [
      "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "post-install-cmd": [
      "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-update-cmd": [
      "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ]
  },
  "extra": {
    "composer-exit-on-patch-failure": true,
    "patchLevel": {
      "drupal/core": "-p2"
    },
    "installer-paths": {
      "web/core": ["type:drupal-core"],
      "web/libraries/{$name}": ["type:drupal-library"],
      "web/modules/contrib/{$name}": ["type:drupal-module"],
      "web/profiles/contrib/{$name}": ["type:drupal-profile"],
      "web/themes/contrib/{$name}": ["type:drupal-theme"],
      "drush/Commands/{$name}": ["type:drupal-drush"]
    },
    "drupal-scaffold": {
      "initial": {
        ".editorconfig": "../.editorconfig",
        ".gitattributes": "../.gitattributes"
      }
    }
  }
}

You've got a problem with your installation. You have two copies of core, as can be seen from the two paths in the error message:

/var/www/html/web/core/includes/bootstrap.inc

/var/www/html/vendor/drupal/core/includes/bootstrap.inc

You should not have a copy of core in your vendor directory. That needs to be removed, though it may also break your site. Make sure to clear the registry drush cr or equivalent after removing that directory.


Views Jump menu with taxonomy url and custom url I have problem with jump menu and contextual filters.
My idea is this:

I have taxonomys (a,b,c) URL: example.com/a (this works fine with contex. filters)

Then: example.com/a/hello

This hello is my menu-url (I make it my own)

When I select a in this jump menu and click menu-link hello , this jump-menu a need to be activated. Default is in this jump-menu is -Any-


How to make Drupal 8 use only relative URLs? I'm trying to get my site to use only relative URLs, like in the question drupal.stackexchange.com/questions/105932

EDIT 3:
It seems like Drupal 8.0.3 and beyond will do this by default:

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

But I've changed the code for Drupal 8 to this by getting rid of the deprecated function:

function custom_file_url_alter(&$uri) {
  global $base_path;

  $scheme = file_uri_scheme($uri);

  if (!$scheme || $scheme == 'public') {
    if (!$scheme) {
      $path = $uri;
    }
    else {
      ////$wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
      $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }

    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);

    $uri = $base_path . ltrim($path, '/');
  }
}

The problem is, whenever I add even just an article with an image (or any content type with a file in it) I get an error like this: 'Uncaught PHP Exception InvalidArgumentException: "The URI '/sites/default/files/field/image/h.jpg' is invalid. You must use a valid URI scheme." at /srv/www/example/core/lib/Drupal/Core/Url.php line 301, referer: http://example.com/node/add/article. I'm also getting this error when visiting a page that links to certain uploaded files.

The documentation says that this hook is called whenever the file_create_url method is called, but I don't know enough about Drupal to understand what scenario this method is being called which is causing Url.php to get mad at me.  For what reasons does Drupal call file_create_url, and why are almost all scenarios working for me while some are freaking out about no scheme being used?

Any extra information or guidance about this will be appreciated.

EDIT:

Here are some examples of $uri as it comes into the function (1) and as it leaves (2) .

1: 'core/themes/stable/images/core/icons/5181c6/pencil.svg'
 2: '/core/themes/stable/images/core/icons/5181c6/pencil.svg'
 1: 'public://css/css_Ys2L0rGQLjkWZQC7f9g5LiLUni8xUQvB1HqJHn3TKK4.css'
 2: '/sites/default/files/css/css_Ys2L0rGQLjkWZQC7f9g5LiLUni8xUQvB1HqJHn3TKK4.css'
 1: 'public://field/image/h_0.jpg'
 2: '/sites/default/files/field/image/h_0.jpg'

The h_0 example is one that happened after I created an article with the h.jpg image, which crashed and prevented creation of the article.  I've noticed that when I upload the image using the form, the little ajax thing that happens and shows you the preview of the image doesn't work when I use this file_url_alter code.  So, something is trying to call file_create_url when saving the image in the first place, and then, since the image is not properly saved, it can't be added as a field of the node.

Also, I've printed a backtrace, and it seems the crash happens after ThemeManager.php's render function calls template_preprocess_file_link(), which, in file.module, tries to do this:
$variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));

...which caused the error I mentioned in the first place.

EDIT 2:

I've made this work by modifying one line of core.  I changed the last line of template_preprocess_file_link() in file.module from $variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options)); to $variables['link'] = $url;. This makes all URLs relative without any noticeable issues.  Does anyone know how to achieve this without hacking core? Or, does anyone know what negative effects doing this might cause?

Maybe you can take a look at this function new to Drupal 8 :

file_url_transform_relative()

Once you pass an uri through file_create_url() you get an absolute url. You can then pass it to file_url_transform_relative() and you'll get the relative path if indeed it's pointed to a local file.


Install and use Azure SDK Is it possible to install Azure SDK via Composer within a Drupal site and use it in custom modules?
{
  "require": {
    "microsoft/windowsazure": "*"
  }
}

Also according to Microsoft docs, below code should be used in order to use Azure API. Not sure where though.
require_once 'vendor/autoload.php';
use WindowsAzure\Common\ServicesBuilder;

You don't need to autoload it in Drupal.
what you need is in the root of the Drupal run :
composer require microsoft/windowsazure

then in your custom module use it with
use WindowsAzure\Common\ServicesBuilder;


customize url of path of file entity I'm using the media module to build an imagebank.
Is there a way to customize the url of a file? Currently is looks like this: file/20 and I would like t to look like this imagebank/image/20.

Any ideas?

thx in advance

File entity doesn't currently integrate with Pathauto but integration is being worked on in Add support for Pathauto.

Please help test the latest patch and provide feedback including if it works correctly and any issues you might have found!


Automatic generate a parent category when adding a new node I have a content type Artist and a content type Songs. Each artist has a number of songs. I want to be able when I add a new song to assign it to the artist that it belongs and then have a view of the songs from a specific artist. I don't want to do a seperate term in taxonomy for every artist I add. Can this be automatically? ex. When I add an artist, and then I add a song I want to be able to assign this new song to the new artist without me having to manually add a new taxonomy term for the artist and then assign this song to this taxonomy term...

I want my paths to look like this.
ex: artist/songallery  ----> artist/songname

Hope I made myself clear,
thank you in advance.

You have content types a)Songs b)Artist

Create a node reference field with artist, in Songs content type. So when you add a new song you can you can select the artist belongs to that. I hope no need of taxonomy.

You can create two page displays in view by selecting necessary fields and give the appropriate path as you wish.

Hope this may help you!


Get the parent items of a menu item How can I get the parent items of a menu item for a view?
I added a Global: null argument in the view and I need to get the parent items of this view. The view is set to belong to a menu in admin/build/menu-customize/primary-links.

I tried these in the argument to examine the parent items:
$menuParent = menu_get_active_trail();
dsm($menuParent);

However, it's not resulting in the output I hoped. I tried to look for a right function in http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/6 but I get confused with all these functions: menu_tree, menu_tree_data, menu_get_ancestors etc.

I am using Drupal 6.

There is not an easy way to get the parent of a specific menu item. The problem is that a path can be in many menus so you need to not only know the path of the item whose parant you want to find, but also which menu to look for them.

The menu_links table hold the info and with a few queries you could find info about the parent. If you actually want to change anything in the menu being printed, that's a completely different story, and can be quite tricky in Drupal 6.

To get menu item you could do something like this:

$path = 'foo';
$menu = 'bar'
$mlid = db_result(db_query("SELECT plid FROM {menu_links}
          WHERE link_path = '%s'
          AND menu_name = '%s'";, array($path, $menu)));

$menu_item = menu_get_item($mlid);
// $menu_item is now the parent menu_item of the menu in bar with path foo


How to compute and display value of some fields? I'm facing the issue but not found the way to resolve. is there any way to help me this.
The issue is that I want to display the total value (included sum and get percent, etc) of some fields depend on what value user select in list.
Value in table like that

Table locations:

Example:

ID Name values

1  US   20%
2  UK   30%

Table Products

Example:

ID Name  Price
1  pro_A 10$
2  pro_B 20$

And what I want to display is to show the list locations and products to let user select as list.

Example: when user select us and pro_A, I want display a total field and computed it (10$*100)/20

Anyone can help me this or help me organize infomation by other ways as long as I can get the same result.

Have a look at the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


Unable to import date from csv with Feeds module I have a simple csv file I'm trying to import with feeds.  Most of the fields are going in just fine, but the dates are failing.  And after following the process through in a debugger, I cannot see why this fails - the date exists when Feeds saves the node, so why does this fail?.

Above: This screenshot of my debugger shows that entity has date information immediately after entitySaved is called.  I cannot detect anything unusual about the object format - looks kosher.  The date was added as the field_deadline_proposals:end. A date can be a range, so I assume this is the proper way to save a single date (non-range).

Above: This is a screenshot of the database table for field_deadline_proposals immediately after node save.  Node 258 does not have the information I expect.

This is the relevant excerpt from my csv doc, with headers:

id,rfp_num,description,title,published,rfp_filename,response_deadline,QA_deadline,mod_date,create_date
4,034-009  Robinson Pkwy,"Robinson Pkwy -Walkthru 6/22/09  9:30am.  Log onto the website for more information. Due date has been moved to 7/6/09  11:00am",TRUE,RFP_034-009  Robinson Pkwy_034-009_doc.pdf,7-6-2009 11:00,29-06-2009 13:00,7-1-2009 13:50,19-06-2009 9:29

My dates are currently in d-m-yyyy hh:mm format, which seems to work just fine and was recommended in this related post.  Frankly, I don't think the date format it much of an issue - I have had success with other formats, including using feeds_tamper to convert the date to UNIX timestamps.  In all cases, though, the save fails, so I suspect some other issue :-/

Got it.  Turns out that adding a new mapping that used the same date field with the Deadling for Proposals: start target solved things.

This wasn't particularly intuitive for me, so maybe this will be helpful for someone else too.


Make either of 2 fields required but not both? Ive added a file field to comments so users can upload a file in a comment as well as post text. How can I make it so one of the 2 fields is required to be filled in to create a comment (so you cant submit blank comments), but without making both fileds required?

Check this thread and Conditional fields module.

If you're using D7 - the principle is the same as in the thread I linked. Basically you need to attach the name of your processing function to the validation array and there perform the checks.


What is the naming convention for theme region template files? I want a custom template for every theme region, but I'm not sure of the naming convention.
For example, with the following information the .info file, would region--header.tpl.php be a correct template name for the Header region?

regions[header] = 'Header'
regions[sidebar_first] = 'Sidebar First'
regions[content] = 'Content'
regions[footer] = 'Footer'

Yes, the naming scheme is region--[region].tpl.php where [region] is the region machine name defined in the theme info file. See Drupal 7 Template (Theme Hook) Suggestions for more information. You will need to flush your theme registry cache for the template to take effect.


Request passphrase at user registration and automatically assign role to user Is there a module that would allow us to request an optional predefined pass-phrase/password at user registration?

So if the user fills in the pass-phrase he would be registered as a premium user or something, if not he would be set as a simple authenticated user.

By the way, I'm using Drupal 7.

Use the Rules module to implement such feature, as further detailed  below.

Step 1: Add a field to the registration form, which wil be used to have a user enter your passphrase. Even though you can use any "machine name" for that field, let's assume you call it "field_optionlist"

Step 2: Use a variation of the Rule included in my answer to "How to specify a Rules condition related to select list values?". Here is what you should tune in that rule:

Replace the Rules event to something like "After a new user submits a registration request"
Replace the "Value C" in the Rules condition to the value of your passphrase
For debugging reasons, start with a Drupal message to be shown (imilar to the rule mentioned above. After the message shows up as you want it to show, replace the Rules Action with something like "Assign role to user".


drupal_goto not working in hook_init First some introduction:

The hook is working in other pages or direct urls.
The only situation where is not working is in the find content page, "admin/content".

When the user clicks on edit link, drupal loads the node edit page, but we need to redirect that edit page to our own edit page. That's why we use the code in the hook.

THE PROBLEM:

When the user clicks on edit, he or she is redirected to the same page again (Find content). Intead of going to the my_module edit page. I Don't know why it's happening this. Any help is welcome :)

The Code:

function my_module_init() {

    // redirect drupal edit page to our own module edit page.
    if (preg_match('/^node\/(\d+)\/edit$/', current_path(), $matches)) {
      $code = _my_module_check_code($matches[1]); //check if the nid is of the content type we need
      if ($code) {
        return drupal_goto('my_module/' . $code . '/edit');
      }
      // If the code is not from the content type we need, we do nothing
      // just leave drupal work it's way
    }

}

The solution is to use the hook_preprocess_page().

function my_module_preprocess_page() {

    // redirect drupal edit page to our own module edit page.
    if (preg_match('/^node\/(\d+)\/edit$/', current_path(), $matches)) {
      $code = _my_module_check_code($matches[1]); //check if the nid is of the content type we need
      if ($code) {
        global $base_url;
        $url = $base_url.'/my_module/'.$code.'/edit';
        header('Location: ' . $url);
      }
      // If the code is not from the content type we need, we do nothing
      // just leave drupal work it's way
    }

}

After clearing cache, all is working fine.


Saving a views sql query I am using Drupal 6, and Views 2.0; I need to create a node where one of the fields is a filterable view. I then need to store the final SQL query of the view in the database.

How would I add the block view to a node creation page?

Unfortunately I wasn't able to solve this issue, so I did a little bit of a work around.

What I did was built a content type where the user could specify what data he/she needed by use of a form and fields.

I then took the user input and built a dynamic sql query to output the required data.

Its a pretty dirty way of doing it... but until I find another solution, I'll have to use it.


404 when using named placeholders for variable parts of Panels path I'm creating a landing page using a custom content type in Drupal 7, I've set up the views and had everything working correctly, but then I decided to change something at the last minute and add named placeholders to my URL. For some reason I'm receiving a 404 when calling the specific URL.  Do I have to do anything specific to my contextual filters in views or in Contexts, so that the URL actually works?

I have this set for my landing page /publications/magazine/2014/SPRING (/Publications/Magazine/%field_year/%mag_issue)
I have a custom date format set to year only for the date field and have a taxonomy vocabulary called seasons (fall, winter, spring summer)

For my contextual filter, I have Content: Has taxonomy term ID using Raw Value with the specific vocabulary set, one of my views requires this. That's really the only unique thing here. I'm working locally at the moment, so i dont have a url, but any suggestions would be helpful, spending 3 hours so far trying to figure this out.

For others who find this question and have similar scenario make sure for your arguments you set your context up properly, for mine I had context set to Taxonomy term ID, instead of the Name and as soon as I changed it to name and saved it. Cleared Cache, everything worked again.


Why D7 creates two tables when i add one custom fields in user registration? I created few custom fields for user registration in Drupal 7.

When I add the "First name" field, two tables are created: field_data_field_first_name, and field_revision_field_first_name.

Why are there two tables, if they contain the same data?

You can find the answer on your question on Duplicate data in field_data* and field_revision* tables. In particular, see this comment:

  The field_revision tables store the revision id, which never changes in these tables. The field_data tables store the node's current revision id and does not store old revision data. Basically the field_data tables only ever contain 1 entry per node. The field_revisions table will contain the number of revisions you've created, preserving the revision data. So if you never use revisions, then yes, the tables will contain identical data.

  Since revisions are a core part of Drupal I don't think there's anything you can do about this. You can probably delete the contents of the field_revision tables (please test first, don't take my word for it!), but as soon as you start creating/editing nodes the field_revision tables will repopulate.


How to include CSS for a custom admin theme? I want to include my custom style.css in admin pages in Custom Admin theme I have been create.
I am including CSS in .info file as follows

name = Example Module
description = Custom Example Module
core = 7.x
configure = admin/config/example-module/settings
permissions = admin/people/permissions#module-example-module
stylesheets[all][] = css/style.css

and I used mymodule_preprocess_page(&vars) , but I didn't see any result.

You can add yourstyl.css in admin theme's .info file.
Just goto your active admin theme, find and open its .info file and place a simple line here; stylesheets[ ] = css/yourstyle.css . It works like a charm.


How do I add a customized parameter to image links Lets say I have image fields in my node. When I get that fields values in the twig it returns the image URL without any issue.

file_url(node.field_image.entity.uri.value)

But now I want to add a specific parameter (lets say ?param=0) to the end of that link. Without hard coding the parameter in the twig file is there a way to write a hook that adds that parameter for all the image links in every node. So if I have to change the param I only need to change it from one place.

You can do this with a preprocess function THEMENAME_preprocess_field and check whether the field is an image and it has a URL

function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_type"] == "image"){
    if(isset($variables["items"][0]["content"]["#url"])){
      $variables["items"][0]["content"]["#url"]->setOption('query', ['param' => '0']);
    }
  }
}


Rebuild form AFTER ajax callback has run I have a form with a button that when pressed re-builds a different part of the form via an ajax request.

Upon clicking the button the form is rebuilt, then my ajax callback is called which saves the values from the form, and then returns part of the form.

The problem is the form is rebuilt BEFORE my callback which saves the values, and therefor alters how the form is built.

If I click the ajax button a second time then it works correctly as has the values from the previous ajax request when the form is build.

How can I get my callback function to run before the form is rebuilt?

function emtr_shift_plan_form($form, &$form_state) {

    ddl('build'); // log that this function is being called

    $form['save'] = array(
        '#type' => 'button',
        '#submit' => array('emtr_shift_plan_form_ajax_submit'),
        '#value' => 'Save',
        '#ajax' => array(
            'callback' => 'emtr_shift_plan_form_ajax_submit',
            'wrapper' => 'postions',
        ),
        '#id' => 'ajax-save-form-values',
    );

    $form['postions'] = array(
        '#type' => ' container',
        '#prefix' => '
',
        '#suffix' => '
',
    );

    // code here to populate the positions container

}

function emtr_shift_plan_form_ajax_submit($form, &$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt

    return $form['positions'];

}

EDIT:

As a workaround I found it is possible to manually rebuild the form a second time in the ajax callback with $form = drupal_rebuild_form('emtr_shift_plan_form', $form_state);, but is seems inefficient building the form twice. Can I just swap the order of these events over as opposed to having the build the form twice per ajax request?

You could try like this making submit different and callback different and see if it helps.

$form['save'] = array(
    '#type' => 'button',
    '#submit' => array('emtr_shift_plan_form_ajax_submit'),
    '#value' => 'Save',
    '#ajax' => array(
        'callback' => 'emtr_shift_plan_form_ajax',
        'wrapper' => 'postions',
    ),
    '#id' => 'ajax-save-form-values',
);

function emtr_shift_plan_form_ajax($form, &$form_state){
  return $form['positions'];
}
function emtr_shift_plan_form_ajax_submit($form, &$form_state) {

    ddl('ajax submit'); // log the ajax callback is being called

    $form_state['rebuild'] = TRUE; // As the form has already been rebuilt at this point what effect can this have?!?

    emtr_shift_plan_form_save($form, $form_state); // save the values

    // This is the point at which I want the form to be rebuilt
}


Are breadcrumbs not working properly? I am using the following PHP code in the view's header to set the breadcrumbs of the view.

global $base_url;
$path = $base_url . "/tag/" . arg(1) . "/" . arg(2);
$title = ucfirst(str_replace("-", " ", arg(2)));
drupal_set_title($title);
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l($title, $path);
drupal_set_breadcrumb($breadcrumb);
print views_embed_view('article_tag_name', 'default', array(arg(2)));

In my page, the breadcrumbs contain the term ID, not the term name. How do I get the term name?

Seems like your breadcrumb is working properly but you get the real path instead of the path alias. You can use drupal_get_path_alias.

$breadcrumb[] = l($title, drupal_get_path_alias('taxonomy/term/'. arg(2)));

Seems like you are setting title and breadcrumb in a .tpl file? Try to avoid that and put your logic in template.php.
Quick tip: views_embed_view can cause performance issues.


Filter |raw doesn't show entity media image Using the following code for displaying content from a WYSIWYG field:
content.field_body|raw I only got the text without images added in a editor as media. When I remove filter raw I see <drupal-entity data-embed-button="media_browser" data-entity-embed.... is being displayed as a text but not as image.

This output from the body field

<drupal-entity data-embed-button="media_browser" data-entity-embed....

is the raw data stored in the database. The tag <drupal-entity> gets replaced by the text filter "Display embedded entities" when the field is rendered.

If you access the field data directly from the entity #paragraph you bypass this rendering process.

Instead of the raw filter, which doesn't help in any way, it only makes your site vulnerable to the content of the body field, you can apply the text format in a render element processed_text:

  {% set paragraph =  content.field_tabs.0['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_body.value,
    '#format':  paragraph.field_body.format,
  } %}

  {{ body }}


How to inject configuration values into services? In Symfony 2 when defining a service it is possible to inject configuration parameters by referencing them with %parameter.name% strings. For example:

services:
  app.mailer:
    class:        AppBundle\Mailer
    arguments:    ['%app.mailer.transport%']

But what is the correct Drupal 8 approach to injecting configuration values into services? Of course I don't want to use \Drupal::config() inside a service class. Passing configuration values each time a service is referenced does not make much sense either.

I know that I can inject the config service itself and then get configuration values from it, but that looks a bit crappy as my service itself has know how to read data from configuration service. For example:

# Yaml service configuration
services:
  app.mailer:
    class:        mail_module\Mailer
    arguments:    ['@config.factory']

PHP

<?php
class Mailer {
  public function __construct($config) {
    $this->mailTransport = $config->get('mail.config')->get('transport');
  }
}

Is there any other way to do this?

You can use a factory for your app.mailer service. The factory take cares of retrieving the configuration for the service. The service can stay decoupled from the configuration service and does not need to know how the config parameters are named.

services:
  app.mailer:
    class:       Drupal/mail_module/Mailer
    factory:      Drupal/mail_module/MailerFactory:create
    arguments:    ['@config.factory']

class MailerFactory {
  static function create($config) {
    return new Mailer($config->get('mail.config')->get('transport'));
  }
}

class Mailer {
  public function __construct($transport) {
    $this->mailTransport = $transport;
  }
}


Drupal 6 Image Resize Thumbnail Maintain Aspect Ratio We have a content type which has an original image.  There is also a resized version which is not a thumbnail, but not the original size either which is used on a drill down page.

What is the best way to maintain the image aspect ratio for this drilled down page image?  I've found some functions, but is there a module or best practice way to do this?

You want the ImageCache module https://drupal.org/project/imagecache there are also additional actions if you require them https://drupal.org/project/imagecache_actions