Struggling to start a project from scratch I am having 6 months of experience in drupal 6. I can able to handle bugs and any new functionality in the existing project.

But i can't able to move single step ahead in the new project. I know PHP very well and if i need to start a project from scratch in PHP i can do without any hesitation.

But i can't able to do with drupal :(

  What is the problem with me ?
  What should i need to do to start a project from scratch ?
  What are the things i need to improve ?

Any guidance will help me a lot..

Thanks in advance..

It sounds, what Your problem is not in Drupal.

Check the Done Manifesto, probably it will help.

And let's move to Drupal 7 :)


How to use Drupal.ajax() to update #content div on  click? I'm trying to update the #content with AJAX. I've found the Drupal.ajax function and tried to use it with this code, copied from Views module but modified:

var base_element_settings = {
  'event': 'click',
  'progress': { 'type': 'throbber' }
};
jQuery('a').once('custom-ajax-processed').each(function () {
    var element_settings = base_element_settings;

    if (jQuery(this).attr('href')) {
      element_settings.url = jQuery(this).attr('href');
    }
    var base = "content";// $(this).attr('id');
    Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
});

But instead of replacing the #content it alerts the response contents with the title An AJAX HTTP error occurred.
HTTP Result Code: 200
What am I doing wrong? Is it possible to achieve with Drupal.ajax() ?

dont know it can be achievable using drupal.ajax , but created a module for drupal 6 using jquery load and Drupal.attachBehaviors with which you can load any page to any div. Now ported to 7 also :)  this is the module (currently under review process)


How do I search all contents including code from admin? I am a Drupal newbie and I am frustrated in my search for methods that allow admin searches of code in node content fields ie CSS classes.  I'm baffled that there is not a built-in default way to help admins search content like this.

I have looked at many projects for Drupal 7 and Drupal 8 and only a few Drupal 7 modules looked like they could have helped. None of what I have read for Drupal 8 appears to offer code search.

The documentation I have read, and the module I found are the following.

https://www.drupal.org/project/admin_views (D7)
http://drupal.org/project/scanner (D7)
https://www.drupal.org/docs/8/core/modules/search/overview
https://www.drupal.org/resource-guides/content-administration
https://www.drupal.org/project/search_api
https://www.drupal.org/docs/8/modules/search-api/getting-started/common-pitfalls
https://www.drupal.org/project/find_content (D7)
https://www.drupal.org/node/384486

For a quick solution, you can edit the View that powers the Content page (or create a new View, edit a different View, etc), and add the body field as an exposed filter. Combined with a LIKE operator that should give you reasonably good results (though it will possibly depend on what input format you're using).

If you want something more like what you described, i.e. something that searches multiple fields at once, you could install the Search API module, create a results View, and add a combined filter that will search across all the desired fields. This approach takes a bit more effort, but might give more accurate results than the first one, especially if you use (for example) Solr as the backend.


How to diasplay stock quantity of goods in node-product.tpl.php I need to get quantity of goods in stock and display a number in the product page node-product.tpl.php.

Here is what I added in the template, but uc_stock_level() seems not to work properly.

$stock = uc_stock_level($node->model);
if ($stock > 0) {
    print $stock;
} else {
    print $stock;
}

I am using Ubercart 2.

There is not much to uc_stock_level(). Check that you are supplying a model/SKU that is in the table and it is active. If that's the case, you might need to flush your cache to pick up new changes in your template file.


Remove the "Advanced search" form on the result page? On Drupal 8, how can I remove the "Advanced search" form on the result page ?

I can hide it with css :

#edit-advanced,
#edit-help-link {
    display: none;
}

But I would prefer to do it with php or even better with a parameter in admin but I didn’t see any parameter related to Advanced search in

/ Administration / Configuration / Search and metadata

You need to go to:

admin/people/permissions

and uncheck the checkboxes for the users that don't need to use the Advanced Search.


Language information in Session for anonymous users I selected the language preference to be detected with user sessions, the problem is that for anonymous user this preference does not seem to be stored. As this site is not user driven (Meaning that site users don t need to create account in order to browse the site), it s very problematic.

Is there anyway to have this language preference stocked in anonymous sessions ?

For Drupal 7 it's normal, there's no session created automatically for anonymous users, we created a new module that stores and detects the language inside a cookie, see locale_cookie, the benefit of a cookie is that your session table stays small.


HTML tags not supported when sending emails in Drupal 8 This is my code to sending email

   function hook_mail($key, &$message, $params) {
     $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'create_article':
      $message['from'] = \Drupal::config('system.site')->get('mail');
      // $message['headers']['Cc'] = $params['cc'];

      $message['subject'] = 'SUBJECT';
      $message['body'][] = Markup::create($params['message']);
      break;
  }
}

Mails are getting without any issue.But some of the HTML tags are not supporting
Eg: HTML bold,italics....
I have also configured SMTP authentication.

You can't send HTML email with Drupal 8 "out of the box."

To send HTML email, you can use the Swift Mailer module, which has the following features:

  Sending e-mails directly through a SMTP server of your choice, a
  locally installed MTA agent such as sendmail or the mail functionality
  provided by PHP.
  Sending HTML (MIME) e-mails.
  Adding file attachments to e-mails.
  Adding inline images to e-mails.

The Commerce 2 documentation includes a tutorial on how to install and configure the Swift Mailer module.


User profile fields: Get count of fields with value XYZ All user profiles contain these fields:

field_age (integer)
field_category (list: "Category A", "Category B", …, "Category Z")

I want to get the number of users with the value "Category A", "Category B" etc. for the landing page.

How can I get the count of users for each answer? I want to display the number on the landing page for every visitor.

The data does not need to be live data. It may be read from a file that is re-generated every 24 hours.

You can create a view as a block using users as the base table (Structure>Views>Add View and set show=Users and check "Create a Block").  Then turn aggregation on in the advanced settings. Then add the field_category field and select "Group Field". Next add field_category a second time and select "Count". This should give you a column of each category, and the count of how many users exist in each category.

Finally, add the block to the frontpage in the Block Layout.


Get $form_state backup and migrate filter extended class I have form altered the backup and migrate quick backup screen (admin/config/system/backup_migrate) and added a text field. I'd like to use the value of the field to create a new node just before the backup is done. I found a way to "hook" backup and migrate just before it performs a backup, which is great. However, I need to get $form_state['values']['my_value'] and pass that to my function that creates a new node. I can't figure out how to get that passed to the pre_backup() inside the extended class backup_migrate_filter.

From your question, I get you altered the form built from the following function.

/**
 * The quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form($form, &$form_state, $inline = TRUE) {
  backup_migrate_include('profiles', 'destinations', 'sources');
  drupal_add_js(drupal_get_path('module', 'backup_migrate') .'/backup_migrate.js');

  $form = array();

  // Theme the form if we want it inline.
  if ($inline) {
    $form['#theme'] = 'backup_migrate_ui_manual_quick_backup_form_inline';
  }

  $form['quickbackup'] = array(
    '#type' => 'fieldset',
    "#title" => t("Quick Backup"),
    "#collapsible" => FALSE,
    "#collapsed" => FALSE,
    "#tree" => FALSE,
  );

  $form['quickbackup']['source_id'] = _backup_migrate_get_source_pulldown(variable_get('backup_migrate_source_id', NULL));

  $form['quickbackup']['destination'] = _backup_migrate_get_destination_pulldown('manual backup', variable_get('backup_migrate_destination_id', 'download'), variable_get('backup_migrate_copy_destination_id', ''));

  $profile_options = _backup_migrate_get_profile_form_item_options();
  $form['quickbackup']['profile_id'] = array(
    "#type" => "select",
    "#title" => t("Settings Profile"),
    '#default_value' => variable_get('backup_migrate_profile_id', NULL),
    "#options" => $profile_options,
  );

  $form['quickbackup']['description_enabled'] = array(
    '#type' => 'checkbox',
    "#title" => t("Add a note to the backup"),
  );
  $form['quickbackup']['description'] = array(
    '#type' => 'backup_migrate_dependent',
    '#dependencies' => array(
      'description_enabled' => TRUE,
    ),
  );

  $form['quickbackup']['description']['description'] = array(
    '#type' => 'textarea',
    "#title" => t("Note"),
    '#description' => t('This note will be saved with the backup file and shown on the listing page.'),
  );

  $form['advanced'] = array(
    '#type' => 'markup',
    '#markup' => '
' . t('For more backup options, try the advanced backup page.', array('!advancedurl' => url(BACKUP_MIGRATE_MENU_PATH . '/export/advanced'))) . '
',
  );

  $form['quickbackup']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Backup now'),
    '#weight' => 1,
  );

  $form['#validate'] = array('backup_migrate_ui_manual_quick_backup_form_validate');
  $form['#submit'] = array('backup_migrate_ui_manual_quick_backup_form_submit');

  return _backup_migrate_ui_action_form($form, $form_state, 'backup');
}

The only way to pass a value submitted in a form to a hook is to save it into a persistent variable, exactly in the same way a submission handler does.

/**
 * Submit the quick backup form.
 */
function backup_migrate_ui_manual_quick_backup_form_submit($form, &$form_state) {
  backup_migrate_include('profiles', 'destinations');
  if (user_access('perform backup') && !empty($form_state['values']['settings'])) {
    // Save the settings for next time.
    variable_set("backup_migrate_source_id", $form_state['values']['source_id']);
    variable_set("backup_migrate_destination_id", $form_state['values']['destination_id']);
    variable_set("backup_migrate_copy_destination_id", $form_state['values']['copy_destination_id']);
    variable_set("backup_migrate_profile_id", $form_state['values']['profile_id']);

    // Do the backup.
    backup_migrate_ui_manual_backup_perform($form_state['values']['settings']);
  }
  $form_state['redirect'] = BACKUP_MIGRATE_MENU_PATH;
}

Your hook_form_alter() implementation needs to do two things:

Add the form element, as you already did
Add a submission handler to $form['#submit'] ($form['#submit'][] = 'mymodule_submission_callback';)


How to automatically delete all product displays when a product is deleted? To automatically delete the product displays when a product is deleted, is a feature of the module Auto Product Display, but I don't need that module.

Preferably using the Rules module, I would like to accomplish the same.
An issue in drupal.org is present, but currently open.

I'm trying to fetch the referencing product displays:

Trigger: After deleting a Commerce Product

Fetch entity by property
Entity is of type: node
The property by which the entity is to be selected: product (the product reference field)
The property value of the entity to be fetched: ?? (The node
ID of the product is not available to select)

How to get the node ID's of all product displays referencing the product?

1) You need the commerce product id (which is the one of the commerce product that has been deleted) and not the nid because of the reference you are using. If this parameter is not available you must bring it into scope using a proper validation.

Notice that after deleting the commerce product there is no product id so no products are referencing it. The correct trigger should be "before deleting commerce product" but does not exist by default.

Also, how do you handle a Product display (node) with multiple product variations? Should this node be deleted? There should be an additional condition to check if there are other variations for the same product display. Except if you have a 1 to 1 reference.

2) Another option should be to do the opposite which is to fetch all the nodes (Product displays) that have an empty commerce product reference. This is easier to create.


Drupal 7 main-menu - change item text if user logged in I'm using Drupal 7's 'main-menu' to run my site's navigation. In my design, the links to join and sign in are in the main nav.

My join link goes to /user/register so it vanishes when a user is logged in. But my sign in is just /user, so that still shows up when a user is logged in. I want it to be replaced, or at least change the text to something like 'My Profile' instead of 'sign in'.

Ideas?

change the sign in link to /user/login.   It will now vanish when the user logs in.   As for replacing it you would need to write some custom code


menu_get_object() not returning node object when view's display is Entity Reference I needed get field's value and pass it as contextual filter to "entity reference view" just described as views and contextual filters with entity reference field.

But $Node = menu_get_object() is not retuning node object.

The scenario

Nodes Items of custom content type

Title : Sony LCD
Tags : electronic

Title : The godfather
Tags :Books
.
.
Items(n)

Node of custom content type Review. It's node id is 10

Title : Make a Review
Filter Tags : Taxonomy terms reference (e.x electronic, books, movies etc)

Attach a entityform to above node using entity reference and also back referenced with enityreference_current

My Review Item : EnityReference field - Entity reference view - Autocomplete widget
Review : text area

When node/10 is viewed, user will have to fill "my review item",but should be filter based on "Filter tags" that was already set.

Code inside VIEWS PHP under Contextual Filter

$node = menu_get_object ();
$ Related_ids = array ();
    $ Related = field_get_items ('node', $node, 'field_filter_tags') // Get the term reference field
    if ($related && is_array ($related) && sizeof ($related)> 0) {
      for ($i = 0; $i <count ($related); $i++) {
        $ Related_ids [] = $related [$i]['target_id'];
      }
    }
    return implode (',', $related_ids);//to perform AND

Update : I also tried with $node= node_load(arg(1)); , this time $node variable set but not type of node. Then I dpm(arg(1)); it shows string autocomplete(yes just autocomplete not string entered in field).

The entityreference autocomplete paths are defined in entityreference_menu() as:

entityreference/autocomplete/single/%/%/%
entityreference/autocomplete/tags/%/%/%

The wildcard arguments are field name, entity type and bundle respectively. The entityreference_autocomplete_callback() function also accepts an optional entity id and string parameter (the last being the search string).

So while you're expecting the path to be node/[nid], it'll actually be one of the above - which explains why arg(1) is giving you the string autocomplete.

I haven't tried it but you should be able to use arg(6) to get the node ID in your current context.


How to eliminate access to page based on the user ID? I want to control the access of a page based on the user ID and the value of some other fields.

For example, if I am logged in as user #5, I have access to user/5 but I don't have user to the page user/6 and administrator users have access to both pages.

In my case, imagine I have a custom user page and I want to give access only to the owner and to the user selected in a custom field.

I don't think I can achieve that using permissions and in the future I might have more restrictions based on the value of other fields. So ideally, I would like to have a function where I will get the uid and the value of the fields, I will do my checks and I will restrict the access or not.

By the way my pages are panel pages not nodes.

Any idea/help/suggestion?

You will probably need to add a custom hook_node_access code.  In this you can use the view operation to check:

Is the current user the owner (yes - done - allow access)
Is the user an admin (yes - done - allow access)
Does the node have your user access list field (No -done - allow access)
Is the current user's uid in the field values? (Yes - allow access / No -deny access)

This should handle the basic access issues.  You may need to look at how to hide / show links based on access as well.


drupal identify which content type is not used I have a drupal existing project which is slow in performance and many irrelavent extra stuff. what aprroach is best where i can identify that which content type is used or not . Or we can say that which content type is used where

Similar for field/taxonomy that which field/taxonomy is associated with which content type.

Just go to http://example.com/admin/content as user 1 and filter content by content type. If there is nothing, then content type is not used. Note that there may be views or modules that expect some content types to exist, even if you are not using them at the moment, so always make a backup before dropping them.

For fields, go to http://example.com/admin/reports/fields - you will get a nice list what is used where.


Trouble extracting year from date field for computed field I have a date field, 'field_date', from which I need to extract the year.  The date format is yyyy-mm-dd, so I figured the following would do it:

$date = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_date')));
$year = explode("-", $date)[0];
$entity_field[0]['value'] = $year;

This gives me Parse error: syntax error, unexpected '[' Am I not getting the date string correctly?

Function array dereferencing was added in PHP 5.4, you must be using an older version.

To fix:

$parts = explode("-", $date);
$year = $parts[0];


How to migrate data from custom user account fields to a single new field? For my Drupal 7 User Accounts I have 5 separate fields (Field Type: Boolean, Widget: 'Single on/off checkbox') used to indicate comms preferences.

Without losing any data I want to migrate these fields to single field (Field type: 'List', Widget: 'Check boxes/radio buttons') but I am not sure how to achieve this?

Step 1: Create a Rules Component

Have a look at this example of a Rules Component (in Rules export format):

{ "rules_search_and_replace_values_in_some_user_account_fields" : {
    "LABEL" : "Search and replace values in some user account fields",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "User", "type" : "user" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "user" ], "field" : "field_accept_boolean" } },
      { "data_is" : { "data" : [ "user:field-accept-boolean" ], "value" : "1" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "user:field-accept-list" ], "value" : "yes" } },
      { "drupal_message" : { "message" : "Boolean field converted to list field for user with id \u0022[user:uid]\u0022 and name \u0022[user:name]\u0022." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a boolean field with machine name field_accept_boolean (values true or false, of course) and a list field with machine name field_accept_list (values yes, no, later).
If field_accept_boolean = true, then the value of the field with machine name field_accept_list will be set to yes.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of the fields to match the machine name of your fields, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some User identifier and hit the Execute mode. Depending on the user id you selected (if it has that field, and if the Rules Condition is satisfied), your user will be updated.

After you're confident your rule works perfect for all variations of your users, move on to the next step below.

Step 2: Let VBO to the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your users to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

Attention: to process many users at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Step 3: 2nd iteration

With the previous Step 1 and Step 2, all users who have field_accept_boolean = true will have their field_accept_list will be set to yes.

If appropriate, just adapt your rule in Step 1 (or clone it to a 2nd Rules component) so that all users who have field_accept_boolean = false will have their field_accept_list will be set to no. Then repeat Step 2 (with this updated Rules component).

After doing so, ask yourself if there could be any users with a value for that field_accept_boolean which was never assigned either value. For those users, you may want to use yet another variation of Step 1 and Step 2, to have their field_accept_list will be set to later.

Of course, you could have multiple fields similar to field_accept_boolean, which you might either migrate to the same field_accept_list (maybe with another value?), or a yet another field. For all thee variations it's just a matter of tuning the Rules component in Step 1, and then performing Step 2 again.

Step 4: Straight forward variations

There are dozens (hundreds?) of straight forward variations of this question that can also be solved using the above combination of VBO and Rules. To just mention 1 of them, have a look at my answer to "How to bulk delete selected content/nodes?" ...

Happy VBO-ing while Rules-ing!


Per language menu item settings in node forms I'm working on a drupal 8 website. On every node the admin can choose wether or not to show a node in the main menu, and where it should be placed. This works great with the menu settings node form shown on every node edit page.

But at the moment I'm transforming the site to a multilingual website all is fine and via the menu settings node form it is possible to change the menu title but I can't choose to show a node in the menu for one language only.

So for example, I have a about England page that I want to show in the menu of my English site only and not in the menu of my Dutch site.

I thought it might be possible to only create an English node for this. But when I choose to add this English node to the menu it is shown in both my Dutch and English site even though there is no official Dutch version of the node. It's not official because I can't find it in the admin/content view but if you try to edit or show it it is there for some reason.

So for example when I create an English node with nid 62. When you want to see this you go to /en/node/62 but the url /node/62/ is also available and this is where the menu item on the Dutch site points to.

I also tried to have the node in both languages and unpublish one of them but then the menu item is removed from both menus.

Hope someone has a solutions for this, any suggestion is welcome.
Thanks in advance.

Okay the problem was that I used the Node view permissions module. Which works perfect but not for multilingual websites. That's why they also made Now view language permissions. By installing this and uninstalling the Node view permissions module the problem was solved.

Now it is possible to create a node and its translation and add them to the menu. By unpublishing the translation you see the default one in the menu and hide the translation from the menu in the other language.


How do I add a custom button next to the "Add Content" button? How can I add a button next to the + Add Content button on /admin/content, in Drupal 8?

You have to provide mymodule.links.action.yml in your module.

This is an example from core for the Add content action button from your question:

node.links.action.yml

node.add_page:
  route_name: node.add_page
  title: 'Add content'
  appears_on:
    - system.admin_content

Reference: Providing module-defined actions


Why are some fields output wrapped in div and others a span? I have been working with a View and I noticed an inconsistency in the way fields are output (unformatted list).

Most of the fields appear below their labels, but one (Post date) appears on the same line.

I looked at the source and I saw that the date was wrapped in a span and the other fields were wrapped in a div:

    Last Name:

Thacker

    Post date:
    Wednesday, April 9, 2014 - 14:39

Why is this happening?  Is it important for this to happen?  How can I change this so that everything is wrapped in a div?

If you click on a field in your view, you get the 'Configure Field' dialog. Look for "Style settings", because there you can customize the Field HTML, Label HTML and the wrapper. E.g. with 'Label HTML' option you can change the <span> to a <div>.


How to set a $_POST var value as default value for a textfield webform component? I need to set a $_POST variable value as the default value for a textfield webform component using Webform 4
In the Default Value field I filled with %post[my$_PostVar] but is not working.
update: it seems like Webform 4 lost the %get and %post tokens comment-6337368
any thoughts...
@googletorp
I installed the Availability Calendars module. This module shows a availability calendar and provide a formlet to allows the visitor to submit a booking.
When this form (the formlet) is submitted this is sent to a webform where the visitor will continue filling the personal data to complete the booking.
Then form let send these vars: $_POST['arrival_date'] and $_POST['departure_date']  to the Webform. Here is why I need to fetch these $_post values in the Webform components

Booking integration by providing a small "formlet" that can post to
(e.g.) a Webform.

and here some part of the Readme file of the module:

Defining the 'complete booking form' webform
-------------------------------------------- This part assumes you are using the webform module.

Define the webform components that the visitor should complete like name,   e-mail, address, number of persons, etc.

Define webform components for the dates that are already filled in:

Begin date (default value: %post[from_display]): the begin date.

End date (default value: %post[to_display]): the end date.

Webform 4 no longer uses so much of its own custom code.

It now uses drupal tokens like you would expect anywhere else.

Under the text area is a link "Browse available tokens." that will give you a javascript token browser to help you find the tokens you want.

You can access submission tokens like this: [submission:values:FIELD_KEY]

The special tokens you are after though like %post are no longer supported in webform 4.x.

For more information see https://www.drupal.org/node/1001798

Your best bet for such token support would be for them to be added to the main token module or another third party token module in the global token space.

$_GET tokens have an issue https://www.drupal.org/node/550164 however I don't think there is one for $_POST at this stage.

Alternatively you can write a hook_form_alter() in a custom module and set the default value there using $_POST.
That would be your easiest option I would say.


Describe my "special" table to views I'm developing a module, and there is a table that needs views integration. The table is not so special, but can't find a solution yet.

This is how my table looks:
nid_a|nid_b|data

I would like to join this table to the node base table, with nid_a as joining key, and nid_b should come from a contextual filter (aka argument).

How can I achieve this?

System: Drupal 7.x and Views 3.x

Create a custom module and use the hook_views_Data. Here is a link for doing that


Add inline JavaScript to end of page dynamically Use case:

I have a custom block:

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "my",
 *   admin_label = @Translation("My Block"),
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $build = array(
      '#markup' => 'SOME WEIRD ADS HTML HERE'
    );

    SOME_COOL_STUFF_TO_ADD_INLINE_JAVASCRIPT_TO_THE_CLOSING_BODY_TAG

    return $build;
  }
}

Is there a way to add inline javascript to the end of the page just when this block is rendered anywhere (in theme or panel page)?

You just use the following code.

$build = [
  '#markup' => 'SOME WEIRD ADS HTML HERE',
  '#attached' => [
    'library' => ['mymodule/mylibrary'],
  ],
];

Follow Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module to learn how to define a library for Drupal 8, and keep in mind that, by default, JavaScript files are added to the footer, as explained in LibraryDiscoveryParser::parseLibraryInfo().

  By default, JavaScript files are included in the footer.

Also, #markup is filtered out, as explained in Render API overview.

  #markup: Specifies that the array provides HTML markup directly. Unless the markup is very simple, such as an explanation in a paragraph tag, it is normally preferable to use #theme or #type instead, so that the theme can customize the markup. Note that the value is passed through \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS vectors while allowing a permissive list of HTML tags that are not XSS vectors. (For example, <script> and <style> are not allowed.) See \Drupal\Component\Utility\Xss::$adminTags for the list of tags that will be allowed. If your markup needs any of the tags that are not in this whitelist, then you can implement a theme hook and template file and/or an asset library. Alternatively, you can use the render array key #allowed_tags to alter which tags are filtered.


How to customise list (text) field? On my user registration page, I would like to add a field where users can type in and select specific key words.

It is possible to make such a field using webforms. It would look as below:

However, my user registration form is not a webform, it is a standard Drupal form, provided by the user module.

I have managed to add a field to the registration form, of type 'List (text)' and then in the 'Manage form display' section there is an option to display it as radio buttons so the user can select more than one option. This works successfully, but what I would really like to achieve is the look above.

Are the use of webforms the only way to achieve this? I guess if I have to use webforms I would have to replace the whole user registration form with a webform.

This will be a lot easier for you, if you use the taxonomy system.

Create a vocabulary for your keywords, then add the different keywords as terms.

The select2 module has a field widget for entity reference fields which allows you to get the autocomplete widget where you can remove the selected terms with an X.

Then you only need to add a little bit of styling, to get it to look like your design.

Hope it makes sense.


Create a View that Displays a group of Taxonomy Terms I have a proposed data structure like this:

Asset:

Title
Image
Description
Taxonomy term: Campaign

Campaign (taxonomy dictionary):

term
image
description

I am trying to make a view block that displays only the Campaign group, represented by the Campaign image.  The farthest I can get is defining a relationship to tax. terms on node, and displaying all Assets with that tag.  I can even Group them, which is really close to what I need.  How do I solve the problem of displaying "Campaigns" as groups of assets (not the list of assets tagged with this taxonomy).

I thought I could show a list of (non-duplicate) fields where that tax. image exists (which should be once per group/aka "Campaign"). But not so far..

How do I achieve this?   Have I overlooked something?  I am open to different approaches or ideas..

If you want to group Assets just by the Campaign (taxonomy) image, you can easily set the Grouping feature under Format to the Image field.

You have to add the Relationship for the taxonomy field first, as you have found out, then you get all the information related to the referenced taxonomy term into the Views. Without that Relationship you only have the Taxonomy term ID available, as the Taxonomy reference field only stores that info.

When you add the Relationship you can add the Taxonomy image field (Campaign image). Each Asset will then show its associated campaign image in its row.

That's when you can use Group by field and set it to the Campaign image. This will split the Asset results into Campaign groups with the image field as the "group header". You will still see the image displayed in each row, which you probably don't want, so you edit the Campaign field setting in Views and choose Exclude from display. This way the image will only display in the "group header" and won't display next to each Asset result.

If you need to display more info about the Taxonomy (Campaign) in the "group header", for example the name, image, and the description, you can add all those fields to your Views, Exclude them from display, and set them all to group by.

But sometimes the styling that comes out of this strategy isn't good enough, the HTML can be a bit unexpected. You can solve that by using Custom text field after all the Taxonomy fields where you enter your own HTML with the taxonomy field values printed out through tokens. And Group only by the Custom text field.

I've written an article about this if you need more detail: Grouping by multiple Fields in Drupal Views


Making 100's events in one go I am maintaining a calendar for a website where events can be listed in. This year is finishing, which means that soon there will be hundreds of events that need to be put in the calendar for next year. Is there a better way of doing this than manually clicking new page for every event? Ideally I would like to be able to fill a dozen events or so in one go.

If your events are nodes, write them into XML or CSV file. Then, you will be able to use Feeds module to import them in one file upload.

Next time ask the person that makes papers / pdf for you to also send you digital source data she's using.


Controlling remote Drupal sites with Drush For a couple of weeks now I have been watching various screencasts and envying those who can operate Drush on their sites, esp. when enabling/disabling of the modules, or clearing cache. The time savings seem to be immense.

However, as a more of a front-end developer, rather than a qualified, fluent console operator, I find myself completely lost as per the usage of Drush with remote sites. Most of the googled readings treat about local sites, they specify paths to local installations, or they assume that a site was created using site-install command. While I am interested in adding Drush to an existing remote site. How do I add Drush into play with that remote site?

Now that I'm trying to get the big picture of using Drush, I think I may have missed some principal knowledge about the environment and tools needed, which I haven't found anywhere.

Apart from having command line Drush installed on my desktop, do I have to install Drush module on my remote site? Or is Drupal core Drush-controllable out-of-the-box (if it is, what is the purpose of Drush module available at drupal.org/project/drush)
Do I have to configure SSH for communicating the server?
Do I need to provide db credentials anywhere (where)?
Do I need to define FTP credentials anywhere (where)?
aliases.drushrc.php: does it live only on my desktop, or should I define anything similar on the remote ftp?

My setup involves staging and production sites, the former also stored on a remote ftp server with its own domain. I would like both to be controllable via Drush. Is that feasible?

It'd be great if someone could shed some light on me.

You have a lot of questions there, but I'll try to give you the best overview of how to do this easily.

First, note that though Drush is listed as a module on Drupal.org, it is not technically a module as you don't "enable" or "disable" it like other modules.

Yes, Drush must be installed on the remote site.  When you do so, make sure to install the same version that you have installed locally.  It may still work if you're using different versions, but it can also cause strange bugs that are difficult to troubleshoot so always try to keep the same version.
It's certainly easier if you have SSH set up for some of the Drush commands.  Your web host should be able to help you with getting SSH keys set up for your local machine.
Yes, you will need to provide DB credentials.  This can be done by following the example in drush/examples/example.aliases.drushrc.php in the drush folder.
No, I don't think so.
You do not need to set up the alias on your desktop unless you are going to be logging in to your remote server and using aliases there.

Basically, if you have SSH working and have installed Drush on the remote server as well as your local machine, then, once you set up an alias, you can type something like drush @myremote status and it should work.


How to remove 'Submitted By'? Although there are many answers for earlier versions of Drupal 8, I could not find a way to remove 'Submitted by' information displayed with Articles.

How can one achieve this with Drupal 8?

This is in the settings of the content type:

  /admin/structure/types/manage/article

Here you'll find in the tab Display settings the checkbox:

  [x] Display author and date information


What is the best practice for theming? I'm about to start theming a Drupal 7 website for the first time. I've watched  Moshe's video, Lia Clark's introduction to theme overrides using context naming, and Franz's talk at Drupalcon Chicago. These are all great, but like everything else in Drupal there must be a thousand different ways to theme now.

What is are the best techniques and practices to theme now in Drupal 7? More specifically, how do I best use hook_page_alter($page)? I'm imagining that after I move all the parts of the page around it will be huge and unwieldy. Are there ways to add a region to a node template?

Edit:

Here is an example of moving a page region that is populated with the Context module while the block module is disabled completely. It was the first way of doing this that came to my mind. Why someone would want to put a region between the links and comments, I don't know. Still it's cool to be able to put stuff there.

In template.php:

function hook_page_alter(&$page){

  $main_content_display = &drupal_static('system_main_content_added', FALSE);

  // Need to beat common.inc drupal_render_page() line 5485 to this
  if (!$main_content_display) {
    $page['content']['system_main'] = drupal_set_page_content();
  }

  if ($node = menu_get_object()) {
    $region_to_embed = $page['sidebar_first'];
      $page['content']['system_main']['nodes'][$node->nid]['#node']->region = $region_to_embed;
    unset($page['sidebar_first']);
  }
}

And in node.tpl.php:

  <?php print render($content['links']); ?>
  <?php if ($node->region): ?>
    <?php print render($node->region); ?>
  <?php endif; ?>
  <?php print render($content['comments']); ?>

Kind of a "big"/multiple question(s), that is hard to answer. Try to ask more specific, single questions in the future.

About hook_page_alter(). In a theme, you should customize the output by overriding default templates. IMHO, that hook is more meant if modules want to alter the output of other modules, especially if they return render arrays instead of arbitrary strings.

Speaking of render arrays, that is one of the main things I do with my modules now, instead of arbitrary templates. I've already replaced quite a few specific "page callback templates" by building and returning a so called render array. The advantage is that, if you for example want to change the order of the table rows, or add/hide a table row, you can do that without duplicating a template with maybe 100 lines of code. And, multiple modules can add/change things.

Two examples:

userpoints_admin_transactions()
user_relationships_page()

Edit:

And for your last question: Regions in "Theme-speak" are places where blocks can be placed. Regions are defined in the .info file of a theme. The node template itself is more or less a block (The "Content" block, which is the output of the executed page callback). Since it is not possible to nest regions within regions/blocks you can also not place regions in a node template.

That said, you can make your node template as complex as you want, and split the content up into "visual regions" for example.


Permissions to create a database with drush command? If I use this line to install a drupal site it only runs fine if the 'mydb' database already exist.

If the database doesn't exist I get an error. Is there other drush command to make an installation when the database doesn't exist?

drush si --db-url=mysql://root:root@localhost:8889/mydb

I don't think is a user permission since the root user has all privileges enabled. Look the picture. I use MAMP (the free version)

I this other capture you can see the connection parameters:

I don't think Drush has an option for this built into the site-install method but you might find something under the sql-sync method, which I think has an option to create a database.

I don't know if it's appropriate for your situation but you might want to look at the Drupal Quickstart: Pre-made Development environment; it has a bunch of custom Drush commands included, one of which will set up an entire site (vhost file, database, file permissions, etc.) in one line:

drush quickstart-create all --domain=example1.dev

I've copied this command out and hacked it to pieces, and now I can install a fully configured Drupal site on my local Mac machine with a single terminal line:

drush isosc --domain=example.dev

I would thoroughly recommend doing this; I couldn't live without it now


Restrict operations to Specific user I constructed my admin/content page using my custom module

Steps i follow
 1. retrieve data from multiple tables and displayed it in table
 2. I gave edit and Delete options

From admin/user edit and delete options working good

Now my question is i logged in as authenticated user how to disable edit and delete options for admin created pages.Only user will see edit/delete option for his own created pages.Thank you

You'll need to implement hook_permissions(). And you probably also need to read up on user_access(). The strategy is to create a permission set, grant it for the admin role, and then check for user_access before you render the buttons. This way the buttons will only show for users who have been granted the permissions.


how to theme content type based on context I have an article content type with categories (term1,term2 etc)
I want to be able to theme the node view with a different theme when specific category is picked on node edit

how can this be done ? any kind of solution is acceptable

NOTE: at this point https://www.drupal.org/project/page_theme, https://www.drupal.org/project/themekey have not been ported to D8 :-( They would really be great solutions

Here is a complete solution

Installing context module we can create a context which comprise of conditions which if they are met they do the specified reactions
Installing entity_field_condition will let as set the desired condition
Add context (lets name alternative theme section)
Add Node Field (entity_field_condition) and select category name and choose the specific value that corresponds to the desired category (tid since we are talking about term reference).
Add reaction theme and choose the theme that you want to be activated on above conditions

NOTES:
At the time of writing this entity_field_condition needs a patch to work properly with entity reference (as is the case of category field).  The patch can be found here

term condition was not working at the moment (buggy was not able to add the condition it was giving WSOD)

Alternatives would be to write my own custom condition or debug the term condition module or write my own theme negotiator


Refer to Term ID from $content field I'm attempting to get the taxonomy term id from a field in the node template for a content type. I'm currently rendering the names of the terms using this

render($content['field_tags'][value]);

This works fine for grabbing the names of the terms. However I would like to be able to grab the actual term ids from those fields instead of just the names. Using devel I do see that that information exists, however I'm not sure how to refer to it.

Updating the Answer:You can use template_preprocess_node. in your theme template.php

function YourTheme_preprocess_node(&$variables) {
  $variables['tags_tids'] = array();
  foreach ($$variables['field_tags'] as $key => $tag) {
    $variables['tags_tids'] = $tag['tid'];
  }
}

then in your node.tpl you could loop through the "$tags_tids"array, and do whatever you want.


How does node import happen when importing from features module? I used the Node export module to export few pages into features; when I import it is randomly imported.

Is there any particular pattern that it is followed while importing? I want to make a particular page as node 1.

That kind of thing is not really possible. The problem is that the node id is serial, so on one machine it will have on id but on another machine it will have another id. Also the the node id is the primary identification, so changing it is not always that easy (if you have comments etc.)

For this kind of thing, UUIDs is really needed (Universally Unique ID). There are modules for this in Drupal 7 and it's being worked on in Drupal 8, but neither will effect the node id, instead it will maintain a UUID which will be the same on all machines that has the node imported.


View with relationship to custom entity via computed property View with relationship to custom entity via computed property

I have nodes connected to a custom entity (called here "myentity") via a computed property, like this:

  $info['node']['properties']['myentity'] = array(
    'label' => t("Myentity"),
    'type' => 'myentity',
    'computed' => TRUE,
    'queryable' => TRUE,  // setting this to FALSE doesn't change anything
    'entity views field' => TRUE,
    'getter callback' => 'mymodule_node_property_myentity_get',
  );

The callback function extracts some values from the node and calls another function, which fills these values into an entity field query, returning the wanted myentity instance.

This entity connection is working, so I can get the property "myprop" of myentity via an entity API wrapper $node_wrapper->myentity->myprop->value().

Now I want to add myprop in a simple view for nodes. After creating a relationship to myentity, "Content: Myentity" shows up in the "Add fields" list, as well as all of myentity's properties.

Selecting "Content: Myentity" works - myentity's default label is displayed in the view output. (With some magic - the displayed SQL query is SELECT node.nid AS nid FROM {node} node).

However, selecting "Myentity: Myprop" does not work. Even before executing the view, Drupal shows a SQL error:

SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "myentity" LINE 1: SELECT node.nid AS nid, myentity.myprop AS myentity_myprop, no... ^

The displayed SQL query here is SELECT node.nid AS nid, myentity.myprop AS myentity_myprop FROM {node} node. myentity is referenced in the select clause, but not in the from clause, nor is there any join statement.

Has somebody managed to add properties of a custom entity, connected via a computed node property, to views?

Finally figured out a workaround: Pull every needed entity property as a "virtual field" into the node itself.

// define additional property information for node
function mymodule_entity_property_info_alter(&$info) {
  $properties = & $info['node']['properties'];
  foreach (array('myprop') as $property) {
    $properties[$property] = array(
      'label' => $info['mymodule']['properties'][$property]['label'],
      'description' => $info['mymodule']['properties'][$property]['description'],
      'type' => $info['mymodule']['properties'][$property]['type'],
      'computed' => TRUE,
      'queryable' => TRUE,
      'entity views field' => TRUE,
      'getter callback' => "mymodule_node_property_verbatim_get",
    );
  }
}

// getter callback
function mymodule_node_property_verbatim_get($data, array $options, $name, $type, $info) {
  $myentity = mymodule_get_from_node($data);
  return !empty($publication->{$name}) ? $publication->{$name} : array();
}

// obtain the related entity from the node
function mymodule_get_from_node($node) {

  // some custom code to get myentity

  return $myentity;
}

Thus, the properties can be adressed as views fields as well as for any other purposes. It's possible to extend this to access properties of nested entities, too.

One drawback, however: The fields cannot be used as views sort criteria.


How to adjust position of drop-down block in Nice-Menu? I have inherited a site built in Drupal 6 that uses Nice-Menus for both the top and side nav bars.  I've been tasked with modifying the current navigation and have run into issues adjusting both the position and width of various menu items.

You can see the issue by going to http://neoninc.org and hovering over "ABOUT" in the top nav bar, then "About NEON & Mission >>."  You should see that the menu item for "Governance" doesn't align properly with its parent item.

The previous developer added the following items to the CSS page called by nice-menu to adjust their widths:

ul.nice-menu li.menu-563 li { width: 20em; !important}   /*  ABOUT */
ul.nice-menu li.menu-840 li { width: 20em; !important}   /* CONTACT US */
ul.nice-menu li.menu-236 li { width: 24em; !important }  /* SCIENCE */
ul.nice-menu li.menu-4191 li { width: 20em; !important } /* CITIZEN SCIENCE */

I tried adding the following:

ul.nice-menu li.menu-781 li { margin-left: 16px; !important} /*  ABOUT >> Governance */

and then:

ul.nice-menu li.menu-781 li { left: 16px; !important} /*  ABOUT >> Governance */

both of which seem to work when editing the CSS directly in FireBug.  They don't work when inserted into the actual CSS file, and I'm stumped.

Yes, I've rebooted, cleared the local cache, cleared all caches in drupal, and double-checked that I actually uploaded the edited CSS file.

Any suggestions are greatly appreciated!

You need to be overriding this...

ul.nice-menu-down li ul li ul, #header-region ul.nice-menu-down li ul li ul


How do I install the latest release of Drupal with Composer Instructions on Drupal.org for installing Drupal with composer provides the following example:

composer create-project drupal/drupal my_site_name 8.3.*@dev --no-dev

This provides me with the latest DEV version of Drupal. How do I get the lasted stable release?

composer create-project drupal-composer/drupal-project:8.x-dev \
  YOURDIRNAME \
  --stability dev \
  --no-interaction


What is the best way to handle post data in drupal? What function I need to implement to handle simple post data when I submit a form?

You are doing it Wrong(TM). Both the question(!) and especially the answer. Yes, you need to implement hook_menu but your page_callback is drupal_get_form because you never, ever work with $_POST directly for security reasons.


How to remove h1 tag from Drupal Garland theme in the header I was shocked to see Bing Webmaster Tools notification that my site: http://www.articlesdirectoryindia.com using Garland theme has two H1 tags and that only one should be there for SEO reasons.

Actually the site name : "Free Articles Directory India" is wrapped within h1 on all pages in the header which I want remove.

I want to know if there is any standard & tested workaround for removing this h1 and replacing this with some div etc?

I tried to change h1 to div for 10 minutes but I could not do it. Even if I'm able to it'd be difficult to test of all browser versions.

if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }

These are the lines 39-45 in Garland Themes page.tpl.php.
This is probably the h1 tag you're talking about. If you want to change it to div it should look like this afterwards:

if ($logo || $site_title) {
        print '
';
        if ($logo) {
          print '';
        }
        print $site_html .'
';
      }


Hide sid in webform confirmation page I am using webform for contact us page.

Once form is successfully submitted,I have redirected it to thank you page.

But the URL of thank you page keep adding webform sid, like given below

http://localhost/test/thank-you?sid=1234

I want to hide the sid from URL

I am using custom redirect URL in form settings

Thanks

No you can not ignore the "sid" from submission confirmation page.

Yes you can create a separate thank you page and redirect to that page.

You can install this modules:

->     rules

->     webform rules

Now add a rule that redirects the user to your URL after a webform submission.

Using hook_form_alter(), and set the override there.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
     $form['#submit'][] = 'my_submit_handler';
  }
}

function my_submit_handler(&$form, &$form_state) {
  $form_state['redirect'] = 'home';
}

Refer Redirect Drupal Webform Submissions


How to set up Drupal behind a proxy correctly? I have a Drupal 7 website on the domain hiddendomain.be:3200. Users visiting publicdomain.be are proxied to the hidden domain. My home page is rendered just fine, but when I log in with the existing account TestUser, I get a "You don't have access rights to this page" message. It seems that Drupal still handles the user as anonymous, because going to publicdomain.be/user immediately afterwards returns the login form again. However, in the log report, a new session has been created for TestUser. Why does this happen?

I have been browsing the web for answers, but the only thing I found was to edit the settings.php file in the default directory (in my case that is settings.local.php) by adding

$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('IP');

where IP is the IP address of the publicdomain.be server. Unfortunately, this does not work. What am I doing wrong?

The problem has to do with how cookies are associated with domains. After you log into a Drupal site, Drupal sends a cookie to the browser that it uses in future requests to show it has been authenticated. Drupal associates that cookie with the domain that the login occurred on. Since your proxy sends requests to your Drupal site using the hiddendomain.be domain, that is the domain that Drupal associates the cookie with. However, the visitor's browser sends requests to publicdomain.be, and so considers the cookie it received from your Drupal site to belong to that domain. It is this discrepancy that is causing the problem.

To fix this, you need to configure Drupal to associate its cookies with the publicdomain.be domain. In your settings.php add, or update, the following line: $cookie_domain='publicdomain.be';

If your public and private domains share a root, then you can use the domain root as the cookie_domain. For example, if the public domain was www.example.com, and the private domain was private.example.com, then in settings.php you would have $cookie_domain='.example.com'; (note that there is a dot before the domain).


Using Fields as Attributes in Node Templates What is the best practice for using a field as an "attribute" in a node template with Drupal 7?  I am using the term "attribute" loosely here to mean something that can't be concretely rendered as an HTML fragment; rather, it gets rendered inside an HTML fragment somewhere in a template.

The field API makes it very easy to wrap a "content" field with HTML so it can be rendered in a template, many times with out needing to edit the node template at all, due to the way render trees work.

Consider a content type such as

Title (title)
Body (body)
Extra (field_extra)

Where field_extra is just something that I want to tack onto the node title, eg

<?php if (!$page && $title): ?>

<?php print $title ?> &mdash; <?php print $extra; ?>

<?php endif; ?>
print render($content);

This is a very, very simplified example to illustrate what I am talking about.

I could just access

$extra = trim($field_extra[0]["safe_value"]);

but I would have to go through some show()/hide() logic depending on how things where configured, and directly accessing fields is discouraged.

I could make a theme_field(), such as

function mytheme_field__field_extra ($variables)
{
  $items = $variables["items"];
  return count($items) == 0 ? "" : trim(drupal_render($items[0]));
}

and then use render(), but I would still have to go through the show()/hide() shenanigans and I am not really rendering the field, just trying to get a plain version of it to use somewhere.

Or, should this really be handled by a template_preprocess_node(), eg

function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];
  $language = $node->language;

  if (isset($variables["field_extra"])
      && isset($variables["field_extra"][$language])
      && isset($variables["field_extra"][$language][0])) {
        $variables["extra"] = trim($variables["field_extra"][$language][0]["safe_value"]);
  }
}

I know all of these will work.  I am really interested in what is the best practice here.  I suspect that the template_preprocess_node() is the best way to handle this, but I have not seen anything definitive about this case.

Thanks.

Is there a reason to not just set the format to "<hidden>" in the content type's "manage display"? Then it will never render but you still have it if you want it.

If you really want to do this programatically, the best practice, for me, is to use a module not your theme. Why? Because if your theme changes... do you want extra to show? Nope, so make it independent of the theme by putting it in a module.


Computed field won't update itself or save to the database UPDATED ISSUE: In the original issue below, I was getting an error when a query was empty. I've now gotten rid of the error, but content no longer saves into the database (where it saved fine before). Also, if the "store value to database" option is unchecked, then the data does not display at all. The new portion is the the second piece of the below code.

$entity_field[0]['value'] = "";$nids = db_query('
    SELECT entity_id FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
    )->fetchCol();

if (!empty($nids)) {
    $entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_venue_default_value')));
   }

else {
    $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
    )->fetchField();
   }

endif;

If the array_pop portion is all that is in the computed field, then the field saves to the database (or displays, if the option is unchecked) just fine. If it's not included at all, the field saves/displays fine. However, when it is placed within if (!empty($nids)), no values for the field will save/display at all. This includes both the value of the array_pop and independent values calculated by SELECT AVG. As always, any help is greatly appreciated (and thanks to both Clive and Tenken for getting me get rid of the initial error).

ORIGINAL ISSUE: I have two content types: Review and Venue. Each review has an entity reference field to relate it back to the correct venue node. On the Venue nodes, I have computed fields to display calculated averages of fields from reviews referencing the current node (i.e. Average Payment Rating for Joe's Nasty Catering). For one of these fields, the code is:

$entity_field[0]['value'] = "";$nids = db_query('
  SELECT entity_id FROM {field_revision_field_review_venue_reference}
  WHERE field_review_venue_reference_target_id = :nid',
  array(':nid' => $entity->nid)
)->fetchCol();

$entity_field[0]['value'] = db_query('
   SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment}
   WHERE entity_id IN (:nids)',
   array(':nids' => $nids)
)->fetchField();

The computed field works 100% correctly when a review has already been submitted for the current venue. However, when no reviews have been submitted, I get an error of PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064. It seems that this is because there are no entries where the Node Reference field is equal to the current NID.

Is there some way to fix this? I hadn't gone through the steps necessary to create the error until today, and as such I just realized that the site I'm building is essentially broken because of it.

If you would print the rest of the MySQL error message I assume your error is a malformed query such as:

SELECT AVG(field_review_payment_value) FROM {field_data_field_review_payment} WHERE entity_id IN ()

Eg, you cant have an empty IN primary key list.

Since you want to show an average value you could do something simple like:

if (isset($nids)) {
  $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value) FROM
    {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
  )->fetchField();
} else {
  $entity_field[0]['value'] = 0; // no values to average == 0.
}


Modal delete confirmation How do I get a confirmation message to show as a modal dialog?

$form['mytable'][$id]['operations']['delete'] = array(
  '#type' => 'submit',
  '#value' => t('Delete'),
  '#name' => 'd' . $entity->ref,
  '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}'),
);

I've looked at the Colourbox module and OpenModalDialogCommand but I don't know how to integrate this into #attributes.

See https://www.drupal.org/node/2253257, wich would do this by default.

It's pretty easy to do it for your own link, note that the patch there is out of date. Instead of the accepts thing, you simply put data-dialog-type and data-dialog-options on your link attributes. See also https://www.drupal.org/node/2488192 that describes this change and contains lots of examples.


Commerce get product id's from order My question is simple: How do I get the product id's from a commerce order with Drupal code?
I have something like this at the moment:

  $orders = commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE);
  foreach($orders as $order) {
    foreach ($order->commerce_line_items['und'] as $line) {
        $line_id = $line['line_item_id'];
        // ... product id, where are you?
    }

Hopefully somebody is able to answer this question :)

Using the entity metadata wrapper, you could also do:

foreach (commerce_order_load_multiple(array(), array('status' => 'pending'), TRUE) as $order) {
  $product_ids = array();
  foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
    if (in_array($line_item_wrapper->type->value(), commerce_product_line_item_types())) {
      $product_ids[] = $line_item_wrapper->commerce_product->raw();
    }
  }
}

The important part here is checking the type of the line item, so you don't end up including shipping line items or other types of line items in your list of product IDs. Additionally, with the wrapper notice that I used the "raw" value of the commerce_product field on the line item. This is because the "value" would be the fully loaded referenced product, while the "raw" value is simply the product ID.


How to output content type title on page.tpl.php? So I am using this code to output nodes title:

<?php print render($title_prefix); ?>
<?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
<?php print render($title_suffix); ?>

What code do I need to output the content type's name (i.e. content type is Article, so output 'Article' inside each Article content type node page next to node title, above or below it)?

In D7 there is node_type_get_name

node_type_get_name($node)

Parameters

  $node: A node object or string that indicates the node type to return

Return value

  The node type name or FALSE if the node type is not found.


How to add an image upload field to a node programmatically? I want to add an image upload field to a node programmatically when the node is being loaded.

I heard that you could use hook_form_alter() but I am looking for better options. Could anyone provide a solution?

Add a CCK imagefield to the node.

If you need to show / hide it, use your form_alter to set ['#access'] = FALSE on the field.


How do I get an article's author email programmatically? I would like to send an email to authors when their content updated. How can I get the email of author(s)?

I think $to = \Drupal::currentUser()->get('mail'); is not my friend.

Since you are talking of authors, I take you are referring to users who posted a node. In that case, supposing you have a $node variable, you should use the following code.

use \Drupal\node\Entity\Node;
use \Drupal\user\UserInterface;

/** @var \Drupal\user\UserInterface $user */
$user = $node->getOwner();
$email = $user->getEmail();

If, instead, you are trying to get the email of the currently logged-in user, then you cannot use \Drupal::currentUser()->get('mail') because \Drupal::currentUser() returns an object implementing \Drupal\Core\Session\AccountProxyInterface, which doesn't have any get() method.

If you want the email associated with the account, you need to use the following code.

use \Drupal\Core\Session\AccountProxyInterface;

/** @var \Drupal\Core\Session\AccountProxyInterface $user */
$user = \Drupal::currentUser();
$email = $user->getEmail();

If then you would need a User object, you should use the following code.

use \Drupal\Core\Session\AccountProxyInterface;
use \Drupal\user\Entity\User;

/** @var \Drupal\user\Entity\User $user */
$user = User::load(\Drupal::currentUser()->id());


How to use tokens in Integer field? I'd like to add a 'Year of birth' field to the build-in registration form. Therefore, I created the Integer field 'Year of birth' at Administration > Configuration > People > Account settings.

I set the minimum value to 1900 and the maximum value to 2013. But, instead of '2013', I'd like to use the token [site-date-yyyy], so that I don't have to change the maximum value every year. Unfortunately, only integers are accepted. How can I use a token?

Try the Date module

Install the module
Go to Configuration > Account Settings > Manage Fields tab
Add a date field of type "Date" and widget "Select list"
Hit Save
Deselect every date piece except year
Hit Save field settings.
Check Display on user registration form.
Expand More settings and values
Set starting year and ending year and default value.
Save settings

If you must use a text field, the date field gives you that option as well. You wont be able to set a start or end date, but the module will validate the date is in the proper format.


H1 tag not showing on front page Im using Drupal 7.41 and Omega3 sub theme and Ckeditor. I have added a sentence in the style of heading (h1)  at the top of my Home Page content, it shows in Ckeditor using the source button (showing markups) with H1 tags around the heading, and shows in the style of H1 normally in Ckeditor. When I save and close off the edit, it just appears as normal text, and as P tags when I view via Firefox (View Source) , the H1 markup is not showing, when I go back into Ckeditor, I can see its in the style of H1 and when I click Source button,  i can see it has the H1 tags around it. When I View Source on Firefox, it shows as P tags. I have flushed Cache, and checked but it still shows as P tags.

Basically, its showing correctly in Ckeditor (with/without clicking Source button), the markup is not getting wiped, but its just not showing when I view the webs page when I come out of Ckeditor (either logged in or not). Can anyone help?

go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or custom) You need to go to
/admin/config/content/formats/filtered_html
add the <h1> to the limit allowed html list


How to create OG image view? I facing issue with OG 7.2x and image.

I create a group content type and add new field with image. After that i upload some picture, and view with colorbox working fine.

After that, i create normal view all things is workings well. if i add contextual(OG member:group id) and relationship(member from og node), the picture disappeared and nothing display under OG view.

Would you please tell me that how to do this?

Many thanks.

Hi what you can do is that create a content pane from a view display and configure it in the following screen shot listed below.

Next in the fields section you can add the image field and other fields as per you like.

 ![Add fields accordingly][2]

Also you can clone the view that comes default with OG.

OG:CONTENT(clone this view and add fields)

Hope this helps. :)

Edit:- For displaying images

I havent done anything like this before. But I think you can do this by "rewriting" the result of the url field.

You can do this by clicking the field with the url that you will find under "FIELDS" in your view settings. Then under "Rewrite Results" you can write something like

<img src="[image_url]" />

here, 'image_url' must be the name of the field. you can verify this in the list displayed under "Replacement Patterns"

Hope this helps. :)


Fill the "Unpublish on" date field of the Scheduler module depending on list field I have a content type, where I want to give the user only three possibilities to unpublish content: in 1, 3 or 6 months. For the selection of the three options I use a list field. How can I transfer the selected value to the unpublish field?

You'd do better to have a custom module that does a form alter on the unpublish date field itself - converting it from a date/text to a date/select.


Getting WSOD after attempting to upload an images from desktop I am unable to upload an image from my desktop in Drupal 7. I am trying to upload an image to a blog without using Ckeditor.  I have created a field for the image and assigned it as image.  All looks good. The problem happens when I go to create a new blog, I see the field for the image. I click on the "Choose file".  It brings me to my desktop.  I select the image and then click onto "Upload". The small blue wheel begins to spin. Then I get the WSOD. I see, in Firefox, at the bottom of the page "Transfering data from XXX.com..."

If you are trying to upload some bigger images, it is possible that you are out of memory.

Processing large photos requires lots of power and memory. Set the RAM with php_value memory_limit 128M or 256M if your hosting allows.


Change Node Owner On Node Submit How can I change the owner of an anonymously submitted node upon the initial node creation?

Goal:

Anonymous user completes form.
Node owner is changed to a specific user id.
Node is inserted into DB.

Can this be done with hook_form_FORM_ID_alter();

hook_form_FORM_ID_alter is used to alter the form before it is rendered, if you want to alter the form after being submitted and before being save, you have to use hook_node_presave.
Put this code in a custom.module:

function custom_node_presave($node) {
  if ($node->uid == 0) {
    // Change anonymous node author to uid: 2
    $node->uid = 2;
  }
}


Custom 404 page not working I'm trying to set a custom 404 page but is not working.
What I tried:

configuration - system - basic site settings and set node path on 404 page -> didn't work
add page--404.html.twig to my custom theme -> didn't work
in my custom-theme.theme added _theme_suggestions_page_alter function -> didn't work

Always show default 404 page, not my custom page.
I clear cache on every attempt.
Is there something I am missing?
Thanks in advance

Edited
Tried on local and cloud acquia server
I check with another websites that I build and all of them give me this 404 page (default)

But with this specific website I get this 404 page

It seems this website 404 error is handle by browser and not by drupal 8(?)

Edited 2
Another thing I notice is when I type a wrong URL appear on "log messages"

But on current website (the one I can't set custom 404) I don't have any error on "log messages".
Is there any code/config to enable/disable this?
Maybe this is same problem?

Are your sure you did all the steps? Step 1: in mytheme.theme
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    case 'system.401':
      // Unauthorized Access.
      $error = 401;
      break;

    case 'system.403':
      // Access Denied.
      $error = 403;
      break;

    case 'system.404':
      // Page Not Found.
      $error = 404;
      break;
  }
  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }
}

Step 2: create the page--404.html.twig file
Step 3: clear cache
For some markup, check https://stefvanlooveren.me/blog/styling-404-error-pages-drupal-8


How to add a class to the image tag The input in file field.html.twig is normally like this:

{% for item in items %}

{{ item.content }}

{% endfor %}

And you get the output in HTML like this:

But I want to add a class to img-tag. How do I receive the following output:

I am looking for a solution like this (solution in another post), but it is not working. Can anybody help?

I'd prefer to avoid editing templates for such simple things as adding just classes. I'd recommend to edit templates only if you really need to make changes to the markup.

For adding a simple class to your image all you need is the following snippet placed in your custom (sub-)theme's *.theme file. (Replace MYTHEME with the actual machine name of your theme). This one identifies the image by its image style (so ensure to have an unique image style applied to your image):

/**
 * Implements template_preprocess_image().
 */
function MYTHEME_preprocess_image(&$variables) {

  // Check the image style.
  if ($variables['style_name'] == 'img_fluid') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}

If you are fine with adding the class not to the img tag directly, but to its wrapping container you could also use the following snippet. You can broaden the if-request as you like to only fire on certain content types (as you maybe use the same field in other content types as well), p.e. check for $variables['element']['#object']->bundle(). Replace field_MYIMAGE with your actual field name.

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {

  // Check for your image field.
  if ($variables['element']['#field_name'] == 'field_MYIMAGE') {

    // Set class.
    $variables['attributes']['class'][] = 'img-fluid';
  }
}


How to keep my Bootstrap sub-theme without using the CDN? I created a sub-theme bootstrap version of CDN.

I based on "Journal" version "3.3.6" and I personalized my style.css file with 900 lines.

https://bootswatch.com/

I no longer wish to use the CDN, but I like to keep my current theme "Journal" and my custom style sheet.

How can I do this without using "less"?

What I want is to work with CSS

I asked this question several weeks ago but I still have not found a solution :

Install without Bootstrap CDN

Zuzuesque thank you your solution works, but I am having display problem :

I no longer have the "glyphicons"
The menu bar is not displayed correctly
The admin menu is hidden by the menu bar

You will need to switch the module you are using - Bootstrap Library is not suited to be used without CDN. The main function this module provides is connection to a CDN of your choice - not provide a theme (or css) itself.

The module you will want to use is the Bootstrap Theme. This one provides a sub-theme you can expand upon.

To get the Bootstrap Theme going:

Disable your old Journal theme + move it from the theme folder - that's important. (Maybe make a backup somewhere).
Download the Bootstrap Theme from the Drupal site and put it in your theme folder. (And leave it there)
Create a subtheme following the instructions for the less-starterkit (you wont need to touch less no worries) here: Sub-Theming Bootstrap. Basically you copy the bootstrap_subtheme folder from the bootstrap theme into your theme folder and rename the folder to journal (your theme name). You also rename  ./journal/less.starterkit to ./journal/journal.info.
Open your new .info file and change name + description. (You can copy it from your old theme.)
Download the latest 3.x.x version of the of Bootstrap Framework Source Files into your new sub-theme. After it has been extracted, the folder should read ./journal/bootstrap. (Don't modify the files in this folder, this folder allows you to later update Bootstrap without overwriting your changes.)
Download the journal theme css from bootswatch. Copy it into your journal/css folder. (This is the file which was previously provided by the CDN.) It should now read journal/css/bootstrap.min.css
Open your .info file again, find the line stylesheets[all][] = css/style.cssand add a line right above it: stylesheets[all][] = css/bootstrap.min.css. This will load the default journal css.
Now you need to copy your custom changes into the new theme. Copy your custom css into css/style.css and your template files (if you have any custom template files) into the journal/templatesfolder.
Enable your new Journal theme.

Glyphicons

Check your subtheme... there should be a folder fonts. If there is no such folder create one. Then navigate to the bootstrap source files you put in the bootstrap folder of your theme, find the font folder there and copy all font files in your own font folder. (This is needed because the default css looks for the fonts under ../fonts/font-name)

Headermenu

Have you checked the settings of your new theme in the UI? It has a couple of menu bar settings, maybe you are just using the wrong one. Generally bootstrap works nicely with the admin menu, at least on all sites I have it on. It is possible, that some of your custom css is interfering with the default bootstrap theme setup. In that case you would need to do some debugging on your custom css. From what I see though it might be enough for the front end to give the main-container a top margin of 60-70px.


How can i find out when the next cron will run? How can i find out programmatically when the next cron will run in order to present it to the author scheduling stuff?

i am using ultimate cron and an external cron process.

Basically, you cannot.

If you are using Drupal 7 built-in CRON triggering method, in Drupal 6 Poormanscron module, CRON run depends on the availability of visitor. If no one visits your page, CRON will not run. Drupal can't predict if or when visitor will appear, so the best you can know is when CRON will not yet run anyway, even if visitor is available.

If you are using external tools, Drupal has no way to predict if and how they will trigger it. It will accept all proper request, so you know even less than in the first case. Even if you know when it is supposed to run, you don't know time difference between servers, as it is subject to change slightly. You don't know the lag between a moment when CRON should happen and when it will, as practically no web servers are hosted on real time operating systems, so there are no guarantees about maximum time between action request and it's execution. In simpler words, server can postpone CRON task if it's to loaded, sometimes even skip it.

If you need predictable and reliable cron, go to http://example.com/admin/config/system/cron, find URL described as "To run cron from outside the site, go to". Then, mail your server administrator and ask him to add this to server's crontab:

*/5 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=yourcronkeyrandomstring

This will make your site's CRON run every 5 minutes, and you shouldn't need to know when exactly - it's ofthen enough for most tasks. If it's not, make it */2 to run it every 2 minutes, or just leave * at every position to get it triggered each and every minute. You can read more about system's CRON configuration on Wikipedia. Of course it will not allow Drupal to know, it will just free you from the need to know.


Custom Twig template for confirmation webform page being cached too hard I've created a custom module which does some additional form handling and styling required for my project - this is all working fine.

Due to the size of the form - 50 odd fields - I'm setting up a Twig file in my module for the confirmation screen as it is far easier to manage it in my IDE than using the GUI. My confirmation page lists all the values styled in a specific way and laid out in a specific way. I've technically got it working by using hook_theme_suggestions_webform_confirmation_alter and hook_theme to point to my Twig template.

However, I've just recently discovered that, due to Drupal 8 internal page caching being so aggressive for anonymous users, the confirmation page is getting cached for everyone regardless of the actual submission values. So the first user gets it fine but the second submission from then on gets the cached version from the first.

I've read in other places to make use of hook_preprocess_webform_confirmation and set $variables['message']['#cache']['max-age'] = 0;. However, this is never called which I suspect is due to how I went about using my Twig template mentioned above.

Can someone help point me in the right direction here. Am I supposed to setup some kind of overwriting route in order to change the theme file or is it just a matter of tweaking what I've already done?

Functions in my .module file

function application_theme($existing, $type, $theme, $path) {
  $info = [
    'gib_application' => [
      'render element' => 'form',
      'template' => 'application-form'
    ],
    'application_form_confirmation' => [
      'template' => 'application-form-confirmation'
    ]
  ];
  return $info;
}

And

function application_theme_suggestions_webform_confirmation_alter(array &$suggestions, array $variables) {
  if (empty($variables['header'])) {
    $suggestions[] = 'application_form_confirmation';
  }
}

UPDATE

I've tweaked my hook_theme function to the below and also disabled hook_theme_suggestions_webform_confirmation_alter assuming it isn't relevant so long as hook_theme is defining the correct name.

function application_theme($existing, $type, $theme, $path) {
  $info = [
    'gib_application' => [
      'render element' => 'form',
      'template' => 'application-form'
    ],
    'webform_confirmation__application_form' => [
      'template' => 'application-form-confirmation',
      'base hook' => 'webform_confirmation'
    ],
  ];
  return $info;
}

Here are the Twig suggestions:

<!-- FILE NAME SUGGESTIONS:
   * webform-confirmation--application-form.html.twig
   x webform-confirmation.html.twig
-->

Unfortunately now my Twig template isn't being loaded at all now (due to dropping hook_theme_suggestions_webform_confirmation_alter.

Seems like there are two different issues here:

(a) Loading a twig template from an arbitrary folder.

Could you try setting the path theme property and see if that allows your twig template to be loaded? For example:

'webform_confirmation__application_form' => [
  'template' => 'application-form-confirmation',
  'base hook' => 'webform_confirmation'
  'path' => \Drupal::moduleHandler()->getModule('application')->getPath() . '/templates',
],

(b) Modifying the cache settings for a part of your render variables.

You should check that the cache tags bubble all the way up from the message array. Apparently:

  You have to render the content variable to ensure that its cache tags
  bubble up and end up in the page cache.

as mentioned here => (https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-up-page)

So, one place to start would be trying to render the whole content variable in your twig template, provided you got past (a)

Update: You could also try calling \Drupal::service(''page_cache_kill_switch'')->trigger(); in order to avoid Internal Page Cache to interfere with the request and page loading.

A simple way to do this inside a twig template would be using an approach similar to this module => https://github.com/stefanospetrakis/twig_killswitch_trigger

Good luck!

P.S.: Sample code is also available here => https://www.drupal.org/sandbox/stefanospetrakis/3011610, I may promote this to a full project if there is any potential interest.


How do I start an empty breadcrumb? I am modifying a module that extends PathBasedBreadcrumbBuilder, but that only has methods to add a link at the end of the bread  and I want in certain cases to start the breadcrumb from scratch or add a link at the beginning of the breadcrumbs.

How can I do this?

I'm looking at this documentation and I think it says that you could start from scratch using:

$breadcrumb = new Breadcrumb();

And the class:

use Drupal\Core\Breadcrumb\Breadcrumb


How do I make an FTP connection from a module? I'm trying to create a custom module that would connect to an external FTP and grab an XML file (provided by third party). This file can't be accessed through http.

In Drupal 8, there is the Drupal\Core\FileTransfer\FTP class, but I'm not sure as of how I could use it inside my custom module. I don't see any service I could use.

Do I use that class directly, or is there a service I need to use?

The information about the classes that extends FileTransfer() are returned from hook_filetransfer_info(), and altered by hook_filetransfer_info_alter(). There isn't any service to use.
As such, the code that uses that class should be similar to the following one.

$info = drupal_get_filetransfer_info();

if (!empty($info['ftp']) && $class = $info['ftp']['class']) {
  $ftp = $class::factory($jail, $settings);
}

Notice that when the patch in Convert hook_filetransfer_info() to plugin system will be applied to Drupal 8.x.3, the code I wrote will probably need to be changed, if the change is not going to be backward-compatible.


Resetting admin user details I forgot my drupal admin password and tried resetting it using forgot password option, but it fails to work( does not send the mail).

Drupal 8 is installed on my localhost. I tried manually editing the users table in the database, so I deleted the user with uid 1(admin) and also deleted corresponding data for uid 1 from users_field_data table.

I am unable to figure out the value to be inserted for uuid in users table. I tried giving 1 for uid, my_name for uuid and md5(password), but the login fails. uuid seems to be encrypted somehow and i can't figure how.

Also, I am using wamp, so I haven't tried using drush or drupal console for version 8.

I found two relevant answers on topics " Insert “uuid” in “users” and Is there a good and recent documentation on the UUID API in Drupal 8 core? ", but not of much help.

You can't easily manually insert a user record. The password is not an MD5 hash, it a salted SHA-256 hash.

You hopefully made a backup, you should restore that. From there, you should consider to use drush, which is the by-far easiest way to log in, with drush uli to generate a one-time login link or drush upwd, to set the password of a user.


Which is the database table in which Boost stores the cache expiry time of a node and what is the column name? I was looking for a way to manually set the Boost expiry time of a node and happened to chance upon the boost_cache table. There is an expire column and I am assuming that it contains the timestamp denoting the expiry time of the database. Then I happened to see the timer column and now I am confused as to which column houses the expire timestamp.  Could someone explain?

Site runs on Drupal 6.

Basing on boost_schema(), the description of those fields is the following:

expire: UNIX timestamp for the expiration date of cached page
timer: Time in milliseconds that the page took to be generated

The expiration time is contained in the "expire" database column.


What is the difference between the $config and the $settings variables in settings.php? In the settings.php file of Drupal 8 installations, there are two different types of variables; $settings and $config. In Drupal 7 we used only $conf variable.

What's the difference between $config and $settigns variables in D8?

Settings are for early-bootstrap (you can't store the database credentials in the database) and environment specific things, like the path to the public file system. Things that are not meant to be exported/deployed.

That means in almost all cases in modules, you want to use the configuration API.


How to resolve fatal error 'Cannot redeclare commerce_kickstart_preprocess_html'? I have installed an ecommerce website with Commerce Kickstart, not in demo  mode. Everything was OK and I began to add products and then my problem started; when I click on 'products category' I receive this error message:

  Fatal error: Cannot redeclare commerce_kickstart_preprocess_html() (previously declared in /homepages/44/d576739206/htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php:41) in /homepages/44/d576739206/htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php on line 41

This is what that line 41 (as in the error message) looks like.

function commerce_kickstart_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Lobster+Two:400,700', array('type' => 'external'));
}

What could the problem be? How can I solve it?

Update (as in one of the comments): I tried to change as you said it and I have this message:

Fatal error: Cannot redeclare commerce_kickstart_theme_preprocess_html() (previously declared in /homepages/..../htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php:9) in /homepages/..../htdocs/profiles/commerce_kickstart/themes/commerce_kickstart_theme/template.php on line 41 code

Update 2 : So if I use another theme, the problem is solved.
And there are 2 (minor) differences in the new error message :
Now it is in that line "9" (no longer "41") :

function commerce_kickstart_theme_preprocess_html(&$variables) { // Add conditional stylesheets for IE drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-8.css', array('group' => CSS_THEME, 'weight' => 23, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-7.css', array('group' => CSS_THEME, 'weight' => 24, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

Update 3 : Here is template.php :

<?php
/**
 * Preprocess variables for html.tpl.php
 *
 * @see system_elements()
 * @see html.tpl.php
 */
function commerce_kickstart_theme_preprocess_html(&$variables) {
  // Add conditional stylesheets for IE
  drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-8.css', array('group' => CSS_THEME, 'weight' => 23, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE));
  drupal_add_css(path_to_theme() . '/css/commerce-kickstart-theme-ie-lte-7.css', array('group' => CSS_THEME, 'weight' => 24, 'browsers' => array('IE' => 'lte IE 7', '!IE' => FALSE), 'preprocess' => FALSE));

  // Add external libraries.
  drupal_add_library('commerce_kickstart_theme', 'selectnav');
}

/**
 * Implements hook_library().
 */
function commerce_kickstart_theme_library() {
  $libraries['selectnav'] = array(
    'title' => 'Selectnav',
    'version' => '',
    'js' => array(
      libraries_get_path('selectnav.js') . '/selectnav.min.js' => array(),
    ),
  );
  return $libraries;
}

/**
 * Override the submitted variable.
 */
function commerce_kickstart_theme_preprocess_node(&$variables) {
  $variables['submitted'] = $variables['date'] . ' - ' . $variables['name'];
  if ($variables['type'] == 'blog_post') {
    $variables['submitted'] = t('By') . ' ' . $variables['name'] . ', ' . $variables['date'];
  }

function commerce_kickstart_theme_preprocess_html(&$variables) {
drupal_add_css('http://fonts.googleapis.com/css?family=Lobster+Two:400,700', array('type' => 'external'));
 }
}

Because the two file paths are the same file, it suggests a possible problem with your op-code caching.

Check if you have any PHP op-code cache enabled; you should only have one op-code cache utility and may need to disable one.

You may also need to tweak your APC settings (if enabled).

apc.include_once_override = 0

Check also https://stackoverflow.com/questions/4575341/php-with-apc-fatal-errors-cannot-redeclare-class.


What is the most efficient way to create and manage 500 sales/landing pages For a domain sales business, what is the best way to create and manage about 500 landing pages, each connected to a top level domain name?

I have worked with the Domain Access module in the past, but that becomes very unpractical with more than 10 domains, it lacks the features to handle large numbers of domains.

I have worked with and Aegir server but don't have experience with using a shared Drupal commerce instance for all the domains.

The domain landing pages can either be one page or multiple pages (sites) as long as it will be easy to apply different themes to them easily, if possible through a centralized management tool.

Disclaimer: I'm a maintainer of Aegir.

Aegir is inherently multi-site, you can have many sites on a shared platform, which means you can have many independent sites with the same codebase. This is a lot more efficient resources-wise than having multiple sites without a shared codebase.

If you often need to create new domains, I developed a Software-as-a-Service suite for Aegir: https://www.drupal.org/project/hosting_saas

Since there is E-Commerce involved, you'll want to have an SSL certificate, with Aegir you can easily use the same wildcard certificate for all the sites if necessary.

If the landing pages don't need to be customized (much), you can even have a single site with 500 aliases in Aegir.

Lastly, one of the main advantages with Aegir is that you can simply clone a site when you need a new instance (which is what we do in Hosting SaaS).


Why are there "template_" and "theme_" prefixes instead one? What's the difference between these ones in function names? I can overwrite each one in template.php, so?

The functions whose name start with theme_ are theme hooks, while the functions whose name start with template_ are preprocess and process functions implemented by the module that implements the relative theme hook.

For example, theme_image() is a theme hook that renders an image.   template_preprocess_node() is the preprocess function implemented by the Node module, which the module implementing the node theme hook. (See the first code lines of node_theme(), the hook_theme() implementation done by the Node module.) There are other modules that can implement a preprocess function for the node theme hook, but for those modules, that preprocess function is named MYMODULE_preprocess_node(), not template_preprocess_node().

A theme can implement both a theme hook (see bartik_menu_tree()) and a preprocess function (see bartik_preprocess_node()). The difference is that bartik_menu_tree() overrides the default implementation (theme_menu_tree()) when the current theme is the Bartik theme, while bartik_preprocess_node() doesn't override template_preprocess_node(), but it is executed after it. (See the documentation for theme().)

As for using two prefixes, the reason is to documenting the purpose of the function. Even if theme_ were used in both the cases, the difference between theme_image() and theme_preprocess_node() would still be clear, but it would require you to read what follows theme_. With the current implementation, you just read the first word of the function name.