Why my stylesheet won´t load into my node/add forms? (D6) I wanted to have a special template for all my node/add forms, in my Drupal 6 installation.

So, I´ve added this code to a little module:

function modding_preprocess_page(&$vars, $hook) {
  if ((arg(0) == 'node') && (arg(1) == 'add')) {
    $vars['template_files'][] =  'node-add';
  }
}

My node-add.tpl.php template looks like this:

<?php print $title ?>

<?php print $content ?>

The thing is that all styling has gone.

The style sheets won´t load, and I don´t understand why. It looks as ugly as it can get when no style whatsoever is loaded.

I may add that I´ve cleared cache more than once, and as this is a testing site, all performance caching has been disabled.

Thanks for your help!!

I´ve found the solution:

<?php
      if ((arg(0) == 'node') && (arg(1) == 'add') || (arg(2) == 'edit')){
    $node = node_load(array('nid' => arg(1)));
    print $title;
    }
?>

Thanks to nevets, who gave me the hint that I needed! :)


Rules sends email to mailto link instead of email address I've created a content type with an email field. Anonymous users are allowed to create these nodes. I've created a Rule that sends an email message to the value submitted in the node's email field, using a replacement pattern. Rules tries to send the email to a mailto: link, not to the email address. The outgoing mail fails with the sendmail error: "Cannot mail directly to files", because it is addressing the email to the link, not the address.

Click the button that says "Switch to Data Selection" and choose the Data Selector corresponding to your email field, not the Replacement Pattern.

That way the Rules module will send the email to the actual email address, instead of to the 'mailto:'-link.


Merge 2 collumn (Display suite) to one collumn depending on resolution In a situation with display suite and two columns (left and right) I would like to accomplish to move everything to the left column and have the ability to reorder the fields.
In a classic situation the whole right column is moved under the left.
For example in the left column I have field1,field2,field3 in the right field4,field5,field6
When resolution is < 800 px I want to end up with a left column with field1,field4, field2,field5,field3,field6.
Not sure how I can make this happen, and any example or suggestion is welcome.

I think one option is to start with one collumn to begin with and build a 2 collumn situation like this: http://demos.wpmission.com/strong-testimonials/examples/two-columns-via-css-column/
But maybe there is other solution to use code to move and rearange the fields from the right to left ds column?

Thx a lot !

I would use a combination of 2 view modes plus Context Mobile Detect to trigger the different view mode


Variables are missing on page--node--add.html.twig I have created two templates

page--node--edit.html.twig

page--node--add.html.twig

I have discovered that the {{ node }} and {{ node_form }} variables are missing during node creation.

Here is my code to render the node add form there using hook_preprocess_page.

  $variables['node_form'] = FALSE;
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $form = \Drupal::entityTypeManager()
        ->getFormObject('node', 'default')
        ->setEntity($node);
      $variables['node_form'] = \Drupal::formBuilder()->getForm($form);
   }

My goal is to print node content type name and form from page--node--add.html.twig template.

PS. No issue on page--node--edit.html.twig (node edit page)

if ($node = \Drupal::routeMatch()->getParameter('node')) {

There's no node ID in the route at /node/add/foo, so there's no node available, and that condition will always be false.

You need to create the node yourself, e.g.

// Get the desired type from the route.
if ($node_type = \Drupal::routeMatch()->getParameter('node_type')) {
  $node = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->create([
      'type' => $node_type->id(),
    ]);

  $form = \Drupal::entityTypeManager()
    ->getFormObject('node', 'default')
    ->setEntity($node);

  $variables['node_form'] = \Drupal::formBuilder()->getForm($form);
}


Custom validate function not working I'm sure there's some simple reason that my custom validate function isn't executing.

Here's my code:

function MYMODULE_form_message_ui_instance_message_manage_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#validate'], 'MYMODULE_validate_relationship');
  watchdog("form", "
" . print_r($form, true) . "
");
}

function MYMODULE_validate_relationship($form, &$form_state) {
  watchdog("validate form state", "
" . print_r($form_state, true) . "
");
  watchdog("validate form", "
" . print_r($form, true) . "
");
}

On form submission, the first watchdog - "form" is being exected, however the second and third are not. Why is this? I can't find any information on why a custom validate hook wouldn't execute.

EDIT per Pierre's request:

I am writing a custom validation function that I am trying to execute before the other validation functions. I am doing this using array_unshift. This seems to be working, as my #validate array looks like this:

[#validate] => Array
    (
        [0] => MYMODULE_validate_relationship
        [1] => message_ui_instance_message_manage_validate
        [2] => message_private_form_message_private_instance_message_manage_validate
    )

However the code in MYMODULE_validate_relationship is never executing.

As far as I can tell, $form and &$form should be irrelevant in the validate function, because once you're at the validation stage, nothing should actually be modifying the form (I think?). And most examples I was seeing did not including passing the $form by reference. And I've tried both ways, and in neither way is the validate hook firing.

The answer is that the submit button was being generated by the actions array item.

Simply changing my form value to this:

$form['actions']['submit']['#validate'][] = 'MYMODULE_validate_relationship';

Correctly allowed it to be executed.

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#actions


Disable registration functionality for sub-domain in Drupal 7 I am using Domain access module for my multi-site creation and using common database for both the site:

1. example1.com (Default domain)
2. example2.com (sub domain)

I want default registration functionality for default domain (example1.com), but don't want this functionality on sub domain (example2.com).

If I configure this registration functionality only for Administrators from admin section (Home » Administration » Configuration » People) from default domain (example1.com) look like below screenshot:

Then this will be applicable for both example1.com and example2.com, as I am using common database and common tables for both the sites.

So can anyone please guide me how can I disable the Registration functionality for sub domain (example2.com) and use this same for default domain (example1.com).

Thanks in advance.

According to this answer on SO (to a 'similar' question posted 'a bit before' this question ...), this is a possible answer to this question (= quote from that question):

= = = Start = = =

As far as I know you can have different variables per domain (Because the Registration option is a variable) using the latest Domain Access module (currently 7.x-3.11 from 2014-Mar-02). It can be done with a submodule named Domain Settings. Enable it if haven't done yet.

If for any reason does not work for you I would suggest to use the Domain Variable module to handle variables for each domain.

= = = Stop = = =


How to Create a Blank Page I need to create a completely blank page in Drupal. For simplicity sake the entire page should display the following:

Hello World!

While I can normally just create a page outside of Drupal, this page will need to access some of Drupals functions such as db_query. How can I create a completely blank page for a single url (e.g. http://www.example.com/blankpage)?

I don't really advise this but here is a solution.

Create a php file in your Drupal root containing the following

<?php
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

That will give you access to the full Drupal api. You can then put whatever markup you wish underneath.

A better method (but more complicated) would be just to create a custom page callback in a module then you can use that to either bypass Drupals theming, or you can make it change the theme to a custom one that produces very basic markup (you'd have to create that yourself).

If you want any details on how to do that let me know :)


Drupal aligning blocks and content next to each other i have a view page and two blocks which i want to display next to each other. I want view content on left and two blocks on right, with one block on top and other just below it. But i am having trouble in achieving the same. My html guy says its not possible to do that without a wrapper container as we need to have things in center as well.

I have omega 4 installed, so sidebar is also below the content block. Also i don't have consistent layout view, as on some pages i have only content with full screen background, and with no side content and on some i have content in which i am facing a problem.

I have searched on google and SO but every solution says to have a wrapper, which is not possible as placing a wrapper globally will limit the display on every screen, which i can't have.

One solution i can think of is use javascript to add classes on page load where i have two column display but it is not a good way to do that i believe.

How can i solve this, can anyone please help??

You can make use of  Panels Module to achieve any kind of Complex Layouts


What are best practices for Drupal 7 my.conf settings? I posted the following wiki to GDO to try to consolidate best practices for Drupal implementations:
http://groups.drupal.org/node/289613

There's just so much written out there, but the documentation is often old or very personalized to one person's my.conf file.

What have other folks used.  Starting with https://tools.percona.com/wizard seems to be the best approach, but the Wizard doesn't know anything about Drupal.

You need to profile this yourself, every server is different - there's not really any such thing as 'best practice' here; get mysqltuner up and running, and follow the recommendations.

Don't try to think of it in terms of Drupal, rather in terms of any web application which needs optimising. If you get too hung up on the 'Drupal' aspect you'll end up looking in the wrong places to optimise


Changing text in Ubercart form I am using Drupal 6 with Ubercart 6.x-2.9. In checkout, I dont need my customers to fill out their address - I just need name and email. So I have removed the address fields within the 'Billing information' part of the form.

When the customer gets to the 'Review Order' page, it lists the name and address with the label 'Address:'. As I only have the first and last name fields, I wish to change 'Address:' to 'Name:'.

Strangely, I cant seem to find anywhere where this 'Address' label is set (I did a text search in all files and searched through the database). Can anyone help please.

There is String Overrides

  Provides a quick and easy way to replace any text on the site.


Show new result each time I visit the page I want to display a result in a view, and each time I visit the page, the result will be the next node from the choosen contenttype.

Is this something I can manage in views or is there any other way?

In Views Sort criteria Section Choose the Global and then choose Global: Random field, it will display each time different result(when the page is refreshed) but it will be random.

I hope it will help you.


In a view, how can I display all sub categories of a given taxonomy term with content from each sub category? For each article, I assign a 'sub-category' taxonomy vocabulary term.  Then for each 'sub-category' taxonomy term, it links to a 'category' taxonomy vocabulary term.

I have set up a variant of the taxonomy-term template page that passes the category ID as an argument to a view.  This view then uses a contextual filter to display all content within all sub-categories for the given category ID.

To illustrate, say you type in sitename.com/taxonomy/term/1922 which is, say, movies.  The view will display all content marked with movies' sub categories.  So it currently would show this:

/taxonomy/term/1922 (Movies)
Title         |      Sub-Category |
——————————————————————————————————-
Star Wars     |            Sci-Fi |
Star Trek II  |            Sci-Fi |
Home Alone    |            Comedy |
Office Space  |            Comedy |
Thin Red Line |               War |

What I want is to have, say, 5 pieces of content per sub-category titled by the sub-category.  Something like this:

/taxonomy/term/1922 (Movies)

Scifi:

Star Wars
Star Trek II
...
...
...

Comedy:

OFfice Space
Home ALone
...
...
...

And so forth.  So that it would title all sub-categories and show the top x number of nodes per sub-category.

This isn't a great answer, but after a couple days of trying to do this myself, the best I could figure out was to use Views Field View (I think that Views Grouping Row Limit would probably work too, but it's still in dev).

Create a basic node view that lists off your five movie node titles (along with any other teaser-like content you'd like), set your page to limit to five entries, and set the contextual filter to the movie's taxonomy term.

Then, make a view that shows taxonomies belonging to the vocabulary (movies). Set the contextual filter to "taxonomy term: parent term"), and output the tid (hidden) and term title. That'll make a list of your parent terms, so now add a views_field_view (set it to use your first view for input, and the tid for your argument).

Again, there's got to be a better way than this, as I'm sure it's going to create some real system overhead.

Pleeeease, someone come up with a better answer!


Combine 2 contextual filters - taxonomy term ID from url and NID Is it possible to get taxonomy term from url and node id at the same time from current node? I need to get taxonomy term from current node to pull some date from referenced nodes that have parent taxonomy of current node term. So far ok. But moreover I need to be able to get to current node's fields. Using another conextual filter to get NID was not helpful.

I don't think you can do this with multiple contectual filters.

Sounds like you need relationships.

Use the contextual filter to get the current nid and show the fields for that node.

Then add a relationship between the node and its terms (you can limit this by vocab if need be) by adding the relationship "Content: Taxonomy terms on node".

Then add a relationship from the term to the parent term by add the "Taxonomy term: Parent term" relationship. This relationship should use the previous relationship.

The add a relationship from the parent term to the content that uses that term by adding the " Taxonomy term: Content with term" relationship. This relationship should use the Parent relationship.

Then you can do extra things like adding filters that use these relationships.

All these relationships can have the "Require this relationship" checkbox checked.

With some relationships you can end up with duplicate results.
One way to try to avoid this is go in the "Query options" in the "Advanced" part of the views configuration and check the "Distinct" checkbox.

Relationships can be confusing and they are hard to explain, but if you play around with them, once you understand them they are very useful.

Extra question
To answer your extra question of whether you can display the value of one field if it is there and if it is not then show another field in its place:

Yes, you can do that.
Depending on your requirements there are a couple of ways it can be done:

Exclude the secondary field from display and for the primary field check "Rewrite the output of this field" and use the tokens to print the primary and secondary fields out next to each other. This solution will only work if only one or the other of your fields will have a value. If there is a chance that both fields will have a value you will end up with both values printing next to each other.
Exclude the secondary value from display. Then in a custom module implement hook_view_pre_render() and you can check the $view->result to see if the primary field has a value. If it doesn't you can replace the empty value with the value of the secondary field.
Override the template for views_view_fields.tpl.php so that if the primary field is empty you print the secondary one. And don't print the secondary one. This could also be handled in the preprocessor function template_preprocess_views_view_fields() in your theme's template.php file.

Unfortunately I don't have time to give code examples right now.


Initially unchecked radio boxes in a form on load I have programmed module having a form (using Drupals's form API) which contains radio checkboxes like this:

$form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
        '1' => t('Yes'),
        '0' => t('No')
    ),
    '#required' => TRUE,
    '#checked' => '', // ???
    '#title' => t('a label text ... '),
    '#default_value' => !empty($form_state['values']['r_8']) ?
        $form_state['values']['r_8'] : '',
    '#suffix' => '

'
);

When the page with that form is initially loaded, I want all these radios initially unchecked. I tried to set the #checked property to FALSE, but it doesn't work. Setting the #default_value to, for example, -1, a warning raises (which I can understand, because -1 is none of the provided option values).

Is there any way to load initially the form with the radio's unchecked?

I could not find any information pointer so that's why I ask here.

Thanks in advance!

#checked is not a property used from radios form fields, nor radio form fields. It was not even used from Drupal 6.

I used the following code, and none of the radio buttons were selected.

/**
 * Form builder.
 */
function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}

In this case, if the user doesn't select one of the radio buttons, the form field would not have a a value associated. Your code could handle it as if the user selected a third value (such as "undecided") or what your code considers the default value (e.g. "yes"); if the latter is the case, users should see a note about that.

It makes sense to use the following code, at least in a case: When you want the users voluntary select a value for the field, and not use the default one selected by the module. For example, it would make sense if the user is expressing an agreement, and you want to be sure the user noticed that field, and clicked on one of the radio buttons.

function custom_module_form($form, &$form_state) {
  $form['r_8'] = array(
    '#type' => 'radios',
    '#required' => TRUE,
    '#options' => array(
      '1' => t('Yes'),
      '0' => t('No')
    ),
    '#title' => t('Test'),
    '#default_value' => NULL,
  );

  return $form;
}


Always prompt for a shipping address even if there are no shippable products with Ubercart I manage a site selling online classes. Some classes include shipped items (books, posters, etc); for these classes, the cost of shipping is included in the class price.

Ubercart products are configured as non-shippable, as automated shipping quotes through UPS should not add any additional cost.

I'd like to configure Ubercart (6.x-2.4) to always prompt users to enter a shipping address, without returning an error message when products in the order are not flagged as shippable.

At present, Ubercart will always prompt the user for a shipping address if "Hide shipping information when possible for carts with no shippable items" is unchecked in "Checkout settings." However, it looks like the UPS module will always try to calculate a shipping quote if shipping details are prompted for, regardless of whether items are shippable or not. If this is the case, an error message is displayed informing the user that a shipping could not be calculated.

Is it possible to configure shipping settings to still prompt for a shipping address, while preventing shipping modules such as UPS from returning an error message if no shippable products are configured?

For example:

    Order A: (works with UPS shipping module)
         Shippable_product_A  $10 (shipping $5)
         Shippable_product_B  $20 (shipping $8)
         --------------------------------------
         Total order cost: $30 + $13 => $43

    Order B: (does NOT work with UPS)
         Shippable_product_A    $10 (shipping $5)
         Non-Shipped_product    $15
         ---------------------------------------
         Total order cost: $25 + $5 = $30

The only work around for this is to alter the UPS module yourself or report it as bug, (because in my opinion, this is a bug.)

You could probably write a module that would override the UPS module to circumvent the above suggestions. You have pretty clearly hit the nail on the head though. The problem is not Ubercart but the modules that are interacting with it inappropriately. I know the FedEx module takes into account shipable products, if my memory serves me correctly.

The entire shipping pane should be hidden if there are no shipable items. (That is the point of having that option in the products.)


How to let views's sort criteria random equally I have two node content. I want to know which content is able to convince user to sign up.

I create a views block and two node contents. The views will randomly choose one node content and display.

At the views sort criteria, I choose global random, but it does not random equally. It choose option A more than option B.

Question: How to let it choose random equally or alternate such as A,B,A,B,A,B..etc?

If you enable core Statistics module, you get some more filters in views:

Content statistics: Most recent view
Content statistics: Total views
Content statistics: Views today

You can select one of them, and sort ascending. So that it will always show the least recent viewed node, or least viewed node in all times, or least viewed node today, respectively which filter you've chosen.


Commerce PayPal commerce_payment_transaction PDOException[23000] I'm using commerce paypal to accept payment on a drupal website. i have configured the module as described in drupal commerce support website and created sandbox accounts both for buyer and seller. i created a test order and paid with paypal, the IPN is received successfully and it is verified according to report/dblogs with message:

  IPN validated for Order 2 with ID 7DW624906V374562U.

But after this db log there's another one which is an error with message:

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created,
  data) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1,
  :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 13054
  [:db_insert_placeholder_1] => 1396116964 [:db_insert_placeholder_2] =>
  a:1:{s:7:"contact";i:1;} ) in drupal_write_record() (line 7194 of
  /home/findaper/public_html/includes/common.inc).

and type:

  commerce_payment_transaction

So, the payment is validated, but there's this error, and the event "when order first paid in full" is not firing. i have no idea how to fix this. can anyone help me with this??

drupal and all modules are the latest version. [drupal7]

Duplicate entry '' for key 'name': INSERT INTO {users} (uid, created, data)

This is incorrect code, since no name value defined for inserting, so user name is empty and name should be unique - you cann't insert second user with empty name.

Try find this code INSERT INTO {users} (uid, created, data) on your drupal files (modules), if no success, investigate your Rules for custom code.


Migrating image with fields Working on a migrate task for images. On d7 and d8 I've file_entity with two fields, but values are not imported.

Here is my source json:

{
  "items": [
    {
      "id": "2417",
      "uuid": "b0ad2fca-d100-45bf-9423-2474f00af68b",
      "filename": "terremoto_irpinia.jpg",
      "filepath": "public://terremoto_irpinia.jpg",
      "url": "http://localhost/sites/default/files/terremoto_irpinia.jpg",
      "links": [
        {
          "url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-napoli-a-foggia-35-anni-dopo",
          "title": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n...",
          "attributes": [],
          "html": false,
          "query": null,
          "fragment": null,
          "absolute": true,
          "display_url": "http://www.foggiacittaaperta.it/news/read/terremoto-irpinia-1980-il-ricordo-da-n..."
        }
      ],
      "alt_text": "some text",
      "created": "1472139573",
      "stato": "Permanente",
      "created_year": "2016",
      "directory": "public://immagini/2016/terremoto_irpinia.jpg"
    },
]
}

On yml, this is my process:

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  urls: http://localhost/modules/custom/migrando/files/download_immagini.json
  item_selector: items
  fields:
    -
      name: fid
      selector: id
    -
      name: filename
      selector: filename
    -
      name: uuid
      selector: uuid
    -
      name: filepath
      selector: directory
    -
      name: url
      selector: url
    -
      name: links
      selector: links
    -
      name: alt_text
      selector: alt_text

  ids:
    fid:
      type: string

process:
  uid:
    plugin: default_value
    default_value: 1
  filename: filename
  uuid: uuid
  status:
    plugin: default_value
    default_value: 1
  created: created
  alt: alt_text
  field_image_alt_text: alt_text
  field_fonte_immagine:
    plugin: iterator
    source: links
    process:
      uri: url
      title: title
      options: attributes
  uri:
    plugin: file_copy
    source:
      - url
      - filepath

Don't work field_image_alt_text and field_fonte_immagine fields.
What's wrong?

Thanks!

I don't see the destination configuration here - presumably the plugin is entity:file, correct? Are you setting default_bundle there, so the file entities are created with the correct type (the bundle those fields are attached to)?


Internal Server Error - Downloading attachments I've recently migrated a Drupal 6.22 site from my local host (Xampp 2.5) to a remote, shared server - Fasthosts hosting services.

After uploading the files through ftp and importing the database, I couldn't access the site at all - it would return a 500 Internal Server Error. Trawling the Drupal forums and searching online, I found out that this was down to the .htaccess file, which I subsquently removed.

This allowed the site to load, but only the homepage. I then found a .htaccess file in the Drupal forum which someone had edited and I uploaded that, which gave me full access to the site - good times! However, after performing a walk-through of the site, I've found that I cannot download any of the attachments I've uploaded to some of the pages.

Is this a .htaccess issue? I've trawled many forums and posted several questions around the place, but no one has given a response yet. My mate highly recommended StackOverFlow, so I hope someone can help!

I've checked the server logs and it's states the error is that the file is not found! But I've deleted and re-uploaded then several times now.

Can anyone advise?

Drupal can put .htaccess files in some folders. It is likely that something in your Apache setup is different and the .htaccess files are no longer valid on your new server.

Removing the .htaccess file from the sub folder could leave you open to hacks, so it may be worth looking to see what it was trying to do and make sure that you are secure.


Allowing unlimited values for a field in programmatically defined form I am trying to insert a custom form into a page in my Drupal 8 site. This form has 2 fields which need to accept unlimited values (one textfield, one fieldset).

In my current implementation, I have declared this form as a class, defined in the src folder of a module, and my .module file adds this form to the $build array via hook_node_view_alter():

$build['myform'] = \Drupal::formBuilder()->getForm('Drupal\my_module_hook\Form\MyForm');

My class constructs the form using public function buildForm(array $form, FormStateInterface $form_state). I am not sure how to set up a field such that it can accept unlimited values.

I'm aware that tutorials and answers on this topic using Ajax exist such as this and this, but all such examples are using $form_state as an array, which breaks my code as $form_state is an object.

Is building this form as a class the wrong way to do it? If not, how exactly do I accomplish what I'm trying to do without using $form_state as an array? If so, how can I insert my form into the page otherwise? I'm not understanding how other answers and tutorials on the subject are accomplishing this since these functions are usually shown out of context.

I have set up a module demonstrating how to allow the user to add unlimited values:
https://bitbucket.org/scotteuser/drupal-8-demo-form-unlimited-values

Here is the Form itself:

<?php

namespace Drupal\demo_form_unlimited_values\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class UnlimitedValuesForm.
 *
 * @package Drupal\demo_form_unlimited_values\Form
 */
class UnlimitedValuesForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'unlimited_values_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // State that the form needs to allow for a hierarchy (ie, multiple
    // names with our names key).
    $form['#tree'] = TRUE;

    // Initial number of names.
    if (!$form_state->get('num_names')) {
      $form_state->set('num_names', 1);
    }

    // Container for our repeating fields.
    $form['names'] = [
      '#type' => 'container',
    ];

    // Add our names fields.
    for ($x = 0; $x < $form_state->get('num_names'); $x++) {
      $form['names'][$x]['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name @num', ['@num' => ($x + 1)]),
      ];

      $form['names'][$x]['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name @num', ['@num' => ($x + 1)]),
      ];
    }

    // Button to add more names.
    $form['addname'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add another name'),
    ];

    // Submit button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Decide what action to take based on which button the user clicked.
    switch ($values['op']) {
      case 'Add another name':
        $this->addNewFields($form, $form_state);
        break;

      default:
        $this->finalSubmit($form, $form_state);
    }
  }

  /**
   * Handle adding new.
   */
  private function addNewFields(array &$form, FormStateInterface $form_state) {

    // Add 1 to the number of names.
    $num_names = $form_state->get('num_names');
    $form_state->set('num_names', ($num_names + 1));

    // Rebuild the form.
    $form_state->setRebuild();
  }

  /**
   * Handle submit.
   */
  private function finalSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Do what you want with the final data here'), 'status');
  }

}

The critical bits are:

$form[#tree] tells Drupal that the form is hierarchical.
$form_state->get() and $form_state->set() are used around the counter num_names
Check the 'op' to see which button the user pressed. If they pressed to add another field, use $form_state->set() to increase the count and $form_state->setRebuild(); to tell Drupal that the form should be rebuilt.

Hope that helps you get it working!


How can I allow users to specify image dimensions in CKEditor I have a use case where content editors have a requirement to specify the height and the width of an image in the image properties. Sticking to styles is not possible because $reasons.

The CKEditor demo has this:

But the Drupal 8 image properties looks rather sparse in comparison.

I've looked all over for this for hours, and this is the first time I've had to write my own Drupal Answers question!

Does anyone know how we can expose the option to set width and height in CKEditor?

I'm aware of IMCE - but expected behaviour of the module in Drupal 8 is to use IMCE for file upload only - once an image is placed, image properties is handled by CKEditor.

There is a YouTube video where someone has managed to configure CKEditor to use IMCE's image properties: https://www.youtube.com/watch?v=2eTfQ7Y4i5I but there's no instructions on how this was achieved, and a comment-or asked but has been hanging for a year.

I'm totally new to Drupal 8, would like to know how to do this! And then I'll figure out how to make sure the change isn't reverted next time core is patched :)

Depending on how far you are in your project consider using Paragraphs instead, to have your content built modularly. Inline images are bad practice IMHO. They are difficult to preprocess and difficult to apply responsive image styles.

With Paragraphs (or in general with a fieldable approach instead like Kevin pointed out in the comments) you'd provide certain paragraph types, for example one for pure text and one for an image. Editor then places an image paragraph, followed by a text paragraph and the text simply floates around the image. You can have responsive image styles for the image, you can build the image field according your logic to provide certain crop types etc.

I know this is not the answer you might look for, but honestly for the sake of maintainability think about it if putting everything into the body field will still work in the long run. In my experience this can lead to a very big mess. Hard to disassemble, hard to migrate, hard to maintain.


Selecting content type using panels/pages We want to select a content type in panels with a specific URL [tgeink.com/latest-news].  Here's why:

We are using panels for several content type 'home pages', like news, articles, etc.  They all rely on a view that displays recent posts in the various content types, along with an exposed menu so that users on the 'news' page only get news when they select a topic.  Currently we are creating different views for each content type because we can't see how to select content type in panels -- we do it in views.

[It's easy if you are using panels for /%node.  We use that to display and edit nodes, with variations for the different content types.]

We'd LIKE to be able use one view for all 'home' pages, and use panels to select the content type.  However, we cannot see how to do this when the panel is referencing a URL such as TGEink.com/latest-news.  Thanks for any help.

You can use views for that solely too you know... Don't use a content pane as described below but a page with path /latest-news/%type.

But for panels:
Create a views content pane that gets all types of nodes @ once. Set contextual filter to node->type and choose raw value from url 2.

Create a page in pagemanager with this path:
yourdomain.com/latest-news/!type
Don't set up a context.

Add the contentpane as content in the page.
Now if you visit latest-news/article it shows all article-nodes. If you visit latest-news/page it shows all page-nodes.

Now you can have all benefits from panels together with a view.


How to edit and delete entityform submissions? I'm using entityform for particular submission. I set the rule When submitting the entityform, its stored in particular content type. Its works well.

But when edit and delete the particular entityform submissions its not work.

So how to relate the entityform submission edit, delete operation stored to the content type i created.

Is there any rule or hook available to store entityform submission to particular content type.?

Thanks in advance!!

use entityform hook_form_alter with devel module in this case i suggest to view your data before submit button ... and entityform hook_form_insert to view your data after submission button using devel module or drupal_set_message. You can actually alter in hook_form_alter button to  store entityform submission to particular content type.


How can I replace a custom token? I am trying to add a custom token in pathauto.
I have a token [story-page-number].
Then in my hook_pathauto_alias_alter() I am trying to replace it using token_replace().

Something is not quite right though.

token_replace("[story-page-number]", (array)node_load($context['data']['node']->nid));

Here's my custom token set up.

function mymodule_token_list($type = 'all') {
    $tokens['story-page-number'] = t('Page number (of story front)');
    return $tokens;
}

function mymodule_token_values($type, $object = NULL, $options = array()) {
    $values = array();
    $values['story-page-number'] = get_story_page_number($node->nid);;

return $values;
}

What am I missing here, I thought it would be a lot more straight forward.

Try this:

$node = node_load($context['data']['node']->nid);
token_replace("[node:story-page-number]", array('node' => $node));

If $context['data']['node'] is already a node, then you may skip the node_load() call, and simply assign $node = $context['data']['node'];

Edit: Sorry, I didn't try your example in code.  You need to include the token type in your token names. In mymodule_tokens(), check to be sure that $type is 'node', and then look up $node from $data['node']. Note that you are using the Drupal 6 hook_token_values(); you should use the D7 hook_tokens().  Use the implementation of node_tokens() as a guide.

References

hook_tokens()
token_replace()


Can't get generated content to push footer down I have been hitting my CSS head against the wall for hours now.  I'm not sure what I am doing wrong but I sure would appreciate some insight.

I've got a view that is populated by a content type that has an image and text.  I've tried at least three sticky footer approaches and none worked.

We took bartik and modified the CSS as we've moved forward.  I don't know if there's some css remnant of bartik wreaking havoc or my own CSS ineptitude.  But we need to get it fixed and any help would be greatly appreciated.

Scott.

First of all, never modify a core theme. Sub-theme. :) Second, the problem is that you are specifying "position:absolute" on some of your blocks which causes the CSS box-model to ignore any content inside the wrapper divs. When you write absolute, you are telling the browser: I know exactly where my content will be and so therefore you should ignore any flowing you want to do.

Try moving away from using position:absolute to position elements and instead use floats which will push the content region height and, in turn, your footer.

More info: http://www.w3schools.com/css/css_boxmodel.asp


Is there a real-time inline field validation module? Currently I'm using the Clientside Validation module for validation of my fields, but I want to be able to have per field real-time validation. Like a check thingy showing if it's correct or a small inline error when there's an error in there. I searched a bit and couldn't find a proper module.

Is there a module for that?

Use Rich Form Module.

This module gives you a framework to easily make client side and server side validation in the same time. It increases the validation features of the Drupal Form API (FAPI). If you want to have a powerful tool for creating custom validation logic to any text field, without writing a tons of codes, this module is for you!


How do I create a front page? I am developing new website in D7 and I have installed bootstrap theme on the of it.

So, now I want to create home page/front page for my website and for that I have created a basic page, but I am not able to add CSS and JS in that basic page.

What approach should I use to create a front page in Drupal 7?

There are two option:

Use a different template for the front page you have to name your template page--front.tpl.php and clear the theme registry. Please check Theming Guide for more details.
There's also the Front Page module: http://drupal.org/project/front


Web form Report crashes upon adding date field I'm using the Webform Report module (version 7.x-1.0) alongside Webform module (7.x-4.16) on Drupal 7.22. When I add Date column to Webform report then save it and view ,Report crashes with message ..website is currently unable to handle this request.HTTP ERROR 500. no matter what format(yyyy/mm/dd..) I enter in date field or leave it empty same happens, If I create report in View by adding all fields including Date fields it works. Also in Webform-Results -Table it works.
Any suggestions..
Also can we in drupal 7 enter date and time both in same textbox so it lands in db in one field or it must be separated as I see drupal has it as separate types?

Thank you,
Nikola

I'm not in situation where we can easily update Drupal because of work environment, the solution was forena reports, which offer full freedom in sql queries(not limited by Webform report or Views limits when creating sql) also result(report) based on query can be shown in drupal interface, just needs some more css adjustment in table header/table data widths for columns

Nikola


Routing for controller with multilingual enabled On my Drupal 8 multilingual project, I have made a custom controller which create a basic page, but I can't figure out which parameter I must use in the routing. Is this _locale?

This is the definition of the route.

custom.route:
path: '{_locale}/portail'
defaults:
  _content: '\Drupal\my_module\Controller\DisplayController::display'
requirements:
_access: 'TRUE

This is the code I am using in the controller class.

public function display(Request $request, $locale) {
    var_dump($locale);die;
}

The language is detected and the prefix removed before routing. So you have a static route without parameter and in the controller you can get the prefix from the language manager:

  $langcode = $this->languageManager()->getCurrentLanguage()->getId();


D7 - Whitespace before printed fields How to get rid of the whitespace in printed fields?

Here's my source code in node.tpl:

<div class="banner" style="background-image:url('<?php print render($content['page_banner']); ?>');">

And here's the result (whitespace before http://)

Any ideas?

Have you tried adding a trim() ? Like :

<div class="banner" style="background-image:url('<?php print trim(render($content['page_banner'])); ?>');

It should just do the trick...

Beyond that, whatever is generating the $content['page_banner'] content is probably adding the unnecessary spaces.


Change form validation error messages In my theme I'm already using the hook_form_alter to customize the form fields but now I want to customize the validation error messages.

After some research, the only way I'm finding is to write a whole separate function and custom error handling of each form field.

I don't want to reinvent the wheel.  Isn't there just a simple way to change the default form validation error so I can get away from "XYZ field is required?"

There are a number of options to resolve this issue:

One option is using the String Overrides module to replace the string used to generate the message.
Another option is to create a custom module that overrides the validation function for a particular form or field, replacing any error messages with the messages of your choosing.
The following link may also help:

Custom Validation Message


Cookies for anonymous users aren't read nor checked I currently have a module on http://hitechwolf.com that creates a welcome overlay upon a user's first visit, This should work by utilizing a jquery created cookie and showing the overlay based on its existence. The jquery works, the cookie is created, but for anonymous users the cookie is ignored and the overlay shows on every page. I've implemented jquery.cookie but it still completely ignores the cookie for anonymous users. I'm at the end of my rope, any help or alternatives would really be appreciated.

welcome-overlay.js

/**
 * @file
 *  Toggles Welcome Overlay, upon first button
 *  clicks toggles different content, second toggles overlay
 */

(function ($, Drupal) {
  Drupal.behaviors.welcomeOverlay = {
    attach: function () {
      var cookieName = 'firstWelcome';
      cookieValue = 'returning';
      cookieDays = 60;

      /** Create Cookie Creation Function **/
      function createCookie(name, value, days) {
        if (days) {
          var date = new Date();
          date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
              expires = "; expires=" + date.toGMTString();
        }
        else {
          var expires = "";
        }
          document.cookie = name + "=" + value + expires + "; path=/";
      }

      /** Check for Specfic Cookie **/
      function readCookie(name) {
        var nameEQ = name + "=";
            ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') { c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) {
              return c.substring(nameEQ.length, c.length);
            }
          }
        }
        return null;
      }

    /** Sets value corresponding to cookie existance **/
      var visited = readCookie(cookieName);
          visited2 = document.cookie.search(cookieName);

      /** If Non-existant Create Cookie and Show Content **/
      if (visited === null || visited2 < 0) {
          // $(document).ready(function () {
          // Seconds Before Overlay Slides Over Content
          setTimeout(function () {
            overlay.slideToggle('800', 'linear', function () {
              appearFirst.fadeTo('800', 1, 'linear');
            });
          }, 1500);
          createCookie(cookieName, cookieValue, cookieDays);
      }
    }
  }
})(jQuery, Drupal);

welcome-overlay.module

function welcome_overlay_preprocess_page(&$variables) {
  /** Include the jquery.cookie plugin **/
 drupal_add_library('system', 'jquery.cookie');
 /** Attach jquery/css to module **/
  $path = drupal_get_path('module', 'welcome_overlay');
  drupal_add_css($path . '/welcome_overlay.css');
  drupal_add_js($path . '/welcome_overlay.js');
}

Instead of making a custom cookie, try using Drupal's cookie system.

Set:

user_cookie_save(array('key' => 'value'));

Get:

var = $_COOKIE['Drupal_visitor_key'];

I just realised this is in php, not javascript as you have used so I will expand.  I made my overlay by creating a new page with hook_menu and am using hook_init to check for cookie values, redirecting to my new page if required.


Unable to login as user in my drupal 6.x website while able to access without login I am having a strange problem with my drupal website where site is working and anybody is able to surf it properly however the moment I try to login using my admin or account it shows offline message given below. What could be the reason

+++++++++++++
Site off-line

The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.

If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider's database server is running. For more help, see the handbook, or contact your hosting provider.

As you can not login from in your site the only way to do something is from database end, if you have access to database try doing this to come out of this mess up:

Try to empty the sessions and the cache tables. Not DELETE! Empty them.
then see if you can login from http://www.yoursite.com/?q=user

Or look if your site is in maintenance mode if it is the follow instructions given here: https://www.drupal.org/node/276457

Hope above will work for you and you will get your site back to normal.
Good luck!


How to add custom attributes to a field? I would like to be able to add a handful of custom attributes to a filefield.  The attributes will be used by other modules to manage the uploaded files.

For example:
Admin creates a filefield and adds a "youtube" attribute, meaning that videos uploaded to this filefield should get transferred to youtube.

I see that the database table content_node_field (which contains a row for each defined field) has a general_settings column that stores serialized data.  I am assuming this is a good place to store my custom field attributes.

Question #1:
How to set/get custom attributes stored under the "general_settings" column?

Question #2:
How to customize the filefield widget so that when admin defines a particular filefield, she can also select values for these custom attributes.

(I am using Drupal 6.)

Thank you!

The database table "content_node_field_instance" has a "widget_settings" column which can be used to store field attributes.  Use hook_widget_settings_alter() to associate attributes with a field.  Admin will then be able to set attribute values from the cck UI.  For example, to associate a binary attribute "my_attribute" with every filefield:

function mymodule_widget_settings_alter(&$settings, $op, $widget) {

  // Apply to all FileFields
  $widget_types = _content_widget_types();
  $widget_type = isset($widget['widget_type']) ? $widget['widget_type'] : $widget['type'];
  if (!in_array('filefield', $widget_types[$widget_type]['field types'])) {
    return;
  }

  switch ($op) {
      case 'form':
        $settings['my_attribute'] = array(
          '#type' => 'checkbox',
          '#title' => t('my attribute'),
          '#options' => array(0 => t('Disabled'), 1 => t('Enabled')),
          '#default_value' => !empty($widget['my_attribute']),
        );

        break;
      case 'save':
        $settings[] = 'my_attribute';
        break;
  }
}

In this example, the filefield form will contain a checkbox labeled "my attribute".  Admin checks the box to set my_attribute to true, for the particular filefield.

To get the attribute value of a particular field:

$attribute_value = $field['widget']['my_attribute'];


Markup being stripped from form element title I need to add links to checkbox titles, I can see the link in the render array but when it renders the markup is stripped. How can I get the links to not be stripped?

I am doing this in a form alter, the checkboxes are added to the user registration form in the Drupal UI, i.e. they are form fields.

$tc_link = Link::fromTextAndUrl(new TranslatableMarkup('terms and conditions'), Url::fromRoute('<front>'))->toString();
$tc_link_label = t('You agree to the ') . $tc_link;
$form['field_terms_and_conditions']['#title'] = $tc_link_label;

The markup is like this:

        <input name="field_terms_and_conditions[agree_terms_conditions]" class="form-checkbox" id="edit-field-terms-and-conditions-agree-terms-conditions" type="checkbox" value="agree_terms_conditions" data-drupal-selector="edit-field-terms-and-conditions-agree-terms-conditions">

        You agree to the terms and conditions

But if I inspect it with kint the links are clearly there.

In Drupal, strings need to be passed through the t() function for translation. This function uses string replacement to sanitize text. When passing links, the HTML should be put in the string, and the URL passed as a variable prefixed with a colon:

$tc_link_label = t('You agree to the terms and conditions', [':url' => Url::fromRoute('<front>')->toString()]);
$form['field_terms_and_conditions']['#title'] = $tc_link_label;


Import site from HTML pages (currently static files in directories, not in a CMS) I've taken over a small website (link here, in case it helps) which is currently composed of largely static HTML files (with a few PHP includes thrown in to generate menus and footers, etc). I want to migrate it into Drupal, as I'm fairly familiar with this and it'll make the site more manageable. My question is: what's the best way to do this?

I've found plenty of modules to migrate sites from CMSes like WordPress, but none to import static files organised in directories. Some research turned up the Migrate and Feeds modules, but I'd like some guidance on whether to use something else, or whether to use these, and if so how. Should I write a perl script to pull out the content and titles and current paths or pages into a CSV of some format? Presumably others have done this, so it'd be interesting to see best practice, or examples...

Many thanks

I'm surprised that you didn't find Import HTML yet. Personally, I haven't used it since the Drupal 5 days, but just give it a try and see if it does what you need.


How do I minify inline CSS using Twig? Inside my html.html.twig template I've added a stylesheet inside the style elements using this.

{% include directory ~ '/css/base/style.css' %}

Is there a way that I can strip it for all whitespaces? Can I apply the CssOptimizer class to it in any way? Can I also strip the stylesheet for comments?

This is not the right way to integrate a .css file inside a twig file in drupal8. You should use the standard procedure as I mentioned below.

 {{ attach_library('bartik/messages') }}

SO now for minifying the .css  you can use the 3rd party site- https://cssminifier.com/

So the after minifying the .css file, crate the library

messages:
  css:
    theme:
      css/components/my-minify.css: {}

Then attach the library in the twig by using the below sysntax

{{ attach_library('your-theme-name/messages') }}

Hope this will help you. If any doubt please don't hesitate to mention.


Reindex Taxonomy URLs? I have a list of terms all with assigned URLs already.
When I change the term and the URL, it is not updating.

I feel like there's a cache or reindexing needed ?

Do you have change the taxonomy term name manually or the url alias?
If you only have change the name you must to check the field "Generate automatic URL alias" is checked to change the url automatically.

If is checked or you have change URL alias manually then clear cache in /admin/config/development/performance

I hope that helps.


Commerce 2: Is it 'really' necessary to setup product attributes before adding a simple product? Following along with the documentation at http://docs.drupalcommerce.org/v2/product/index.html#

Slightly puzzled by the following

  "Setup product attributes - Before creating products, you need to
  create some attributes... "

Is it really necessary to setup some product attributes? What about a simple product for which a the body field is all that is needed to describe the item?

Be interested to know whether there may be some other reason for why product attributes should be created or whether the documentation ought to be clarified?

If the products you are adding do not require different variations, there is no need to add attributes. Product attributes are meant to define unique properties of a variation of the same product.

An example would be a t-shirt where the color and the size are two different attributes. The shirt has the same print and model (eg. long sleeves), but any given combination of size and color can exist, each having a different price, photo, etc. and its own SKU.

The documentation lists the creation of attributes before the creation of products, so you can choose these attributes once you start adding products.


cck Nodereference for files I am trying to create a node that has a single file attachment (using CCK filefield), and be able to reference that file by other nodes (possibly more than one node).

The application is such that there's a "forms library" that will have various documents refer to forms.

I have looked at FileField Sources, but I'm not clear if I change a file in node A, if the attached file in node B will reflect that change.

Additionally, we're finding related nodes based on taxonomy terms (http://drupal.org/project/relevant_content), so it would be nice if I could refer to the node, but by clicking on the link to the node (via the node reference), the file opens.

I've looked at Custom Formatters (http://drupal.org/project/custom_formatters) and Formatters 4 Node Reference (http://drupal.org/project/formatters4nodereference) as suggested by Attaching existing server files to filefield, but I don't seem to "get" the two modules, and neither of them are flush with documentation.

Is there a module for this, or am I looking at writing something?

You don't want FileField Sources, you want to use a Node Reference field on the node you want to reference the file on, and you want to change the display of the node reference field with either a Custom Formatter (that you'd need to write yourself) or a standard FileField via the Formatters 4 Node Reference field module.

To change the display of the Node Reference you would want to goto the Display Fields page on your Content Type and select the new Formatter from the dropdown.

A brief demo of what you could potentially do for this sort of system can be seen at: http://www.youtube.com/watch?v=qBXoN25guic


How to render a static html from a drupal module I need to call a static html page and display the content of it when calling it from the module function , i tried to call from the form api but its just rendering the full markup ,please help

here is the try :

$items['mailusers/staticpage'] = array(
    'title' => t('My Static Page'),
    'page callback' => 'my_static_page',
    'access arguments' => array('access GASF admin menus'),
    'access callback' => TRUE,
  );

  return $items;

and the function

function my_static_page() {
     $form['html'] =  array(
    '#type' => 'markup',
    '#markup' => //'
My Heading
'
         file_get_contents(drupal_get_path('module', 'mailusers') .'/mailuser.tpl.php'),
  );
 return drupal_render($form);
}

The easiest way is to create a template file and use hook_theme

Put your html in a html-page.tpl.php in your module directory.
Use following code to render the html template in your page.

After adding the code make sure you clear your Drupal cache.

function my_static_page() {
  $html = theme('html_page');
  return $html;
}

/**
 * Implements hook_theme().
 */
function your_module_theme($existing, $type, $theme, $path) {
  return array(
    'html_page' => array(
      'template' => 'html-page',
    ),
  );
}


Hook_menu to Form with %node wildcard I have a content type 'school' and an entityform that's called 'contact'...

I would like the URL path for the contact form to be:

www.example.com/node/nid/contact

It's important that the node ID be passed in the link to the entityform in this format rather than:

www.mysite.com/eform/submit/contactform?some_custom_field=[nid]

so that people can share the contact form easily.

It's also important that the contact form be an entityform

Any pointers to set up my entityform url so that it reflects the NID of the content that linked to it?

I am trying to set up URL alias for the entityform but am having trouble setting up the NID as a wildcard.

  EDIT for my helper module I have...(we can ignore the entityform part of my question because I'll probably re-build the form) ... I am trying to get the letter generator to appear at /node/%node/lettergen but the %node wildcard isn't working ...

function lettergen_menu() {
$items = array();
$items['node/%node/lettergen'] = array(
'title' => 'Letter Generator',
'description' => 'Generate a Letter'
'load arguments' => array(1),
'page arguments' => array('lettergen_form', 1),
'access callback' => TRUE,
);
return $items;
}

  THIS WORKS

function lettergen_menu() {
$items['node/%node/lettergen'] = array(
'title' => 'Lettergen',
'description' => 'A form to mess around with.',
'page callback' => 'drupal_get_form',
'page arguments' => array('lettergen_form', 1),
'access callback' => TRUE,
);
return $items;
}

One of the option is:

create a entity reference field in 'school' content type to reference associated contact form.
write a helper module that adds a menu item node/%node/contact.
Make sure access_callback check for your content type and return false for other node type to avoid any perf issue.
In menu callback function, render the entity form to display.

Here is an example of "node/%node/something" pattern from token module.

/**
 * Implements hook_menu().
 */
function token_menu() {
  ...
  ...

  $items['node/%node/devel/token'] = array(
      'title' => 'Tokens',
      'page callback' => 'token_devel_token_object',
      'page arguments' => array('node', 1),
       // 'node' => token_devel_token_object function gets a string 'node' as argument 1
       // 1 => token_devel_token_object function gets a node object of node id given in url. for mode details refer https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_load/7.
      'access arguments' => array('access devel information'),
      'type' => MENU_LOCAL_TASK,
      'file' => 'token.pages.inc',
      'weight' => 5,
    );

// page callback definition
/**
 * Menu callback; prints the available tokens and values for an object.
 */
function token_devel_token_object($entity_type, $entity) {
...
...
}


Send email to all users that are tagged with the same tag a node is when created There is a lot of similar questions here but I am having a hard time wrapping my head around this.

I have a taxonomy term reference field called field_category. This field is available on user/*/edit and on node/add.

Category

1
2
3

What I would like to do is send an email when a node is created that has the same taxonomy term(s) that a user has specified in their profile.

I have tried to wrap my head around using the rules and view_rules module but every configuration I have tried fails.

Can anyone provide me with some direction? Thanks!

Drupal 7.65

Rules: 7.x-2.12

Views Rules 7.x-1.0

Edit

Using pinueve answer, here is where I am at. The actions/conditions section of his answer is still unclear to me. My holdup is trying to match his example in the actions section.

{ "rules_area_of_expertise" : {
    "LABEL" : "area of expertise",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "mail" ],
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_insert--answers_question" : { "bundle" : "answers_question" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_category" } },
            "DO" : []
          }
        ]
      }
    ]
  }
}

install: views-rules-module, and rules-conditional module. Add in views a rules-view (is a new display type added by rules-view-module) of type USERS, add your category-field, hide from display, add relationship to taxonomy-vocabulary, add field: term-ID and UID. Both fields in views middle column set your fields as type: INTEGER. If you want you can delete user-field_category from this view. If needed, filter users by role or whatever to shorthen your view results, and important: no-pager, display all rows.

Now in rules: react-on: new content of type: your-content-type, conditions: entity-has-field: node-created-content: your field_category, actions: fetch-entity-by-id: taxnomony-term: value: drill in node until you find node-term-ID.

Add your new view-rule (find link at bottom settings in actions), now you have term-ID from user & UID, inside view-loop and a conditional, add an if, data-comparision, your NODE-term-ID vs USER-term-id, if equal, fecth USER by ID, with your variable UID, and send email. Done.
Note: is possible that you will need to transform your NODE-term-ID as an integer.

Your rule will look like something like this:

EDIT: first install rules Version: 7.x-2.11, i can see that you do not see 'conditional label' in rules action. To avoid to update rules module, install disable-updates-module

FIRST action should be 'fetch entity bt ID: tanonomy term', select your new node, and drill until you find term-ID.

SECOND action: add your users-views-rule. all following actionts take place inside rules-view-loop.

THRID action: inside rules view, data compare: your variable term-id from rules-view-users with NODE-term-ID (first action), if values match (are equal) then fetch USER by ID with your variable value UID from rules-view, now you have user object avilable, do send email to that user, rules-view will compare next user, and so on. here is another img of how will look your rule, notice how actions are taking place inside rules-view-loop.

and here is an img where you can find how to add your rules-view, it says "Add a view loop" at the bootom of img.

And this is how you set your fields inside rules-view, this is located in middle colum of your view.


How to import Excel file to CCK nodes? Is there a way to import a Excel file into CCK nodes?

Each Excel file contains only a single sheet
First row of there sheet is header
Data are only strings, numbers, and decimal numbers
It's a daily task which will be performed by a user

You'll probably have to save your Excel file to CSV format to be able to import more easily. Two options:

Node Import: You can certainly import CSVs with this, and I've used it successfully for huge spreadsheets before -- it's powerful, helpful and quite easy.
Feeds: Much more complex to get going than Node Import, but Feeds can in theory do everything you want and much more. Can also update existing nodes.

Either of these will allow you to import CSV data (exported from your Excel document) to nodes and their CCK fields.


How should the content structure for a Comparison website look like? What is the "right way" to build a community-oriented comparison system in Drupal 7? My primary question is do I need to hand-roll the DB code for this or is there a way to do it with existing Drupal techniques? My secondary question is how would you structure this in Drupal?

The entities of my site are as follows.

User classes:

Administrators (me <=1)
Analysts (trusted community moderators <100)
Authenticated Users (untrusted community content creators <2000)
Anonymous site visitors can view all of the reviews (billions of people :)

Products:

product classes. (e.g. Cameras, Laptops, Mobile Phones, etc). There will be >500 product classes. Analysts can edit and manage product classes by adding product feature types, etc.
products (e.g. Nikon D7000, Canon EOS Rebel, etc) are an instance of a product class. Authenticated Users can add/edit products.
product features are the pre-defined set of features of a product class (e.g. Exposure Metering, Exposure Modes, White Balance, Max Shutter Speed, etc). These are administered by Analysts.
product feature types. Each product feature must be of a certain type like a star rating, text, price, number, url, etc.

My initial solution was to create a custom content-type for each product class, then use Drupal fields for the product features. My concern with this approach is that I don't know how to allow semi-trusted Analysts to create and manage their own product classes and product feature types without giving them administrator privileges. Also, I imagine having hundreds of product classes and so it feels weird to have a custom content-type for each * product class*.

I'm happy to do it the php-module way, or the pointy-clicky way. How would you approach this?

Your initial solution, having own content types, can also support that content editors can only edit their own content. Define an content type, setup user role for "Analysts", and set the appropriate user permissions for them.

Look at http://www.example.com/admin/people/permissions and http://www.example.com/admin/people/permissions/roles.

I'm assuming you have Drupal 7, but Drupal 6 has more or less the same functionality.


Strip HTML tags from autocomplete field I have altered #autocomplate_path for node queue autocomplete node suggestions to show image field along with title and nid, which is working fine. The code which is returns the image with title and nid is.

$matches[$node->nid] = theme('image_style', array('style_name' => $get_image_field_style, 'path' => $image_field_uri, 'attributes' => array('class' => array('nodequeue-runsheets-images'))))
              . check_plain($node->title)
              . " [nid: $id]";

This is how I see the results with the above working code: -

The problem comes when drupal autocomplete pull the selected suggestions and populate it to autocomplete textfield. I see the html tags as . How can I override this to show only node title and mid.

The problem:

The solution in following post worked for me
http://www.derreklemar.net/tutorial/drupal-autocomplete-overriding-default-select-event-behavior


Drupal Commerce Barcode Scanner module I've installed Barcode module and Commerce Barcode Scanner module. The first is for generete barcodes to products. The second is supposed to read barcode labels. I couldn't test Commerce Barcode Scanner yet because I don't have a Barcode Scanner by now.

But I've been searched how Commerce Barcode Scanner works and I don't find anything.

Do I have to position cursor in a specific field from front-end or back-end of my site or is really only necessary to stay in some page of my site to Commerce Barcode scanner redirect to the Product Display (as that is the behavior setted up by default in rules)?

You know that only 17 sites currently report using this module? And that last revision is reported to be from 2013-Oct-27? So it is old thing, and hardly used. I advise caution.

This bugreport suggest that all you need to do is to have focus anywhere on your page, and it will work... except when you hit the bug itself.


How to have separate private comments for nodes apart from the general comments? I have a specific requirement.
Apart from the general comments which everyone can view or post for my custom node I also require private comments thread which will be shared only by the node created user and selected few.
Using the same comments form will not work as it will be viewed by all.
Any inputs on achieving this?

Thanks.

For Drupal 7 see the Reply module. It lets you create your own set of "comments" attached to any Entities you want.

With some custom code you could limit the field to a specific user role or set of users. Be sure to read the README in the module.


Drupal queue / update module I have a Drupal 7 site and the queue table has over 4K records. They are primarily for the "update_fetch_tasks" queue. Is the queue table by nature a temporary place holder?

I would like to clean it out and see if it fixes some issues that I am experiencing with the update module. I've done some digging on the queue module and from what I can tell is that proper usage is to claim the queue items and when you are done with them you should delete them. So it seems odd that a core module is leaving records in the queue.

Is there any harm in removing records from the queue?

That table is used by the BatchQueue class; on the top of the page I linked there is the following note:

  Stale items from failed batches are cleaned from the {queue} table on cron using the 'created' date.

For some reason, in your case they are not being deleted during cron tasks; probably cron tasks are not enabled in your site, and the setting that allows cron tasks to be executed through JavaScript is not selected.
In any case, once batch operations are completed (which means also when the updates have been completed), it is safe to delete those database rows.


Why would $user->sid be undefined? I added some debugging statements (using dd()) which include a timestamp and $user->sid (after declaring $user as a global).  I tested it, of course, and everything worked great for me. Then a user reported getting some notices which said "Undefined property: stdClass::$sid ..."

I added a conditional to test to see if $user->sid is set before writing out the value, but I didn't think that it was possible for it to not be set!  I did some quick Google and drupal.stackexchange.com searches, but couldn't find any info on how this might be possible.

Anybody have any insight here?

TIA,
Lee

If you are not logged in the property will be undefined. This is all I've got for the anonymous user

object(stdClass)#7 (4) {
  ["uid"]=>
  int(0)
  ["hostname"]=>
  string(9) "XXX.XXX.XXX.XXX"
  ["roles"]=>
  array(1) {
    [1]=>
    string(14) "anonymous user"
  }
  ["cache"]=>
  int(0)
}


passing page arguments to drupal 8 from controller to form controller This is my code in routing.yml file

test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'

I need to get the value of node in the form controller buildForm function.

How can I access that? Any help?

Update the .routing.yml file like so:

test.check-test:
  path: 'node/{node}/test'
  defaults:
    _form: '\Drupal\test\Form\Test'
    _title: 'Test'
  requirements:
    _permission: 'access test'
    node: \d+
  options:
    _node_operation_route: TRUE

Then use it in your form controller the following way:

namespace Drupal\test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;

class Test extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $form['placeholder'] = [
      '#markup' => t('This is the form for @node_title.', [
        '@node_title' => $node->getTitle(),
      ]),
    ];

    return $form;
  }
}


Page redirect in custom WebformHandlerBase I have written a custom WebformHandlerBase and attached it to the Mulitpage webform. With this I'm able to get the values into the custom handler as soon as user clicks on Next Page> button

class MyFormHandler extends WebformHandlerBase {
     public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

         $form_id = 'webform_submission_' . $webform_submission->getWebform()->id() . '_form';

         if($form_id == 'webform_submission_registration_content_form') {
            $values = $webform_submission->getData();
            /* custom code to calculate the score based on the values */
             $eligible_to_participate = 1;
             if ($score >= x && $score <= y) {
                  $eligible_to_participate = 1;
              }
             else
             {
                 $eligible_to_participate = 0;
             }
             if($eligible_to_participate == 0) {
                  // This user is not eligible so redirect to 'finish page'
                  /* The below code is not working
                   * how-ever the same code is working in hook_form_FORM_ID_alter()
                   */
                  $url = Url::fromRoute('entity.node.canonical', ['node' => 78]);
                  $response = new RedirectResponse($url->toString());
                  $response->send();
              }
          }
      }
 }

Based on the user selected values I need to redirect the user to a different page and the code for doing the same is as follows

 use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;

 $url = Url::fromRoute('entity.node.canonical', ['node' => 78]);
 $response = new RedirectResponse($url->toString());
 $response->send();

Now the problem is, this code is not working in custom handler function. If I write the same code in hook_form_FORM_ID_alter() it is working fine.

Any idea where am I doing wrong? Any help much appreciated.

<?php
namespace Drupal\sa_webform\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "my_webform_handler",
 *   label = @Translation("My webform handler"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Calculate the score with webform
 *                                                     submissions"),
 *   cardinality =
 *       \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results =
 *    \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */

 class MyWebformHandler extends WebformHandlerBase {
 /**
  * {@inheritdoc}
  */
    public function submitForm(array &$form, FormStateInterface $form_state,
                           WebformSubmissionInterface $webform_submission) {

       $form_id = 'webform_submission_' . $webform_submission->getWebform()-
               >id() . '_form';
       if($form_id == 'webform_submission_xxx_form') {
         $values = $webform_submission->getData();
         /* Take the action based on the Webform submission values */
       }
    }

    public function confirmForm(array &$form, FormStateInterface
          $form_state, WebformSubmissionInterface $webform_submission) {
       $form_id = 'webform_submission_' . $webform_submission->getWebform()-
                                                  >id() . '_form';
       if($form_id == 'webform_submission_xxx_form')
       {
          if(based_on_some_condition) {
          /* Here 12 is the node id where i wanted to redirect to */
          $form_state->setRedirect('entity.node.canonical',['node' => 12]);
       }
    }
}
?>

For more examples refer webform modules src code located at webform\src\Plugin\WebformHandler

BrokenWebformHandler.php

DebugWebformHandler.php

EmailWebformHandler.php

RemotePostWebformHandler.php


View theme override in drupal 8 I am new to drupal 8 and i need to override a views template. So, for that I have enabled theme debug in services.yml to view the twig template suggestion name.

This is my view theme debug.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_unformatted__test_content_view' -->
<!-- FILE NAME SUGGESTIONS:
   x views-view-unformatted--test-content-view.html.twig
   x views-view-unformatted--test-content-view.html.twig
   * views-view-unformatted.html.twig
-->

Then, I created the file in templates of drupal8 theme and the theme file calls. I used themename_views_view_unformatted__test_content_view() function to override in themename.theme file but the function doesn't called.

Is there anyway to override the variables coming to the twig template. Can anyone give me suggestion to override the views template.

Thanks in advance.

In your case 'views_view_unformatted__test_content_view' is the theme hook in the render array. In Drupal 8 that will make it possible to use following preprocess functions to modify the variables before they get to the template:

themename_preprocess_views_view_unformatted__test_content_view()
themename_preprocess_views_view_unformatted()

There is more information about preprocess functions available here.


How to combine four text fields into one column in a view? I have four text fields in my Content Type:

First Name
Middle Name
Last/Business Name (required)
Generation

I want to combine these into one column in my view. I want the display format to be: LastName, FirstName MiddleName Generation

So only the last name is followed by a comma. The first name and middle name and generation only have spaces between them. I go to the Drupal view table settings and set the "Column" for all four fields to "Last/Business Name." But here's where I'm stuck: I know that there is a "Separator" field, but if I set it to a comma the format will be LastName, FirstName, MiddleName, Generation and that's not what I want.

TL;DR: Add the four fields, hide them from the view. Add a custom text field, use it to custom-render the earlier four.

What you need to do is add the four fields into your view. For each, click and check the Exclude From View setting. Then add a fifth field, a Custom Text field, and arrange it so that it comes after the four fields earlier. Click on it to edit, and configure it to output the fields earlier using token replacements.


Entity form submission sending email I'm working on entity form using the module "eform" in D8.

I would like it to send email when the user submits a form. It was done using some other modules rules and entity rules, but since "entity rules" is not released yet in D8, I couldn't find a way to send submission email.
Is there any module to make it possible or should I create a custom module to do that?

I've asked the question multiple times. It appears that we need to wait for Rules. For the time-being, I'm using the built-in drupal contact form + contact_storage module for form. It's not the best, but it works.


How do I pass multiple block configurations to a behavior? I am trying to create a Drupal 8 module that implements a Curator IO widget, so I created a block plugin with its own custom configuration.

public function blockForm($form, FormStateInterface $form_state) {
  $form['curator_io_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('Curator IO Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['curator_io_settings']['feed_id'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Enter your unique Feed Id'),
    '#default_value' => $this->configuration['feed_id'],
    '#maxlength' => 256,
    '#size' => 64,
    '#description' => t('Set your unique feed id found at curator io'),
  ];

  return $form;
}

I attached my library from the build method and passed a variable so I can work with it in jQuery.

public function build() {
  $build = [
    '#theme' => 'curatorio_io',
    '#attached' => [
      'library' => [
        'curatorio/curatorio_assets',
      ],
      'drupalSettings' => [
        'curatorio' => [
          'feed_id' => $this->configuration['feed_id'],
        ]
      ]
    ],
  ];

  return $build;
}

I am getting this variable value in JavaScript using the following code.

(function ($, Drupal, drupalSettings) {
  'use strict';
  Drupal.behaviors.curatorio = {
    attach: function (context, settings) {
      console.log(drupalSettings.curatorio);
    }
  }
};

It is working fine for one instance of the block.

When I add 2 or more instances of this block, only the first block works. I can understand that no matter how many instance I create for this block, the JavaScript will always get included once, so how do I pass multiple values for feed_id to the JavaScript behavior?

So as Leigh suggested I send this data values into a twig file

  public function build() {

    $build = [
      '#theme' => 'curatorio_io',
      '#id' => uniqid(),
      '#feed_id' => $this->configuration['feed_id'],
      '#widget_type' => $this->configuration['widget_type'],
      '#attached' => [
        'library' => [
          'curatorio/curatorio_assets',
        ],
      ],
    ];

    return $build;
  }

Now in my twig file, I put those values into data attributes

<div class ="curator-feed"  id = "{{ id }}" data-feed-id = "{{ feed_id }}"  data-widget-type = "{{ widget_type }}" >

</div>

and in js I attached my JS logic to get attribute value and attach Plugin into it.


How to find the viewid and view-display-id? I'm trying to customize a view displayed in the homepage. Specifically, I'm trying to build slideshow with Bootstrap Carousel.

I've checked this page, but I don't understand how to find viewid or view-display-id. Instead of the viewid I've tried to use the view name, but it doesn't seem to work.
Anyhow, I've created a new folder inside the templates folder called views, in which I've created a new file with the following name: views-view-fields--homepage-carousel--block.html.twig

Here is the code:

    {% if ((title is not empty) or (description is not empty)) %}

        {% if (title is not empty) %}

 {{ title }}

        {% endif %}

        {% if (description is not empty) %}
          {{ description }}
        {% endif %}

    {% endif %}

Which naming should I use to override a view displayed only in the homepage?
Thank you!

UPDATE

I've managed to correct the information thanks to user No Sssweat. Now, I'm able to customize my view. Here is the file name: views-view--homepage-carousel--block-1.html.twig, where homepage-carousel is the viewid and block-1 is the view-display-id

Anyhow, I've created a new folder inside the theme root called views

This might not work if it's not inside the /templates folder. You should create a /templates folder if there isn't one already and then create a /views folder inside there.

So should be mytheme/templates/views and then you put all your Views' template files here.

  I don't understand how to find viewid or view-display-id

You can find the view name at the top left. Although if your view name were to have an empty space you would have to add a dash. Ex: If it was named "Front Page" then the view-id would be front-page

You can find the Display ID under Advanced, machine name.

Another way would be to right mouse click and inspect element with your browser


Horizontal form elements I have described the form, but every element there is located under the previous one. I need to describe the form where all elements will be placed horizontally but not vertically.
This is my form:

function contact_register_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Sign up to be notified when your community launches:'),
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add me',
  );

  return $form;
}

You can use code similar to the following one, used by the Node module in node_filter_form().

  // Build the 'Update options' form.
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
    '#access' => $admin_access,
  );

  // ...

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'approve',
  );

The key is the line settings the "#attributes" attribute to "container-inline."

That code is for Drupal 7; the equivalent code for Drupal 6 starts with the following code:

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

Supposing you are using Drupal 6, then your code should be changed to something similar to the following one:

function contact_register_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Sign up to be notified when your community launches:'),
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#prefix' => '
',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Add me',
    '#suffix' => '
',
  );

  return $form;
}

I didn't put the description inline, as it would not be correctly rendered because it is using a "item" form field. I also find that inlining the description would cause the form to take too much space. (Imagine what would happen if the inlined description would be longer, and placed in a single line.)

The CSS styles that Drupal 7 adds to container-inline elements are the following.

/**
 * Inline items.
 */
.container-inline div,
.container-inline label {
  display: inline;
}
/* Fieldset contents always need to be rendered as block. */
.container-inline .fieldset-wrapper {
  display: block;
}

They are added from system.base.css.


Flat Shipping price per product using Drupal Commerce I've been beating my head against a wall trying to configure shipping in Drupal Commerce for a week now and so here I am! I have a Select or Other field in the product entity with a couple of choices:

Free Shipping
Call for Details
Other (and the admin enters a flat price)

Again, this is entered on a per product basis, on the Commerce Product entity (not the node). My question is how do I update the shipping price based on this value? It should work as follows:

Item 1 (shipping: $1.00)
Item 2 (shipping: $4.00)
Item 3 (shipping: Free)
Item 4 (shipping: Call for Details)
Item 5 (shipping: $1.00)
Total Shipping: $6.00

Perhaps I'm doing this wrong. Any direction would be awesome. Thanks!

This is the final working code:

class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      if ($line_item_wrapper->commerce_product->field_shipping_price_other->value() > 1) {
          $price += ($line_item_wrapper->commerce_product->field_shipping_price_other->value()*100)*$line_item_wrapper->quantity->value();
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom Shipping label'),
      'quantity' => 1,
    ));
  }
}

If you are using commerce shipping 1.x, you should do something like this:

Disclaimer, this is written by memory.

This is based on two fields on the product,

field_shipping_type containing the shipping type
field_flat_rate containing the actual rate for the product.

Create a custom module and add a folder for the shipping plugin, fx plugins/quotes/custom_shipping
Create the custom_shipping.inc with the plugin definition.

<?php

$plugin = array(
  'title' => t('Custom shipping'),
  'description' => t('Descriptive text.'),
  'handler' => array(
    'class' => 'CustomShipping',
    'parent' => 'quote_base'
  ),
  'price_component' => array(
   'title' => t('Shipping'),
   'display_title' => t('Shipping'),
   'weight' => -40,
  ),
);

Create the actual shipping logic in the CustomShipping.class.php file in the same dir. All you need is something like this:

class CustomShipping extends CommerceShippingQuote {
  public function calculate_quote($currency_code, $form_values = array(), $order = NULL, $pane_form = NULL, $pane_values = NULL) {
    $order = $order ? $order : $this->order;
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $price = 0;
    // Loop through the products, and add costs.
    foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
      switch ($line_item_wrapper->commerce_product->field_shipping_type->value()) {
        case 'free':
          break;
        case 'flat_rate':
          $price += $line_item_wrapper->commerce_product->field_flat_rate->amount->value();
          break;
        case 'call_for_details':
          // Call for details
          break;
      }
    }
    return array(array(
      'amount' => $price,
      'currency_code' => $currency_code,
      'label' => t('Custom shipping method line item label'),
      'quantity' => 1,
    ));
  }
}


Unable to access Admin panel of Drupal site at Localhost, migrated from server There is one my online website in Drupal. I did a Setup on Localhost for Testing Purpose. But unable to get it working correctly.

Using WAMP
Used Migrate tool.

I tried:

Deleted .htaccess file.
Base URL set.
Tried to access all possible Admin URL, sitename.com/admin .
Clean URL disabled on localhost.

Problem:

All pages working fine that means FRONT END IS FINE. But while accessing BACKEND for user or admin is just not working. It says PAGE NOT FOUND.
When I use admin URL as following:
sitename.com/?q=admin  = It redirects to https://localhost/sitename/?q=toboggan/denied&destination=admin

I'm not sure how it is adding https. Page says: unable to connect
If I use sitename.com/admin it says: "Page not found".

Please suggest the solution.

This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that browser you are able to login, then it's probably a cookie problem (in your original browser).

If http redirects to https you might have a module that does this or it might be a rule in .htaccess see if you can comment out the rule in htaccess or disable any relevant module with drush dis MODULENAME.

If none of these suggestions help, then re-edit your question by adding more details about which modifications to your '.htaccess file, httpd.conf, etc' you already tried (and didn't work).


How to style a programmatically created page with a template? I'm struggling with understanding theming pages with templates. I'm stuck with creating a new template for a programmatically created page. I have a module that shows a download page for a file. The page is basically a form where user can click Submit and get their file downloaded. I construct the whole form programmatically in a page callback. But what if I want to style it with a template? I fail to see how to do it. Here is my (simplified) code:

// Implements hook_menu()
function mymodule_menu()
{
    $items = array();
    $items['file/%mymodule_mycustomfile/download'] = array(
    'page callback' => '_mymodule_filedownload',
    'title' => 'Page Title',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    );
    return $items;
}

// Implements autoloader %mymodule_mycustomfile
function mymodule_mycustomfile_load($fid)
{
    return ($fid > 0) ? (object)array('fid' => $fid) : FALSE;
}

// Page callback function
function _mymodule_filedownload($mycustomfile)
{
    return drupal_get_form('_mymodule_filedownload_form', $mycustomfile);
}

// Creates page form
function _mymodule_filedownload_form($form, &$form_state, $mycustomfile)
{
    $form['label'] = array('#type' => 'item', '#markup' => 'File ID');
    $form['fid'] = array('#type' => 'item', '#markup' => $mycustomfile->fid);
    $form['submit'] = array('#type' => 'submit', '#value' => 'Download');
    return $form;
}

// Submit button click handler
function _mymodule_filedownload_form_submit($form, &$form_state)
{
    die('On Submit');
}

You can see that I construct my form fully in _mymodule_filedownload_form(). But I want to have something like file-download.tpl.php for it and put things like Label there. I fail to see how to do it. My problems are:

1) I stumbled upon theme_hook_suggestions and by default Drupal suggests the following template names: page__file, page__file__%, page__file__1, page__file__download. When I created page--file--download.tpl.php and went to /file/1/download, my screen went blank. I do not know how to output my form in this file and I'm afraid I do not even want to restyle the whole page. I only need to style the page content (the form itself) and leave the page alone. Why can't I have file--download.tpl.php if I have node.tpl.php and comment.tpl.php?

2) As a side note, when you execute template_preprocess_page(&$variables) on node pages, you can see the defined $variables['node'] that contains full node object. How is it done? Can I possibly have something like $variables['mycustomfile'] on my file download pages?

In this case your page is a form, so you need to create a form template this way:

Implement hook_form_alter() in a module or template.php and set the form's #theme property:

function _mymodule_filedownload_form($form, &$form_state, $mycustomfile)
{
    ...
    $form['#theme'] = array('mymodule_filedownload_form');
    ...

}

Then implement new theme:

/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path){
  $path = drupal_get_path('module', 'mymodule');
  return array(
    'mymodule_filedownload_form' => array(
      'render element' => 'form',
      'template' => 'form--mymodule_filedownload_form',
      'path' => $path . '/templates',
    ),
  );
}

And then add form--mymodule_filedownload_form.php template with follow code to render complete form (you can render it also by components):

<?php print drupal_render_children($form) ?>


Redirect HTTPS to HTTP for a bilingual site I set up a bilingual site pointing to 2 different domains for a client. My client then started receiving comments about unusual behavior, and digging a little I found out they (unknowingly) signed up for an HTTPS account while being on shared hosting and not having an SSL certificate.

I understand I can revert this by going to settings.php and force HTTP writing:

$base_url = 'http://example.com';

My question is if this is the correct way to handle this and I don't need to change anything else (like .htaccess); also, I have a different domain for a Spanish version of the site, could this domain be affected by pointing $base_url to the English domain? should I add both?

I would do the https to http redirect inside of .htaccess. Setting the base_url in settings.php will only fix it after the user clicks on a link. The landing page will still be https. I would use something like this in your .htaccess file:

RewriteCond %{HTTP_X_FORWARDED_PROTO} ^https$ [or]
RewriteCond %{HTTPS} ^on$
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]