Issues with view preview I'm having an issue when creating a new view. The preview pane, upon refreshing/updating" will, instead of updating in the preview section, force the window to navigate to "admin/structure/views/view/MyView/preview/default/" . It doesn't matter is "auto preview" is checked or if I manually press the "update preview" button. I have no idea what i changed recently to start getting this behaviour. My initial thought is that I removed an important js class from a template but I haven't been able to identify which one. I also know it's a theme issue because reverting to any other stable theme fixes the problem!

Is there a better resource for finding what classes are important for core ajax components because I can't find much on the official documentation. Additionally, has any experienced this and know what I might have changed to get this behavior?

I figured out my problem and it had to do with classes as I suspected. For whatever reason, a snippet of javascript that was not previously interfering with the preview functionality just recently started breaking the view. I'm still not entirely sure why but I'm guessing I removed the class in another template and so it was never being rendered and now my javascript was overwriting it.


How is $form['#action'] encoded? I have the following set up:

Webform "my_webform"
Entity type "activity"
The "activity" entity type includes a webform reference field
Activity ID 14 has some content and a reference to "my_webform"
Activity ID 14 has the path "/activity/14"

In a custom module I have a hook_form_alter() to perform some changes based on certain conditions. I'm using the devel module and kint() to debug the structure.

function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_form) {
    kint($form['#action']);
  }
}

Here's the first bit of strangeness:

kint() states the length of the string as being 55 characters. To work out what the characters are, I used the following:

function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_webform) {
    $array = [];
    for ($i=0; $i<strlen($form['#action']); $i++) {
      $array[$i] = $form['#action'][$i];
    }
    kint($array);
    print implode(' ',$array);
  }
}

This produced the following:

f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M

To get a proper look, I tried to remove this spaces:

print str_replace(" ", "", 'f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M');

The result:  /activity/14

The full hook_form_alter():

function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'my_webform) {
    $array = [];
    for ($i=0; $i<strlen($form['#action']); $i++) {
      $array[$i] = $form['#action'][$i];
    }
    kint($array);
    print implode(' ',$array);
    print str_replace(" ", "", 'f o r m _ a c t i o n _ p _ p v d e G s V G 5 z N F _ X L G P T v Y S K C f 4 3 t 8 q Z Y S w c f Z l 2 u z M');

    // exit;
  }
}

Uncommenting the exit; results in the full 55 character string so something's happening after this hook_form_alter() is invoked. Where and how this is happening? How does it alter what print displays after the fact?

I've hardcoded the string in str_replace() for testing but this can be replaced with print implode('',$array);

The form action url is placeholdered to make the form cacheable when used on different pages:

Drupal\Core\Form\FormBuilder::prepareForm

  public function prepareForm($form_id, &$form, FormStateInterface &$form_state) {
    $user = $this->currentUser();

    $form['#type'] = 'form';

    // Only update the action if it is not already set.
    if (!isset($form['#action'])) {
      // Instead of setting an actual action URL, we set the placeholder, which
      // will be replaced at the very last moment. This ensures forms with
      // dynamically generated action URLs don't have poor cacheability.
      // Use the proper API to generate the placeholder, when we have one. See
      // https://www.drupal.org/node/2562341. The placeholder uses a fixed string
      // that is Crypt::hashBase64('Drupal\Core\Form\FormBuilder::prepareForm');
      $placeholder = 'form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM';

      $form['#attached']['placeholders'][$placeholder] = [
        '#lazy_builder' => ['form_builder:renderPlaceholderFormAction', []],
      ];
      $form['#action'] = $placeholder;
    }

The placeholder is replaced before the cached page is delivered to the client. See FormBuilder::renderPlaceholderFormAction and FormBuilder::buildFormAction

The confusion in your debugging attempts is caused by placeholders being replaced not only in rendered forms, but also in debug output you put on the page via kint() or print.


jQuery effects with exposed filters I am trying to produce a view with exposed filters, where:

The options are listed as text links, like a menu
The page automatically updates when a link is clicked
jQuery effects appear to seamlessly 'reorder' and remove items smoothly

eg: http://thisiseyeweb.co.uk/our-work#filter=.e-commerce

I have solved 1 & 2 by using Better Exposed Filters and settings in Views. So I can produce the list of links that make up the menu, and the ajax action to change what is displayed. But I can't make items that should no longer display 'fade out' or remove themselves in a prettier fashion, like the link above.

Many thanks.

You may want to look at this https://drupal.org/project/views_quicksand

It integrates this plugin http://razorjack.net/quicksand/ with views.

Hope it helps.


Overriding field values in Drupal 8 I am attempting to override a node field value in Drupal 8 (on output) using template_preprocess_node. Specifically, I am attempting to override the text of a long text field. I am currently using this:

function THEMENAME_preprocess_node(&$variables) {
  $variables['content']['field_content'] = array(
    '#type' => 'markup',
    '#markup' => '
Testing 123
',
  );
}

And that works, but it totally overrides the field, removing the classes I added to the field wrapper, etc.

Does anyone know how to just set the value only, without replacing the entire field theming, etc? I do not want to manually add the field wrapper classes to #markup.

After doing a quick test, turns out that hook_preprocess_node will always override hook_preprocess_field's attributes.

Therefore, instead of adding the class in hook_preprocess_field, and if you don't want to use '#markup', you could add it in hook_preprocess_node like this:

function THEMENAME_preprocess_node(&$variables) {
    $variables['content']['field_test'] = array(
    '#type' => 'processed_text',
    '#text' => 'Test 123',
    '#prefix' => '
',
    '#suffix' => '
',
  );
}


What is the purpose of _services_controller_execute_preserve_user_switch_anonymous()? I have been having a problem persisting the authenticated session after a successful registration using Services 7.x.3.11 in Drupal 7.

I've sort of solved that issue by commenting out the call to _services_controller_execute_preserve_user_switch_anonymous() inside of sites\all\modules\services\includes\services.runtime.inc. The file's comments read:

  As authentication methods should authenticate user themselves changing global $user variable we preserve incoming session authenticated user and his session so changes made by authentication do not interfere.

Aside the grammer, I do not understand the purpose of this method nor how Services authentication works and integrates with Drupal's core. Can anyone explain why this is necessary for Services to honor Drupal's roles and permissions.

The user register action (which is essentially just an alias of the user.create resource) executes the user register form. Doing so affects the global $user object, which overwrites any existing $user object. Other resources related to the user will also do the same thing.

This is undesirable, as it replaces the global user that you're using to authenticate against the endpoint. So the Services module saves your session before executing any callbacks, and restores it afterwards. This ensures the integrity of the original session.

I think the misunderstanding is simply that you're expecting the user register resource to automatically invalidate the current session, and replace it with a session for the newly created user. I can't see anything in the code that would suggest that's supposed to happen, and it makes sense that it wouldn't...

Imagine your app needed to register 10 users in a batch; if your session was invalidated each time you made a call to user.register, and replaced with a session for the new user, you'd have to logout and potentially re-authenticate before each subsequent registration. Not an ideal situation to be in.


Error: Call to undefined function locale_translation_use_remote_source() in install_import_translations() After I added a language, and set as default language, I get this error.

  Error: Call to undefined function locale_translation_use_remote_source() in install_import_translations()

I didn't enable the Locale module yet. I enabled only the Language module.

What do I have to do?

The error is caused from the fact install_import_translations() is calling a function that is provided from the Locale module (locale_translation_use_remote_source()), but since that module is not installed, the function is not found.

The Language module doesn't have the Locale module as dependency, so installing the first doesn't install the second. The opposite is true: One of the dependencies of the Locale module is the Language module.

I cannot say if this is caused by a bug on Drupal core that doesn't check the Locale module is installed before calling one of its functions, but installing the Locale module would resolve the issue. Once the Locale module is installed, Drupal will be able to find its functions, and you won't see that error again.


How does Browscap work? How does Browscap work? Every Browser seems to be a crawler. I think that is a bug. How can I fix that?

I'll used this tutorial and get this execption on the mobile url:

  PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'false' for column 'is_crawler' at row 1: UPDATE {browscap_statistics} SET counter=counter + 1, is_crawler=:db_update_placeholder_0 WHERE ( (parent = :db_condition_placeholder_0) ); Array ( [:db_update_placeholder_0] => false [:db_condition_placeholder_0] => Firefox 10.0 ) in browscap_exit() (Zeile 134 von x:\somewhere\sites\all\modules\browscap\browscap.module).

In replay to paul-m here are my settings:

Current browscap data version: 4911.
Enable automatic updates is enabled.
Enable user agent log is also enabled.

If I refresh the Browscap data I'll get everytime a timeout after 30 seconds. Also If run the cronjob it timesout after 240 seconds. Not sure what I do wrong.

/admin/reports/browscap/browsers shows me an empty list, but /admin/reports/browscap/crawlers containes all browsers.

I vaguely recall having that same error message, and running update.php solved it. So make sure you've installed the latest version and run update.php.

To get Browscap to log non-crawler user agents, head to /admin/reports/browscap/browsers and follow the instructions. They tell you to enable 'Monitor browsers' on the Browscap configuration screen.

To participate in the issue queue of Browscap, or any Drupal project, go to the project page and look on the right side. You'll see a list of maintainers, and under that a section called Issues for Browscap. Search for your issue there. Or just go to the project's issue list.


Couldn't create a subtheme of a core theme I want to do some customization on seven administation theme, I won't to copy it in my themes folder, I want to create a subtheme of it, it doesn't work for me. this is my info file

name = SEVEN SUB
description = a Seven subtheme
base theme = seven
core = 7.x
stylesheets[all][] = style.css

when I replace Seven by a theme already exists in my sites/all/themes, my theme inherits it, but for core themes it doesn't.
I tried to specify the path of seven, themes/seven and /themes/seven doesn't fix the problem.

In Drupal 7 if subtheme is attaching CSS with exact same file name, Drupal thinks you want to override a CSS file. That seems to be the problem for you. So you are overriding the CSS from the Seven theme by attaching style.css in the info file.

Easiest way to get over that problem is to rename your CSS file into something else e.g. seven_sub.style.css.


How to switch from recommended release of module to dev release? For example, I'm currently using the Geofield module.
I'm using version:

7.x-1.0-beta2 (2011-Nov-17)

Now I see the development version has some functionality that I want.  How do I correctly and safely "upgrade" to the development version of the module?

7.x-1.x-dev (2012-Jan-10)

What I currently do is, remove the geofield from any content types, disable the geofield module, uninstall the geofield module, physically delete the geofield module from my server, and then download and install the dev version.  This seems to work but I'm wondering if there is a more efficient workflow.

(I have drush installed so I'm open to a solution involving drush)

From the working directory (site root) use this command:

drush dl module_name --dev

To get the DEV version.

Or:

drush dl module_name --select

To display a list of available versions.

Afterwards do drush updatedb to apply any database updates made by the module. You should check out https://drushcommands.com/ and all the commands on that page (the aliases are at the end of each section). For example, drush up will check for all possible updates.

In most cases you will not need to disable and uninstall things first but always make sure you are working in a dev environment and have regular backups (e.g. use the backup_migrate module). Drush will also backup the previous version of the module when usingdrush upbut NOT if you directly overwrite withdrush dl`.


How to get Taxonomy Term Field Value in twig I have a taxonomy term with the name 'Colors' and it has 1 image field called field_color_image. In my project I have a node type with a field type of Taxonomy term that refer to Colors. My aim is that I want to show the image in the Colors taxonomy to a node. I already used kint and it didn't really help. How do I achieve this? Thank you beforehand.

To get the url of your term reference image inside the node twig try:

node.field_color_term.0.entity.field_color_image.entity.uri.0.value

Change field_color_term by your field name.

There is another way by configuring the display of your content type and your term like the following:

Content type display should be like

Taxonomy term display should be like

After this configuration you can render your field type of Taxonomy term, it will show the image:

{{ content.field_YOURFIELDNAME }}


Why does a try block affect drupal_set_message? I have a try block set up:

try {
//some code
throw new Exception ( 'My exception message' );
}
catch ( Exception $e )
drupal_set_message('Caught exception: '. $e->getMessage(),1);}

But instead of using 'status', 'warning' or 'error' I used an integer and get a greyish looking message box. Are there any other "hidden" drupal_set_message options? Thx

The second argument of drupal_set_message() should be a string. This string is just added as a class around the message. It an be anything you want.


In a Views page with 3 arguments, 3rd argument default PHP being ignored if 2nd argument is not present Using Views 2, I have a View with 3 different vocabularies as arguments.

The first 2 are intended to be acquired from the URL, however the 3rd will only ever receive it's value from the Default Value PHP Code.

However if argument 2, which is optional, is not supplied, then Argument 3 is not evaluated.

SOLUTION:

Just to clarify where I landed:

The default option Action to take if argument is not present is always set to something (there is no do nothing).

It was already set to Display all values which was not working.

However Provide default argument > Fixed Entry > "all" while the argument wildcard is also "all" is allowing the 3rd argument to be evaluated.

Always keep the optional args in the end otherwise define Action to take if argument is not present or at least set Provide default argument in argument configuration form.


Create a footer menu from primary links and should be able to control what should appear I have a menu at the top on hover it expands. I want a menu at bottom of page with same links, but i may choose what should appear here. Is there any module available for it.

For this functionality, try Footer Sitemap

It allows you to choose which menus and/or menu items will be included in the footer sitemap.

You can then customize the template included to manipulate the markup if you need to.


How to include only an updated custom field in an email created using Rules? I used the Rules module to create a rule with an event "After update existing content". This rule sends an email to the editing user when that user makes an edit to one of the multiple custom fields in a node. I would like to include only the custom field that he/she changed in that email.

Part 1: Processing a single field

Below is a sample of a rule (in Rules export format) that will send an eMail similar to what is asked in the question:

{ "rules_notify_author_of_selected_field_updates" : {
    "LABEL" : "Notify author of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : {
          "data" : [ "node-unchanged:field-optionlist" ],
          "value" : [ "node:field-optionlist" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[site:current-user:mail]",
          "subject" : "Notification about a node with a special field value",
          "message" : "Go checkout the node with nid [node:nid] and title [node:title]: it has a field with a value (which is [node:field-optionlist]) you needed to be informed about ..."
        }
      }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After updating existing content".
In my case I have a selection list field with machine name field_optionlist, and a few possible values.
The Rules Condition checks if the "The selected value changed".
If the Rules Condition is true, then (as Rules Action), an eMail will be triggered to the editing user.

Change the field name of field_optionlist to match the field name of your content type, and adapt the actual eMail details (subject, etc) to fit your needs. Then import it in your own site (using the Rules UI). That's it.

Part 2: Processing a multiple fields

Option 1 - a SEPARATE rule for processing each field

If you have multiple fields, create a similar rule for each of them, so that it will send 1 single eMail for each field update.

Option 2 - a SINGLE rule for processing all fields together

If you have like a dozen fields, using Option 1 implies .... a dozen rules (fairly straight forward rules, but a bit of a maintenance challenge). To consolidate them all in a single rule, you should consider (both of) these refinements:

a Rules Component (which will replace the Rules Action as in the prior rule example), and which you'll be able to reuse within the Rules Action later on by assigning appropriate values to its variables (as further detailed below).
the Conditional Rules module which will allow for conditions to be part of a Rules Action.

Read on for more details on this refinements.

Rules Component

Create a Rules Component that will (simply) produce an eMail, using these Parameters:

User to be notified with machine name user_to_notify.
Updated Field Label with machine name updated_field_label.
Updated Field Value (old) with machine name updated_field_value_old.
Updated Field Value (new) with machine name updated_field_value_new.

Here is an example (in Rules export format) of such Rules component (I trust the eMail subject, content, etc is clear from just reading the source ...):

{ "rules_email_field_updates" : {
    "LABEL" : "eMail field updates",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "user_to_notify" : { "label" : "User to be notified", "type" : "user" },
      "updated_field_label" : { "label" : "Updated Field Label", "type" : "text" },
      "updated_field_value_old" : { "label" : "Updated Field Value (old)", "type" : "text" },
      "updated_field_value_new" : { "label" : "Updated Field Value (new)", "type" : "text" }
    },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Notification about an updated field",
          "message" : "Please be aware that the field labeled \u0022[updated-field-label:value]\u0022 has been updated from \u0022[updated-field-value-old:value]\u0022 to \u0022[updated-field-value-new:value]\u0022.",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Conditional Rules

On top of the field_optionlist field from above, let's assume we add a 2nd field, i.e. a free format text field with machine name field_free_format_text. Assuming that you enabled the Conditional Rules module, you should be able to import the rules example below (in Rules export format) in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names):

{ "rules_notify_editing_user_of_selected_field_updates" : {
    "LABEL" : "Notify editing user of selected field updates",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Option List",
                  "updated_field_value_old" : [ "node-unchanged:field-optionlist" ],
                  "updated_field_value_new" : [ "node:field-optionlist" ]
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "component_rules_email_field_updates" : {
                  "user_to_notify" : [ "site:current-user" ],
                  "updated_field_label" : "Free Format Text",
                  "updated_field_value_old" : [ "node-unchanged:field-free-format-text" ],
                  "updated_field_value_new" : [ "node:field-free-format-text" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}

If you're familiar with Rules, the above Rules example should be self explaining. If you're not, here are a few more details to explain the rule:

Rules Event: After updating existing content.
Rules Conditions: Check if we're processing content that has either of our 2 fields.
Rules Actions:

If the value of field_optionlist changed, then invoke the Rules Component, with parameters related to this field.
If the value of field_free_format_text changed, then invoke the Rules Component, with parameters related to this field.

Voilà, happy (Conditional) Rules-ing!


A question about performance with Form API and Ajax callbacks Im creating a dynamic form, using FORM API.
Several lines of results, fetched from DB, and several functionnalities like deleting a row, adding a row, modifying quantites and calculating total prices.

I did everything using ajax callback, but Im not sure this is the best way of doing it, especially with the 'change quantities' and 'calculating prices' functionnalities.

What I understand about AJAX Callbacks is that a full refresh of the form is done during callback (using cache if possible), and that alony a certain part of the form is returned (using return $form[XXXX]).

So when I change a quantity input field, the form is rebuild, and Im updating the price col and total.

The question im asking to myself is : should I use simple javascript to manage my prices when quantities change ? For me its seems more logical, avoiding by the way useless PHP requests.

As Im not sure about it, likely to forget something important, I prefer asking it to you guys. Thx !

I build such a dynamic form recently and asked me the same question. I did go with the Drupal-way and only used the Form API with zero lines of custom JavaScript. In general you have to weigh the pros and cons of server-side vs. client-side processing. For me these are:

Form API approach

(+) No custom JavaScript/jQuery code neccessary.
(+) You have the full power of the Form API including validation and storing of data inside $form_state (This was one of the main reasons for me since I was using this inside a multi-step form).
(+) Logic stays on the server. You probably need some server-side functions or do not want to expose your logic to everyone.
(-) It will be slower then a JS approach (depends on your server's performance).

JavaScript approach

(+) Fast. Since you do all processing on the client, you can update values instantly.
(+) May be easier to implement. It can be more straight-forward since you don't need any deep Form API knowledge.
(-) You have to fiddle around with jQuery selectors to somehow pass data to Drupal (maybe using hidden fields). This is not always nice and things can break if the HTML structure changes.

Normally I would prefer a JavaScript approach since the user experience can be much better. But in my recent case I really liked it to not have to write any custom JS code and let Drupal handle all the AJAX stuff. I was really impressed by the capabilities of the Form API.


Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php? Drupal 7 comes with some files (authorize.php, cron.php, update.php, xmlrpc.php) that bootstrap Drupal, and execute specific tasks.

Are there any cases where a module would need a similar file to bootstrap Drupal, and execute specific tasks? What are the pros of using this method instead of using a menu callback?
Why does Drupal use cron.php, but it uses a menu callback for the batch operations?

If you examine these files you will see that they share the bootstrap process, but the rest is different.

index.php calls menu_execute_active_handler, which is a fairly heavyweight function.  It essentially does everything to render a page (lots of hooks get called).

cron.php just calls drupal_cron_run, which is fairly lightweight (it just calls everything that implements hook_cron and also bumps up the execution time via set_time_limit.  This can decrease the memory footprint for expensive tasks (like rebuilding search indexes).

Addendum to address comment

Routing everything through index.php is good (front controller pattern).  However, I see it being acceptable to have an extra script entry point for maintenance tasks that essentially run a single hook.  I think of this as tasks that could normally be handled by drush, but need to be web-accessible or if a site doesn't have CLI capabilities.  I have also run into a few cases where a site would bootstrap, but abort because of major problems (like a severely damaged menu cache).  A maintenance script can fix this, if drush can't be used.  It is worth noting, though, that extra precaution needs to be taken to lock down the scripts against malicious access and use.


In Drupal Commerce, how can I decrease stock of product B when buying product A with rules? I'm having some issues writing some rules for my site.

Let's say I have two products. B and C, as well as a combined product called A. Buying product A should decrease the stock of B and C by 1, but the stock of product A should also always be the lowest stock of B or C.

I can't, for the life of me, find out how to do this, and googling has turned up zero results.

Are you using the Entity Reference module?  You will somehow need to set up the relationships between A + B + C in Drupal, and Entity Reference is one Rules-module compatible way to do this.

Another more flexible but more complicated way would be to use the Relation module.


set specific time to cron for specific php script Actually i want all unpublish nodes to be delete automatically whose created date is 2 days ago. I can write php script for that and also include that code in hook_cron api.

but i am confused that my site is set to be run cron after every 3 hours and i want that php script to be run after 24 hours. can i set specific cron time for specific job. i dont want change the site cron job time.

Set system cron to every 5 minutes, and use Elysia Cron to manage particular tasks:

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

  [NEW IN 2.0] Set the timings and frequencies of each cron task (you can run some jobs every day at a specified hour, other only monthly and so on...). For each task you can simply choose between some frequently used options ("once a day", "once a month" ...), or use a powerful "linux crontab"-like syntax to set the accurate timings. You can even define your frequently used options to speed up site configuration.


Disable the /blog route I'm using Drupal 6.16. I would like to permanently disable the /blog path (and all its sub-paths, but not the Blog module.

Is this possible?

You can do this with hook_menu_alter() in a custom module or theme, for example using the following code.

function custom_module_menu_alter(&$items) {
  unset($items['blog']);
  unset($items['blog/%user_uid_optional']);
  unset($items['blog/%user/feed']);
  unset($items['blog/feed']);
  return $items;
}

Make sure to clear the cache.


Add Form frields to View I'd like to generate a view of Employee names, but I'd like to embed it inside a form as well as add checkboxes next to each Employee name. I tried to use Rewrite the output of this field but my <input/> tag is getting stripped out when being displayed.

How would you recommend I do this?

I ended up using Views Bulk Operations to generate the page content and then I added some javascript and css to hide certain things and to also add some extra fields, etc.

It was a total hack, but it got me through on a time crunch.


How to get list of module folders which can be deleted safely? I've uninstalled a lot of unnecessary modules recently through admin/modules/uninstall.
Now I want to understand what folders of the modules can be deleted from sites/all/modules.

I've tried drush pmi, but there is too much information.

How can I get list of folders which can be deleted safely now? Any drush command may be?

Use this:

drush pmi --fields=type,project,title,status,path --format=table|sort

This gives you a module list with five columns:

First is the type of project: module or theme.
Second one is the module project, for exampe views, logintoboggan, admin_menu, etc.
The third one is the installation status: enabled (in use), disabled (not in use but install info in DB) and not installed (it hasn't been installed yet or it have been already uninstalled).
Fourth column is module name. A module downloaded from drupal.org can have several modules inside (the downloaded module is the project and the inside modules are the real modules).
The fifth column is the path to the module.

With this information you can safely remove every project (second column) that all of its modules are in 'not installed' state.

For example, see this fragment list:

module  job_scheduler  Job Scheduler                enabled        sites/all/modules/contrib/job_scheduler
module  job_scheduler  Job Scheduler Trigger        not installed  sites/all/modules/contrib/job_scheduler/modules/job_scheduler_trigger
module  jquery_update  jQuery Update                enabled        sites/all/modules/contrib/jquery_update
module  l10n_client    Localization client          enabled        sites/all/modules/contrib/l10n_client
module  l10n_update    Localization update          enabled        sites/all/modules/contrib/l10n_update
module  languageicons  Language Icons               enabled        sites/all/modules/contrib/languageicons
module  ldap           LDAP Authentication          not installed  sites/all/modules/contrib/ldap/ldap_authentication
module  ldap           LDAP Authorization - Roles   not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_drupal_role
module  ldap           LDAP Authorization           not installed  sites/all/modules/contrib/ldap/ldap_authorization
module  ldap           LDAP Authorization - OG      not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_og
module  ldap           LDAP Feeds                   not installed  sites/all/modules/contrib/ldap/ldap_feeds
module  ldap           LDAP Help                    not installed  sites/all/modules/contrib/ldap/ldap_help
module  ldap           LDAP Query                   not installed  sites/all/modules/contrib/ldap/ldap_query
module  ldap           LDAP Servers                 not installed  sites/all/modules/contrib/ldap/ldap_servers
module  ldap           LDAP SSO                     not installed  sites/all/modules/contrib/ldap/ldap_sso
module  ldap           LDAP Test Module             not installed  sites/all/modules/contrib/ldap/ldap_test
module  ldap           LDAP User Module             not installed  sites/all/modules/contrib/ldap/ldap_user
module  ldap           LDAP Views                   not installed  sites/all/modules/contrib/ldap/ldap_views
module  libraries      Libraries                    enabled        sites/all/modules/contrib/libraries

You can safely remove the ldap module because all modules are not installed but not job scheduler because one of its modules is enabled.


How to setup voting on user profiles? I've got a website where people vote on a user using a button found on the user's profile page, and where users are ranked on the homepage based on the number of votes to their name (along with some fields associated with their account).

I'm trying to implement this voting system using another module (because the voting API isn't particularly well documented). Unfortunately, the Rate module is only suitable for nodes and comments, and the Fivestar module is not suitable for this purpose (I just need a single vote button).

I've also tried adapting the Flag module, although this is proving to be difficult, because I need the ability for users to vote a maximum of once per week on a profile, and by default, it does not allow this.

I'm using Drupal 7, and I have access to cron jobs and full control of the drupal installation.

I'd be grateful if anyone who has experience with the voting API, or a different module could direct me on how to set up this system.

if you end up getting stuck, you could create a Rule that populates a node when a user is created, and essentially create a node-based profile that the user can edit, then use Rate. Look at Node Limit to limit the profile count to 1 node per user, and set permissions on the content type to restrict the user being able to only edit (and not delete) their own content.

Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

Rate:

  This module provides flexible voting widgets for nodes and comments.

Node Limit:

  The Node Limit module allows administrators to restrict the number of
  nodes of a specific type that roles or users may create. For example,
  if a site has an "Advertiser" role that can create "advertisement"
  nodes, then the node limit administrator can restrict all users in
  that role to a specific number of nodes. He may also restrict users on
  a per-user basis.


What are the criteria to decide between modules ThemeKey and Switchtheme? There are (at least) 2 modules that allow for switching between themes, i.e.:

ThemeKey.
Switchtheme.

What are the typical criteria, or pros/cons, for a site builder (without any custom coding or custom theming) to decide for either one?

I have the impression that using ThemeKey the administrator (only) determines how the theme is switched, while by using Switchtheme it is rather the user who decides (from a list predefined by the administrator). Am I close?

Switchtheme is a user-driven theme switcher with a couple of automatic options. It provides a couple of blocks (displayed via a custom Switchtheme permission) where a user can select a theme to choose on a per session (or user account) basis.

Its automatic (admin configured) solutions are:

A per-browser automatic switcher through the Browscap module
A per-URL switch through adding a ?theme=theme_machine_name query parameter to the page request (e.g. http://example.com/?theme=seven)

ThemeKey is a combination of user/admin driven theme switching based on various settings & rules.

Its theme switching solutions provided are:

A per-alias solution that allows to set a theme for each Drupal alias
A per-node solution that allows a permissioned user to set a theme for any node they create (as well a default option).
A per-user solution that allow a user to set a default theme for their configured account.
A chain of custom rules that evaluates various Drupal system, user, comment, node, taxonomy, and Views properties.


LDAP SSO does not authenticate user on homepage I have configured ldap sso and it is working so far for all Url paths except for the homepage.

I get authenticated on /user/login/sso and I get authenticated on /whatsoever but I don't get authenticated on /
The settings for Automated SSO is checked and my  settings for Apache look like this:

 <Location />
            AuthType Kerberos
            KrbAuthRealms xyz
            KrbServiceName HTTP/xyz
            Krb5Keytab /usr/local/apache2/conf/conf.d/drdc.keytab
            KrbMethodNegotiate on
            KrbMethodK5Passwd off
            KrbSaveCredentials on
            require valid-user
    </Location>

I did check the default excluded paths in the ldap sso module, but couldn't find the path / there.
I have tried to redirect every not authenticated user to /user/login/sso but somehow this results in "to many redirects"
(I want to keep /user/login/ free for loggin in as admin user without kerberos)

if ($event->getRequest()->getRequestUri() != '/user/login' && $this->currentUser->isAnonymous()) {
  if (preg_match('/\/comment\-([\d]+)/', $current_path)) {
    $destination = str_replace('/comment-', '#comment-', $current_path);
    user_cookie_save(['destination' => $destination]);
  }
  $url = '/user/login/sso';
  $response = new RedirectResponse($url);
  $event->setResponse($response);
  return;

Any idea?

This works now after unchecking this setting in the SSO-Module konfig:


New User Registration take long time (more than 60 seconds) New user registration take too much time in my drupal 6 website. When we perform Add user in administrator section, it is working normally, within one or two second we can add users. But when we are trying to Create new account, it takes long time.

I have enabled CCK, Content Profile,Token,CAPTCHA,Views Modules.

How does debug it ?.

You can install the devel module and see which part of Drupal that slows things down. You could start out by taking a look at the queries that are run.


Any way to use the Scheduler module with the Bean module? I use the https://drupal.org/project/scheduler module with standar content types.

But I see no integration with the Bean module

Is there any way to use the Scheduler module with the Bean module?

If not, are there any other module for this. I need to set both publishing and unpublishing dates for bean nodes.

Scheduler,

  ...allows nodes to be published and unpublished on specified dates.

As for Bean,

  Bean is an acronym that stands for Block Entities Aren't Nodes.

Emphasis mine in both.

So no, you can't use Scheduler with Bean as Bean doesn't use nodes. There's no such concept as "bean nodes".

I doubt you'll find a pre-built module with arbitrary scheduling for any type of entity. Being 'published' is a concept specific to the node entity type; not all entity types have that characteristic, so I doubt you'll find anything generic.

You'll probably need to write something from scratch. The code for scheduler will be the best starting point, but it'll need to be adapted to work with entities (or at least the Bean entity type).


Images Not Uploading to sites/default/files/* I transferred my website to a live hosting from my local computer. Now the image files don't seem to upload to the correct folders. The images that I added while the site was local appear fine, but if I try to add new ones the preview is broken. However, if I click the link next to the preview I get the image. It seems like the images are not going into the sites/default/files/style/... sub directories. All of directories have permissions of 0755 or 0775.

Please check admin/config/media/file-system page on your site to see if the file directories are set correctly and accessible by Drupal. It's possible the server is configured differently from your local installation or the relative directories are set incorrectly in the configuration fields.

As for the comments about permissions and ownership - it seems you can run chmod on the directory, so the intention was that you would run chown on the directory to set the owner to the Apache group (on Ubuntu it www-data).


How to cleanup Wordpress media tags after migration? After migrating from Wordpress to Drupal with the Wordpress Migrate and Migrate modules, content still contains media tags:

[[{"type":"media","view_mode":"media_large","fid":"4202","attributes":[{"class":"media-image","typeof":"foaf:Image","style":"","width":"339","height":"305"}]}]]

What is the best way to strip them out?

Ah found the answer after some digging:

  You have the Media module enabled, so the migration renders image references as media tags - you need to change your filter to interpret the tags

http://drupal.org/node/1859458#comment-6819442

  You have the Media module enabled, correct? And you're saying when you view (not edit) the nodes you're seeing the media embeds ([[{"type":"media"," etc.) instead of the image itself? Please go to /admin/config/content/formats and make sure that the text format you've chosen for the imported bodies has "Convert Media tags to markup" enabled.

http://drupal.org/node/1642352#comment-6136596

http://drupal.org/project/media


How to prevent button to use validation function? I have a form with a submit type element and a button type element.

For the form I have a validation and a submit handler functions.

The validation should occur only when I click on the submit type button, but it is also getting used when I click on button type element.

How can I prevent button type element from using the validation function.

P.S.

I have used button type for #ajax.

You are looking for two Form API entries:
#ajax['prevent']:

Description: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'. Multiple events may be specified separated by spaces. For example, when binding #ajax behaviors to form buttons, pressing the ENTER key within a textfield triggers the 'click' event of the form's first submit button. Triggering Ajax in this situation leads to problems, like breaking autocomplete textfields. Because of that, Ajax behaviors are bound to the 'mousedown' event on form buttons by default. However, binding to 'mousedown' rather than 'click' means that it is possible to trigger a click by pressing the mouse, holding the mouse button down until the Ajax request is complete and the button is re-enabled, and then releasing the mouse button. For this case, 'prevent' can be set to 'click', so an additional event handler is bound to prevent such a click from triggering a non-Ajax form submission. This also prevents a textfield's ENTER press triggering a button's non-Ajax form submission behavior.
Values: String. Possible values: One or more jQuery events, with multiple events separated by space characters.

#limit_validation_errors:

Description: Provides an array of sections which are parts of $form_state['values'] which should be validated, implying that sections which are not listed should not be validated. This is normally used in multistep forms in the case of a "back" button, for example, where '#limit_validation_errors' => array() would mean not to validate anything as form values on the current page are to be discarded anyway. #limit_validation_errors does not have any effect if #submit is not set. More discussion is in the form_set_error() documentation.
Values: array indicating sections of the $form_state['values'] which should be validated.


How to use image URL in custom Views? I use the Image URL Formatter module for my custom Views. The Views settings look like so:
Setting field:

Setting custom text:

This is the result I get:

Inspect html

http://example.com/sites/default/files/color-placeholder/team-1.jpg
)"&gt;

  Kate Benke
  Back-End Developer

How should I correct my config to use mage URL?
Note: I don't want override template.

Views field strips out
 tag. To add background image you need to follow below steps:

Add global custom field into view header and put below code.

Now assign background-img class to  Global :Custom text field like

.

{{ field_social }}
{{ title}}
{{ field_profession_team }}

  Note: Use Global Text Area in view header and select an input filter
  where html tags aren't limited i.e. full html text format


Fetch result of query twice I faced with problem while fetching query results, my code:

$result = $query->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result->fetchAllKeyed(2, 0);

But the $array2 is empty, so fetchAllKeyed cut all values from $result.

I'm already tried to use the following:

$query2 = clone $query;
$result = $query->execute();
$result2 = $query2->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result2->fetchAllKeyed(2, 0);

It's works, but I don't want do two queries instead of one.

So, how can I do two (or more) different "fetch" from one result?

Since fetchAllKeyed() internally uses foreach loop to sort the data, the answer given by  Suranga Panagamuwa Gamage to use fetchAssoc() and then a loop seems the most efficient way.


How to link to login page? I am trying to do something a priori simple.

I wish in a template to add a link to the login page.

I found this documentation, so I know how to link to a node etc. but to a url type "/ login", I did not find.

Do you know how to do it ?

You can use the link function and the route for the login page (user.login), e.g.

{{ link('Login', 'route:user.login') }}


Controller is loading twice after search form is submitted I created a custom module that I consume an external api. I have also created a custom form (its action points to controller url) which filters the data. However, when I press the search button and the controller is loading, despite I get the right results immediately the controller is reloading and consequently I loose the filtered results.
How I can stop this behaviour?
This is my code so far:
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $ada = $form_state->getValue('ada');
    $sector = $form_state->getValue('sector');
    $sub_sector = $form_state->getValue('sub_sector');

if ($sub_sector=='') {
  $subject_unit=$sector;
} else {
  $subject_unit=$sub_sector;
}

    $datefrom = $form_state->getValue('datefrom');
    $dateto = $form_state->getValue('dateto');

    $params=[
    'type'=>$subject_unit,
    'datefrom'=>$datefrom,
    'dateto'=>$dateto,
    'freetext'=>$freetext,
    'ada'=>$ada
  ];

}

controller:
class DiafaneiaController extends ControllerBase {

  public $filters=[];

  public function getList(Request $request) {

    $filters = \Drupal::request()->request->all();

    $data = array();
    $response = $data = $result = null;

    $page = pager_find_page()+1;
    //echo 'pageNo:'.$page;

    if (function_exists('diafaneia_reponse')) {
      $response = diafaneia_reponse('https://diafaneia.hellenicparliament.gr/api.ashx?q=documents&pageSize=20&pageNo='.$page.'&sector=0216896c-4d26-49de-b896-a2b600ab3843', 'GET',$filters);
    }

    if ($response) {

      $result_docs = json_decode($response);
      $data = array();

      // # add all the data in one multiple dim array
      $data['title'] = 'products to consume REST API';
      $data['docs'] = $result_docs;

$num_per_page = 10;
$offset = $num_per_page * $page;

// Now that we have the total number of results, initialize the pager.
pager_default_initialize($result_docs->TotalRecords, $num_per_page);

$render = [];
$render[] = [
  '#theme' => 'diafaneia_list',
  '#data' => $data,
  '#type' => 'remote',
];

$render[] = ['#type' => 'pager'];

    }
    return $render;
  }

It's unclear how both pieces of code are connected with each other.
If you are handling the form values in form submit you need to pass the resulting parameters to the controller:
public function submitForm(array &$form, FormStateInterface $form_state) {
  // prepare $params
  $form_state->setRedirect('route_to_controller', [], ['query' => $params]);
}

If you are pointing the form action to the controller
$form['#action'] = Url::fromRoute('route_to_controller')->toString();
$form['#method'] = 'get';

then there is no form submit and you have to process the submitted values in the controller.


How to optimize APC when running many sites with common codebase? When having many (+100) drupal sites on a server with a common codebase, what is a good setup to achieve good APC performance?

a) Increase APC memory to something really large (>10GB)

b) Less sites per server

c) Drupal multisite

d) Pseudo multisite. Shared Drupal core symlinked to each site.

e) ?

I would prefer option d). Will APC cache the absolute path to each file?

I think the key here is to limit the total number and size of your PHP scripts. You've already taken the first step by running them off a shared codebase. The next step is to make sure you're not duplicating modules or themes that are shared. For example, you should have sites/all/modules/views, not sites/site1.com/modules/views and sites/site2.com/modules/views.

Once you've done that, I can't imagine that the total size of your php files would be more than, say, 200MB.

The next step is to configure APC and figure out exactly how large all of your php scripts are. For a production server, I like to permanently cache my php scripts. Place the following in your apc.ini file:

apc.enabled=1
apc.shm_segments=1
apc.shm_size=512
apc.cache_by_default=1
apc.stat=0
apc.ttl=0

Note the apc.shm_size=512 setting. We've purposely set it to something much larger than we think we will need. Once this is set (and you've restarted Apache), you should hit every single php script on your site so APC caches each of them. This includes the module admin page, views, theme pages etcetera for each of your sites. Once you're done with that, load up the apc.php script and see how much memory APC is actually using and adjust the apc.shm_size downward accordingly.

I have detailed instuctions on configuring APC for Drupal on Github.


redirect internal body urls temporarily for local development I have painstakingly moved my production site to a local dev server to do some offline edits.  However, all of the internal site links located in the body of whatever page still point to the production site.

How do I temporarily redirect urls in the body of pages to the local dev server?

I need

  "examplepage.org/randomcontent"

to redirect to

  "examplepage/randomcontent"

NOTE: All the drupal nav pages via admin menu work correctly.  Seems like a common problem, but I can't find a straight forward solution.

If there is given hard coded URL then you need to change it one by one , and if its coming through program or Drupal standard behavior then you can check it with clearing the cache.

Following are the way you can check:

1. Check settings.php to ensure that $base_url is set to "http://localhost"

2. Check settings.php to ensure that MySQL settings are correct

3. Take an SQL dump of the entire local database and searched for any references to live site URL

4. Delete all the local cache data from database

5. Check various blocks to ensure that there was no hard coding of links


how to hide particular comment programmatically not sure why:

function MY_MODULE_comment_view_alter(&$build) {
    $build['#comment'] -> status = 0;
}

does not work. It displays comment on the red background, however comment is still visible for all users with 'view comments' rights. What I would like to achieve is simply hide comment so it's not visible.

You achieve this by adding a comment_post_render callback function to the build that outputs nothing:

function MY_MODULE_comment_view_alter(&$build) {
  $build['#post_render'][] = 'MY_MODULE_comment_post_render';
}

function MY_MODULE_comment_post_render() {
  // Nothing here.
}


How to remove front tag from landing page and logged in home page? I have a D7 website on the production environment. On the landing page and logged in page i see the page head title "Front | XXXXXXXXXX". Basically xxxxxx is portal name. I would like to remove the Front keyword from the title and show only XXXXXXXXX.

I tried with several options like
- handling in the template.php with in goodnex_preprocess_page()
- handing via module with hook_init().

Please suggest how to fix it.

There is th module Page Title that fixed this. Also if you're using Metatag, its functionality has moved into the module. They should let you use a custom title that will remove your site name.


How to migrate a physical files into Drupal 7 I'm new to Drupal so forgive me.

I'm trying to migrate an existing site into Drupal. The site is all static content. I'm wondering if I can point Drupal towards a file path, rather then manually creating pages within Drupal and coping the body text.

Is there an easer way to handle a migration. I've looked on google, but most links are for existing CMS systems, or assume a database is provided.

If I do need to copy the HTML into the body, how I can I manually edit the header tag for a page? e.g. I'd like to add CSS and Js references.

Thanks

If the site to be migrated has low double digit numbers of pages or has widely varying HTML and document structure among the pages the easiest solution is copy and pasting it by hand. This may be an opportunity to reorganize the site, add taxonomy terms and clear up other minor content issues.

For larger sites there are several options:

The Migrate module provides a framework and API for you to automate content migration. Using it will involve some coding and require a degree of familiarity with Drupal.

The Feeds module is generally used for importing data like RSS feeds but can be used to import site data. For example, it will import a CSV file, converting lines to Drupal nodes. I envision a solution copying pages into a structured spreadsheet with fields for Title, Author, Body, etc. and exporting that to a CSV for import via the Feeds module.

For completeness I'll mention the Import HTML module which only has Drupal 5 and 6 versions available. If you found this module suitable to import your content you could import into a barebones Drupal 6 installation and perform a site upgrade to Drupal 7.


Change "Add to bag" to "Add to cart" In the following website, I want to change the string from "Add to bag" to "Add to cart." I am using Drupal 6 and Ubercart.

How could I change it?

You can change this in Ubercart settings using no extra modules...

Go to /admin/store/settings/products/edit/general, which is in Store administration -> Configuration -> Product settings -> Edit -> Product settings in the menu.

The text for 'Add to cart' is editable in the Add to cart button text section.


How do I disable/enable the Advanced Content Filtering (ACF) in CKEditor 4.8.0? Please tolerate me for asking such a question.  All the answers I found are for Drupal 7.  There is barely any talk on this issue for Drupal 8.  I am a beginner in Drupal and I am not a programming oriented person.  However, I am determined to find the solution to make this work.

It seems the most straight forward solution is to add the following line of setting:

CKEDITOR.config.allowedContent = true;

However, where should I add it in Drupal 8?  There's no (ckeditor).config.js, as far as I can find within my Drupal's installation directories.  How or where should I proceed?  Does this matter need coding in order to achieve my goal in Drupal 8?

Many of the CSS classes and scripts embedded within the content are stripped off by the CKEditor either after saving or works in the initial save but are then stripped after editing the content the second time.

If you have the patient for someone like me, please help.  Much appreciated!  If I am tackling the problem in a completely wrong direction, please advise as well.  Thank you!

It seems that the short answer is "no" in Drupal 8. You should ensure that your HTML is W3C compliant and changes to your code will be minimal.


Write errors to the log unless the user is an administrator Under error reporting it is possible (and actually recommended for live sites) to write errors to the log, but not to the screen as well. I don't want to show errors to my users, but at the same time I never check my logs. Is there a way of only showing these errors on screen to administrator users?

Using the devel module you can print to the screen errors that you are seeing, but that requires custom work to catch specific exceptions that you expecting to see.


Custom Testimonial page I need to make a testimonial page, which include 3 parts.

text on the above
video testimonial which have the owner name and his image
text testimonial which have the owner name and his image

I am new at Drupal and using Drupal 7 for start things.

I made 2 content types, first for video testimonials the second for text testimonials

Now I am confused how i will proceed to plan things up.

Thank you for the help in advance

You can do this in many ways. But i suggest that you do it with panels.

In this video tutorial you can see exactly how you can do what you asked for.

You can spice up your testimonial page by adding views displaying random testimonials.


Problem with menu position module I have a menu like this:

In the first sidebar you see the main menu with links.
The second sidebar is a block that is visible on pages that begin with stocklijst/.

The link in the first sidebar links to the first link in the second sidebar. So the menu items both have class active. But when I click on the second link in the second sidebar the menu link in the first sidebar won't be active anymore.

I've installed the Menu Position module to make sure the link is active but it doesn't work. I added a rule like this:

But the menu item isn't active when the path is equal to stocklijst/gezocht.

What am I doing wrong?

UPDATE:
This is my view:

From your comments, I came to know that you have added a new menu and used it as Menu Block in second sidebar region.

But Menu position module doesn't support new menus.

See the following points from Menu Position module page

  This includes affecting:

  The main links of the theme
  The secondary links of the theme
  The breadcrumb trail
  Menu blocks provided by core's Menu module
  Menu blocks provided by the Menu Block module

So inorder to work with your new menu, you need to install Menu Block Module.

Menu Position module works well with Menu Block module.

So if you install Menu Block module you can use your custom menus also.

  So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”

  Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!

I've tested this scenario and it works perfect.


How do I remove a validation handler from a form? I am using the Invite by e-mail module, which has its own hook_form_alter() with a validation handler. I wish to remove its validation handler and use my own validation handler.

Use hook_form_alter() to change the $form['#validate'] to be your custom validate handler.

function custom_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_form_id') {
   $form['#validate'] = array();
   $form['#validate'][] = 'my_custom_validation';
  }
}


How can I add new components to a fieldset? I'd like to customize the webform everytime the user saves a webform node.  I'm using rules with a custom action that updates the webform when the user saves the node.  Looking at devel, I haven't been able to figure out what the proper key to specify a parent fieldset is.

In my action I have the following:

for ($j = 1; $j <= 5; $j++) {
  $node->webform['components'][$i] = array(
    'nid' => $node->nid,
    'cid' => $i,
    'pid' => 0,
    'form_key' => "participant$j",
    'name' => "Participant",
    'type' => 'fieldset',
    'value' => '',
    'weight' => $j,
    'display' => array(
      'addmore' => $i,
    ),
    'extra' => array(
      'description' => 'Please provide the participant information listed below. Required items are denoted with an asterisk.',
      'title_display' => 0,
      'private' => 0,
      'collapsible' => 1,
      'conditional_component' => '',
      'conditional_operator' => '=',
      'conditional_values' => '',
    'mandatory' => 0,
    'page_num' => 1,
    ),
  );
  $i++;

  $node->webform['components'][$i] = array(
    'nid' => $node->nid,
    'cid' => $i,
    'pid' => 0,
    'form_key' => "first_name$j",
    'name' => 'First Name',
    'type' => 'textfield',
    'value' => '',

    'parent' => "participant$j",
    'extra' => array(
      'display' => array(
        'addmore' => $i,
      ),
      'title_display' => 'inline',
      'private' => 0,
      'disabled' => 0,
      'unique' => 0,
      'maxlength' => 60,
      'width' => '',
      'field_prefix' => '',
      'field_suffix' => '',
      'description' => '',
      'attributes' => array(),
      'conditional_component' => '',
      'conditional_operator' => '=',
      'conditional_values' => '',
    'mandatory' => 1,
    'page_num' => 1,
    ),
  );
  $i++;
...

It looks like setting the pid to the parent fieldset's cid achieves my goal.


Strange characters after URL -> /#.UAfaBbTY-iE I'm not sure how it's happened, but on each page there are some characters appended to the URL, similarly to the following one:

http://example.com/rndsite/#.UAfaBbTY-iE

They seem to be the same for each page. Anybody know what is causing this?

Do you have an AddThis widget on any of the pages?  This is a known issue with that widget.  to resolve change this portion of the snippet:

var addthis_config = {"data_track_addressbar":true};

WITH

var addthis_config = {"data_track_addressbar":false};


Is there a hook when a relation is created, updated or deleted? I know how to use hooks like hook_node_presave. Is there also a hook to catch the deletion of a relation or the update of a relation? In the API I cannot find anything.
Maybe there is a workaround?

Thanks.

Relations are themselves entities, so you can use the entity hooks:

hook_entity_insert()
hook_entity_update()
hook_entity_presave()

and so on, checking the $type parameter to react only for the appropriate entity type(s).

There's a full list of available entity hooks in the system.api.php file.


Webform node titles - 6x I have a custom content type that has a webform. One of the components is the node title.
Is there a way to use a token to pull the node title instead of typing it?
I've tried setting %title as default but that simply spits back the token at me as text "%title".
Please advice.

Last I checked, Webform didn't pick up a title token.

But it is possible to send the page's url in an email by using the %server[key] token.

For example, in the Webform tab > e-Mails subtab > E-mail template, include:

http://yourdomain.com%server[REQUEST_URI]

See this page for more info.

EDIT: This comment may have a full solution


Flexslider field: number of thumbs, number photos and thumb slider I just installed the module Flexslider. I want to create an image gallery similar to this one: http://flexslider.woothemes.com/thumbnail-slider.html, with a main big photo slider and thumbs sliders (carousel).

I'm using Flexslider field (that means it will create a gallery with the images of the node) instead of Views. I'm not sure how to show all thumbs (all the images I uploaded to the node) in the strip.

I was playing around with the settings in the section "Edit optionset" of the Flexslider module, specially with Item width, Minumum items and Max items. When I change the values, sometimes it shows 2 thumbnails, sometimes 3, etc, depending of the quantity I put in the values.

The weird thing is, when displaying the node if it shows only 3 thumbnails, the main big slider just will have 3 photos, even if the node have a lot of more photos.

What I need is simple, create a gallery that shows all the images in the slider and per each image it should shows one thumb. How I do that? And what means the fields Item width, Minumum items and Max items

Thanks in advance.

I ended up doing it from scratch. I created a custom node.tpl.php, got all the pictures with

$photos = field_get_items('node', $node, 'field_photos');

Then looping through all items and creating for each item the options

$photos_slide = array(
    'style_name'    => 'large',
    'path'          => $photo['uri'],
    'width'         => '',
    'height'        => '',
    'alt'           => '',
    'title'         => $title,
);

and then print the image:

print theme('image_style', $photos_slide);

You can follow this example http://flexslider.woothemes.com/thumbnail-slider.html in order to know how to set the HTML.


How to creat graphs/plots in Drupal, using python library matplotlib, updated in real time if possible? I would like to display plots and graphs in Drupal nodes.

Can somebody point out a good workflow to get this done?

Ideally, I would like to use the graphical python library matplotlib. But a solution that is more Drupalish would be fine too.

Ideally, I would like to enter numeric values in an interface, and see a graph updated in real time. I have not been able to discover any module(s) for this.

Jakob

I don't think there is an out-of-the-box solution for this. You probably already found the Charts module, but that does not seem to support on the fly updates.

So you would need to create your own module. You could then send your data with an ajax call and redraw the graph using that data  (the form api in Drupal 7 has excellent support for this; create a fieldset with its own div in which you put the graph). I'm working with Highcharts (which I really like) in my own modules and do something similar.


Featurize user roles and permissions can't update I have added user roles and permissions to feature which I use to featurize general site configurations and theme settings.

In the past I believe this worked just fine, however, with my latest push the remote created additional roles instead of changing the names as I had done on dev. I deleted the old roles and kept the ones with the proper names. MySQL drupal.role shows that the roles now have new IDs also which I believe could be the cause of the problem. I shouldn't have deleted the roles that matched dev but since I already did, where do I go from here? Should I manually change the ID's in MySQL?

I'm working on a new site that isn't launched yet but will be importing users from another site.

Here you can see the original role IDs and what is on dev:

Here you can see the role ID's on prod now:

Since production hasn't yet been released and is still under development, I took a risk of mysqldump the drupal.role table and then importing them on prod, which fixed the issue.

LongBoardNode's suggestion of editing the RID on dev would have probably been a better idea,


Theme setting to change block position (region) i want to create a theme setting to change blocks position(region) for ex.

  option_1 block_branding-> region_top block_main_menu-> region_menu

  option_2 block_branding-> region_branding block_main_menu->
  region_header_first

I think that should do something like:

Create a file with a function to change the region of the blocks according to option.
Call this function when the form is submitted.

But I don't how to get block info to change its position.

First of all you should change each desired block region for your theme manually at Administration>Structure>Block layout Tab and then go to the config export function at:  Administration>Configuration>Development>Configuration synchronization>Export Tab>Full archive to export all the block settings for your theme.
Then you should take a look at to the generated YAML files and placed them in a new folder within your theme at /config/install. you then uninstalled the theme and then reinstalled it as the default.


Display members of Organic Groups that are members of a given Organic Group in Views Suppose I have an OG called "Color"
Then, suppose I have OG Groups called:
"Red"
"White"
"Blue"

Within of "Red", there are users that are members.

It is easy to define a filter to display members of "Red".

What I want to do is have a view that displays members of "Red", "White" and "Blue" because each of those OGs are members of "Color".

How do I do that without making each member belong to both "Red", and "Color"?

What you can do is add a relationship to the View for the User entity (current user). From there, you have the ability to create filters based on the OG group(s) that the user belongs to.


show entire Book Navigation tree My question is about how to show the entire book navigation tree in a block (drupal 8)

Thanks to @oknate we can have a Book Navigation block with the top level book showing, But i need the whole tree. (think table of contents)

All the folowing examples assume you are are the top page of a 3 level deep book.

Also, I have a working module at https://github.com/petergus/alt-book-nav.git

Showing the title (top level) book in the book navigation block is done by replacing the following in book/src/Plugin/Block/BookNavigationBlock.php (with a custom module of course)

 // Only show the block if the user has view access for the top-level node.
  if ($nid) {
    $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
    // There should only be one element at the top level.
    $data = array_shift($tree);
    $below = $this->bookManager->bookTreeOutput($data['below']);
    if (!empty($below)) {
      return $below;
    }
  }

with

     if ($nid) {
        $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
        return $this->bookManager->bookTreeOutput($tree);
      }

That only shows the top level and child level though, I want to be able to view the full tree from any page.

I am completely new with drupal 8 and not very handy with PHP so all i could find out was that

     $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
     kint($tree);

returns only the book name and first level
and

     $tree = $this->bookManager->bookTreeAllData($node->book['bid']);
     kint($tree);

(without the $node->book) returns multiples levels, that is, multiple 'below' arrays.

I have no idea how to go further with pulling that information into the block, does someone?

As mentioned above, I have the module that @oknate suggested at https://github.com/petergus/alt-book-nav.git

Greatly appreciating any help, and hoping this questions serves the community.

It turns that I already posted the answer in the question, but somehow missed it during testing!

Removing , $node->book from $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book); does print the entire expanded tree.

If someone has time to add a user form option to the module it could eventually benefit many and get on the drupal.org repo.


How can I append date and time to node titles? I want to append the date and time to node titles. For example, If the title is Test, I want to change it to Test_DDMMYY_hhmmss.

How can I achieve this?

This will do for you

function modulename_node_presave($node) {
      if($node->type == 'node_type_machine_name') {
        $new_date = date("DMY_hms", time());
        $node->title = $node->title."_".$new_date;
      }
}


How to delete a node or a list of nodes with Drush? I discovered the Delete all module which gives you the ability to delete all the nodes of a given content type. However, with this module you can't delete a single node or a list of nodes.

In the question "Can I delete nodes of a given content type with Drush?" I found 2 answers talking about the command drush node_delete <nid> but I can't find this command.

I found in a discussion about node_delete() some code using eval to accomplish this task, but it is using eval:

drush php-eval "global \$user; \$user = user_load(1); node_delete(nid);"

In case that there doesn't exist a functionality implemented to accomplish this, what is the better way to implement this functionality: in the Drush module or create a new module?

Finally I create my own module named drush_delete

Inside the drush_delete.drush.inc file put this code:

<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

Install the module, run drush cc drush to clear the drush cache and use the command like this:

To delete a node use:

drush node-delete 1
drush nd 1

To delete multiple nodes use:

drush node-delete 1 2 3
drush nd 1 2 3

You can found the command in this module:

https://github.com/adrian-cid/drush_commands


What are the differences between the various OpenID widgets available? There seems to be several different widgets for providing easer registration and login. I'm curious how they work and what the difference between them are? For example, there is the OpenID selector, Loginza, and Janrain.

The first and the last link you provided takes to the same project page.

The OpenID Selector module replaces the OpenID login form provided by openid.module (an optional Drupal core module) with the same OpenID selector used, for example, on Stack Exchange sites. Though additional modules, it integrates with login provided by:

Facebook
Twitter
LinkedIn
vkontakte.ru
mail.ru
Windows Live ID

The Loginza module replaces the Drupal core module for OpenID, as it implement OpenID authentication, and it allows to authenticate users using the login provided by the following sites/services:

Google Account
Yandex
Mail.ru
Vkontakte
Facebook
Twitter
Loginza
MyOpenID
WebMoney
Rambler
Flickr
Last.fm
Verisign
AOL
Steam

The other difference between the modules is that the Lorenza module is for Drupal 7, while the OpenID Selector module has versions for Drupal 6 and 7.


How to programatically create an address field I would like to use the address field module in my module.  How do I create an address field and an instance for that field.  I haven't found any code in the module that defines what the array structure should look like.

I found this code in the commerce module (under modules/customer/commerce_customer.module):

if (empty($field)) {
  $field = array(
    'field_name' => $field_name,
    'type' => 'addressfield',
    'cardinality' => 1,
    'entity_types' => array('commerce_customer_profile'),
    'translatable' => FALSE,
  );

  $field = field_create_field($field);
}

if (empty($instance)) {
  $instance = array(
    'field_name' => $field_name,
    'entity_type' => 'commerce_customer_profile',
    'bundle' => $profile_type['type'],
    'label' => t('Address'),
    'required' => TRUE,
    'widget' => array(
      'type' => 'addressfield_standard',
      'weight' => -10,
      'settings' => array(
        'format_handlers' => array('address', 'name-oneline'),
      ),
    ),
    'display' => array(),
  );

I can modify that to meet my needs, if someone is familiar with this module and could point out some attributes that may be missing, I'll accept their response as an answer to this question.

Update The address that I'm importing may contain up to 6 lines for the street address (all for one location) as defined by RETS.  Is it possible to store a street address this long in an address field?  If not I can concatenate the extra addresses into the second address line.

I had a similar question these days, and I tried to see if the Features module could help. Features worked to me.

You can create the field by the UI and then export a feature with the address field already created.
After that you can move the inc files for your custom module and add an include on your .module file:

include_once('[your_module].features.inc');

Then, you will need to add the some lines on your .info from the info file of the exported feature.

Your info file will need something like this:

dependencies[] = "features"
dependencies[] = "text"

features[field][] = "node-article-field_address"

This question may help you too: Develop a module that adds a new content type with custom fields.


Return to calling page after save button I am putting together a simple restaurant menu function for a site. I have a menu content type imaginatively called 'restaurant menu item' I use for each dish. I have created a restauranter's "dashboard" for them to update their site including the menu. With views, I have created a table containing the full menu, a row for each dish and on each row there's an 'edit' and 'delete' button. Their function is pretty obvious I'm sure.

When the edit button is clicked, it goes to the (themed) edit content page. I've used the more buttons module to provide a cancel button. If the cancel button is pressed, then the user is returned to the table page and can continue editing. However, if she clicks on save it simply displays the updated content (and not particularly nicely) and it's not easy for the user to get back to the table and continue their updates.

I was wondering if there's a simple way of returning the user to the table page after the save button? Note if the edit is performed from the more standard drupal content listing admin pages, then it should return to the content listings pages there.

You can use a rewritten "Content: Nid" field to create the Edit link field with a destination parameter that points back to the URL of the page with the table.

The "Link path" field should look something like this:
node/[nid]/edit?destination=path/to/table


How can I find the name of the field store in the DB? I have a content type for which I have created my own img using cck like this:

How can I find the name of the table that stores the img field?

Drupal 7

If the name of the image field is "Dark Image", then the table name in database will be field_data_field_dark_image

Drupal 6

As mentioned in this page, table name should be content_type_YOUR_CONTENT_TYPE_NAME. If the name of the image field is "Dark Image", inside the table you will find a column called field_dark_image that stores field data.


How do I render a custom form on a view page? In my module's routing.yml file I set the form path to a path which also shows a view page. But on that path the form does not get displayed, only the view.

When I change the path in the routing.yml it works, so I guess views somehow overrides/ ignores my form.

How can I do that?

It's only possible to display one "page" on a url, so you can't both display a view and a form or any other "page" for that matter.

You have a few options:

Insert the form into the view (can be done with a global views handler)
Insert the form on the view page by exposing it as a block.
Insert the view on the form page by exposing it as a block.

Probably the easiest solution for you is to convert the view page to a view block and insert it on the form page. Views already has support for this, so you only need a few clicks in the interface to achieve this.


With a WSOD upon deployment of a site, should I first clear the cache, check watchdog logs, or check the Apache logs? With a WSOD upon deployment of a Drupal 8 site, should I first clear the cache, check watchdog logs, check the Apache logs, or something else?

I read the Drupal WSOD triage information here But it doesn't seem to share which solution should first be done in this situation.

This seems to indicate that it could be with the DB, so would I need to check that first?

I just noticed Fixing white screens step by step. It seems to suggest that I should look at the system (Apache) logs first. Am I interpreting this correctly?

Yes. Because of the variety of possible Drupal stack configurations, it's impossible to say you'll always find your error in an Apache log. However, a WSOD generally means PHP has hit a fatal error and it's configured not to dump sensitive debug info to screen.

If that's the case, you might not even have a working Drupal app to make use of its tools like cache clearing, watchdog, etc., so it's best to find where those PHP errors are dumped so you can get Drupal into a bootstrapped state.

Of course, you should know your stack better than anyone else so a cache clear could eliminate the issue if you know the source of the problem. But if you're unsure, Apache logs are a good first start.


'Manage fields' and 'manage display' links not working for content types I did an update of several modules (core included, from 7.xx to 7.26), a couple of weeks ago, and until now I had not tried to access content types.

Today I did, but while I can see the 'manage fields' and 'manage display' links, when I click on them I'm taken to the 'edit' page.  Also, if you have admin_menu installed and just hover on structure/content-type/custom-content-type, a menu with the available edit options appears, but in my case only 'delete' is there.

Searching around I see this is most commonly caused by the 'field ui' module being disabled, but I checked and it's in fact enabled.  I disabled/re-enabled it but nothing happened.

Per this post, I also tried enabling all checkboxes at admin/config/administration/admin_menu under the 'performance' tab, flushed caches, and still no result.

I did the site's update for a client, and still have a version of the site on localhost, where all menus work fine.  I sent them all files/database so their hosting provider would upload the site and now this issue comes up.  I have no access to the database, only the admin pages.  What else could be the problem and how could I fix it?

Thank you in advance.

Solved.  I could get access via FTP and found out there were 2 missing files from the server.  After uploading them the problem is fixed.


Use hook_menu_alter to change access callbacks I'm trying to working with hook_menu_alter, I'm tryng to change, for example, access callback to an admin path (admin/config/account/people/fields).

I've create a permission and I've added to a role.
Now I'm trying this:

function mymodule_menu_alter(&$items) {
   $items['admin/config/people/account/fields']['access arguments'] = array('my custom permission');
}

But it doesn't work.

Can I edit this "system" modules permissions?

Your code is correct (that's definitely the way to override the access arguments for a path using hook_menu_alter()).

If it's not working you just need to clear your caches (and of course make sure that your custom module is installed and enabled).

I just copied your code into a test site, cleared the caches, and no longer receive 403 errors when visiting that page as an anonymous user.


How to configure Compass module with Basic theme? I am trying to use compass framework with Drupal 7, Basic theme and Compass module on my local hosting on Windows. It is already installed on my computer.

Should i install it to my local webserver again somehow, how can i know the path of existing Compass exutable?

Well the only real answer i can give is set up a real webserver on Unix system with ruby (rails or without rails) and use whatever you want. I did not managed to get it running on windows. But ---- windows, lads


Related Content View with multiple Entity Reference Fields I am trying to create a View to display related content based on shared taxonomy terms from multiple vocabularies.

For example:

I have two content types called Car and Parts.

I have two vocabularies called Type and Country.

Content Types:

Car

Entity Reference: Type
Entity Reference: Country

Parts

Entity Reference: Type
Entity Reference: Country

Vocabularies

Type: sedan, convertible, coupe, van, suv
Country: usa, japan, germany

I would like to display a view of related Parts when viewing a Car node.  Furthermore, I only want to display if both Type and Country match.

I’m able to get either Type or Country matches to display by adding the following relationships.

Content: Taxonomy terms on node
(term) Entity Reference: Referencing entity (type)
(term) Entity Reference: Referencing entity (country)

and a contextual filter of:

(Content referencing Taxonomy term from field_country) Content: Nid

Basically, switching the relationship on the contextual filter determines whether or not Type or Country matches should be displayed.  I am having trouble figuring out how to display Parts that match both the Type and Country of the Car.

Basically you need to do the following.

Create a view based on content of type parts (as a block I'm guessing)
Add a relationship "Content: Country (field_country)" using the defaults
Add a relationship "Content: Type (field_type)" using the defaults
Add a contextual filter for "Taxonomy term: Term ID" with the following settings.

Relationship: country
Provide default value: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms to vocabulary: Vocabularies country.
Multiple-value handling: Filter to items that share all terms

Add another contextual filter for "Taxonomy term: Term ID" with the following settings.

Relationship: type
Provide default value: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Limit terms to vocabulary: Vocabularies type.
Multiple-value handling: Filter to items that share all terms.

Now just place your block on all car pages.


What are Text Filters and Input Formats? In views, when I add a field of type body, there are some options given: text_default, text_plain, text_trimmed.

How do these options filter the contents of the field and where can they be found in the code??

These are called 'text filters', and a text filter is made up of 'input formats'. Input formats are defined in hook_filter_info().

You can read more about text filters here: https://www.drupal.org/node/213156


How can I force changes to go to settings.local.php? I have a settings.php file in git which has the logic to include settings.local.php already uncommented, with settings.local.php in .gitignore for security purposes.

I would like to be able to install Drupal (8.3.3) so that any changes which are made by the installer (by default: hash salt, databases array, install profile, sync directory location) are made to settings.local.php rather than settings.php as the installation currently does. Is this possible?

I think it's possible, but you'll need a custom installation profile to do it.

drupal_rewrite_settings() takes a 2nd parameter for a custom path to settings.php, but none of the default core methods make use of it, they let it fallback to sites/default/settings.php. It's used in three key places:

Drupal\Core\Installer\Form\SiteSettingsForm::submitForm()
drupal_install_config_directories()
install_write_profile() (deprecated)

The form and install_write_profile() are invoked from an install task, so those can be altered with hook_install_tasks_alter(). drupal_install_config_directories() is invoked from the form submit method, which you'll be overriding anyway, so you can replace it with your own method.

A completely untested example:

profiles/foo/foo.profile

function foo_install_tasks_alter(&$tasks, $install_state) {
    $tasks['install_write_profile']['function'] = 'foo_install_write_profile';
    $tasks['install_settings_form']['function'] = 'Drupal\foo\Form\SiteSettingsForm';
}

function foo_install_write_profile($install_state) {
    // Only need to write to settings.php if it is possible. The primary storage
    // for the install profile is the core.extension configuration.
    $settings_path = \Drupal::service('site.path') . '/local.settings.php';

    // Make sure the file exists.
    touch($settings_path);

    if (is_writable($settings_path)) {
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];
        drupal_rewrite_settings($settings, $settings_path);
    }
    elseif (($settings_profile = Settings::get('install_profile')) && $settings_profile !== $install_state['parameters']['profile']) {
        throw new InstallProfileMismatchException($install_state['parameters']['profile'], $settings_profile, $settings_path, \Drupal::translation());
    }
}

profiles/foo/src/Form/SiteSettingsForm.php

namespace Drupal\foo\Form;

use Drupal\Core\Installer\Form\SiteSettingsForm as BaseForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\Crypt;

class SiteSettingsForm extends BaseForm {

    public function submitForm(array &$form, FormStateInterface $form_state) {
        global $install_state;

        // Update global settings array and save.
        $settings = [];
        $database = $form_state->get('database');
        $settings['databases']['default']['default'] = (object) [
            'value'    => $database,
            'required' => TRUE,
        ];
        $settings['settings']['hash_salt'] = (object) [
            'value'    => Crypt::randomBytesBase64(55),
            'required' => TRUE,
        ];
        // Remember the profile which was used.
        $settings['settings']['install_profile'] = (object) [
            'value' => $install_state['parameters']['profile'],
            'required' => TRUE,
        ];

        $settings_path = \Drupal::service('site.path') . '/local.settings.php';
        drupal_rewrite_settings($settings, $settings_path);

        // Add the config directories to settings.php.
        $this->installConfigDirectories();

        // Indicate that the settings file has been verified, and check the database
        // for the last completed task, now that we have a valid connection. This
        // last step is important since we want to trigger an error if the new
        // database already has Drupal installed.
        $install_state['settings_verified'] = TRUE;
        $install_state['config_verified'] = TRUE;
        $install_state['database_verified'] = TRUE;
        $install_state['completed_task'] = install_verify_completed_task();
    }

    protected function installConfigDirectories() {
        global $config_directories;

        // Add a randomized config directory name to settings.php, unless it was
        // manually defined in the existing already.
        if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
            $config_directories[CONFIG_SYNC_DIRECTORY] = \Drupal::service('site.path') . '/files/config_' . Crypt::randomBytesBase64(55) . '/sync';
            $settings['config_directories'][CONFIG_SYNC_DIRECTORY] = (object) [
                'value' => $config_directories[CONFIG_SYNC_DIRECTORY],
                'required' => TRUE,
            ];
            // Rewrite settings.php, which also sets the value as global variable.
            $settings_path = \Drupal::service('site.path') . '/local.settings.php';
            drupal_rewrite_settings($settings, $settings_path);
        }

        // This should never fail, since if the config directory was specified in
        // settings.php it will have already been created and verified earlier, and
        // if it wasn't specified in settings.php, it is created here inside the
        // public files directory, which has already been verified to be writable
        // itself. But if it somehow fails anyway, the installation cannot proceed.
        // Bail out using a similar error message as in system_requirements().
        if (!file_prepare_directory($config_directories[CONFIG_SYNC_DIRECTORY], FILE_CREATE_DIRECTORY)
            && !file_exists($config_directories[CONFIG_SYNC_DIRECTORY])) {
            throw new Exception(t('The directory %directory could not be created. To proceed with the installation, either create the directory or ensure that the installer has the permissions to create it automatically. For more information, see the online handbook.', [
                '%directory' => config_get_config_directory(CONFIG_SYNC_DIRECTORY),
                ':handbook_url' => 'https://www.drupal.org/server-permissions',
            ]));
        }
        elseif (is_writable($config_directories[CONFIG_SYNC_DIRECTORY])) {
            // Put a README.txt into the sync config directory. This is required so that
            // they can later be added to git. Since this directory is auto-created, we
            // have to write out the README rather than just adding it to the drupal core
            // repo.
            $text = 'This directory contains configuration to be imported into your Drupal site. To make this configuration active, visit admin/config/development/configuration/sync.' . ' For information about deploying configuration between servers, see https://www.drupal.org/documentation/administer/config';
            file_put_contents(config_get_config_directory(CONFIG_SYNC_DIRECTORY) . '/README.txt', $text);
        }
    }

}

The last step, if you want this to be fully automated and possibly avoid errors during installation, is an awkward one. You need to programatically uncomment the include for local.settings.php at the bottom of settings.php.

I'm not aware of any Drupal helpers for that (might be wrong though), so you can probably approach that as a general PHP/other task.

I think the top of the foo_install_write_profile() function would be as good a place as any to do it, unless of course your dev workflow means you can do it before you even carry out the installation (probably best if possible).


More link not displaying on view. Why? I created a view and am expecting the More link to appear but it isn't.

The Content: Body field formatter is set to Trimmed and the trim length is 100. Create more link is ticked, and I have entered "More" in the More link text text box.

Any advice would be greatly appreciated.

You get a more link (that links to the node) if your view lists nodes in the teaser view mode. For any other case the situation is more complex.

Ongoing discussion about this issue: https://drupal.org/node/823380 "More link is always visible on teaser".

Perhaps the best solution for the time being:
https://drupal.org/project/readmorecontrol


How to reference a view using entity reference field type? I have two content types, courses and tutors.
Tutors contains a biography and a large photo

Courses contains lots of other information but more importantly contains a tutor field which is a entity reference field type.  It creates a dropdown list containing all tutors.

The problem I have is that when I create a new course page and select a tutor from the dropdown list, it displays the full biography and large photo.

What I want it to display is the first say 100 characters of the biography and a cropped version of the tutor photo (I have set up a image style which crops the photo to 100px)

I’m guessing there may be 2 ways of doing this.
1)  Customising a teaser
2)  Creating a view but I’m not sure how you reference it and how you would get the view to just show the selected tutor (from the dropdown list above)

I am using Drupal 7

Any advice much appreciated.

Sounds like you know what your doing. Like you say either create a 'view mode' in your content type or create a view. All you have to do with the view is create a relationship (under 'relationships' in the advanced section) to get your entity reference and set a filter for the tutor.

Tried to find something similar to your issue, hope it helps. How to use Entity Reference and Views