Connection timed out and lock_may_be_available() on working site I'm hoping someone can point me to a fix. My drupal 7 app was running fine locally this a.m. while I was testing a way to insert a row using mysql tools for a non-Drupal function. My environment is Apache running virtual host on php 5.4.34 on a Ubuntu VM.

After not getting satisfaction using the mysql functions, I started a simple PDO function using Drupal's database settings from the settings.php file. I was able to insert a row successfully but when I returned to the local site I got this error after a long time:

drupal_log_error(Array ([%type] => PDOException,[!message] => SQLSTATE[HY000] [2002] Connection timed out,[%function] => lock_may_be_available(),[%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc,[%line] => 167, etc

[%type] => PDOException
    [!message] => SQLSTATE[HY000] [2002] Connection timed out
    [%function] => lock_may_be_available()
    [%file] => /media/psf/Home/apps/habitatnashville/includes/lock.inc
    [%line] => 167
    [severity_level] => 3

I've looked here and on Drupal's site. Because it's a connection error the likely suspects are that I've munged the credentials somehow.

When something like this happened months ago, I did a service mysql restart, did that again a few minutes ago, rebooted the ubuntu VM and rebooted entire computer to shake that lock.

I've removed that test file with the PDO just in case. Here's the output of my drush status:

Drupal version                  :  7.27
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database username               :  admin
 Database name                   :  my_db
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :  Anonymous
 Default theme                   :  My_theme
 Administration theme            :  rubik
 PHP executable                  :  /home/sam/.phpbrew/php/php-5.4.34/bin/php
 PHP configuration               :  /home/sam/.phpbrew/php/php-5.4.34/etc/php.i
                                    ni
 PHP OS                          :  Linux
 Drush version                   :  6.2.0

My database is running as "service mysql status" => mysql: start/running, process 1291.
What else could be affecting this?

There could be multiple reasons/thoughts:

Are you sure mysql is running?
Has your site got just too big for the resources allocated to mysql in the configuration?
Did you manually "emptied" all of the cache files via the database?
Low file system space on the database server
If you just moved the site to the other server and mysql is not set up to accept enough connections.
The user you are connecting with has SELECT permissions on mysql but not DELETE or UPDATE etc.
The host settings in sites/default/settings.php doesn't matche the one from the User in the database
MySQL 5.7 does not allow root user to access a database from client app. After switching to a normal user, it solves.
Sometimes tuning xampp like on php.ini (memory_limit=256M) and my.ini (max_allowed_packet = 32M) and disable devel by drush (drush dis -y devel) also works.
...


How to change the "Check boxes/radio buttons" fields weight? I have created a radio buttons field in entity form. I just want to move yes label above and No label below. How to achieve that i am not getting any option.

In field edit settings page, you can organize your options in "Allowed values list" section.


Render block via twig template I have programmatically created a block. In my module folder I added all suggested templates in a templates folder(mymodule/templates/suggestedtemplatename.html.twig).

However the block is not using any of them!
I have enabled the theme debugger which gives me all the suggestions and describes which part of the page is produced from which template. I can see only block.html.twig producing html.
I tried drush cr and uninstalling/installing the module

I was missing the implementation of hook_theme. In order to use the template you need to declare it there.
FX

/**
 * Implements hook_theme().
*/
function mymodule_theme() {
  return array(
    'block__newsletter' => array(
      'render element' => 'elements',
    ),
  );
}

You should then have a templates/block--newsletter.html.twig.


Prepopulate node-add form with search terms? I would like users to be able to create band profiles (which will be a content type), and then those profiles will be associated with their user accounts via Entity Reference. However, I only want one profile per band, so I don't want each member of the band to be able to create a page for the band (but I'd like to have all members of the band be able to be related to the band page via Entity Reference).

So, before a user is able to create a band profile, I want them to search current bands on the site (either via Views or Search API, not sure which yet...probably whichever method allows me to solve the issue below). If the band does exist, then the user will select it and a reference will be created. However, if a profile for the band does not yet exist, I want the user to be presented with a link to the node add page to create a band.

This is where my question comes in. When a user creates a new band, how can I populate the node-add form with the terms that they searched for to begin with? So if a user searches for a band from "San Diego, CA" called "The Band", how can I populate the creation form with "San Diego, CA" and "The Band" without him having to enter the information again on his own?

I don't know of a module that solves exactly the problem you're describing out of the box, but you might be able to come close with Entity Reference View Widget and/or Node Reference URL Widget.


Organic Group Permission I am using drupal 7, how to give permissions for the anonymous user to the view the fields of created from the OG module. The values doesn't show for the anonymous user. In the people permission page, there is no option to view the field name permission. There is only a permissions of creating, editing and deleting the node. Please help me resolve this problem.

Thanks.

It sounds like you have "Strict node access permissions" enabled.

On the OG settings page (/admin/config/group/settings), make sure "Strict node access permissions" is unchecked.

This disables the OG permissions and lets you use the standard Drupal permissions alone.


How To: Change Block Text Color I need to change the text color of a block on my main page.  The existing theme uses blue text on a light blue background which makes it somewhat difficult to read.  I used Firebug to find the div ID and created a local.css file per this post.

#block-views-team-events-calendar-block-2 .content
{
color: #ffffff;
}

I changed the color to white, but, I don't see any change on the page.  I tried clearing the cache, but, I got the same results.  How can I change the text color for one single block on my main page?

There can be multiple reasons why your styles are not applied to the page elements:

CSS aggregation is enabled. Disable aggregation and see if your custom CSS works. If it doesn't, you probably forgot to include the file in your theme - move to the next option.
CSS stylesheet is not added to the theme via THEMENAME.info file or other methods. Placement of the CSS file in your theme's css folder does not make it load while Drupal pages are loading.
wrong selector used
styles are overridden by a selector with higher specificity  ...etc.

To add CSS stylesheet to the Drupal theme, add the following to the current theme's .info file and clear cache:

stylesheets[all][] = css/local.css

You can also add CSS files to your theme via drupal_add_css function that you can use in hook_preprocess_page().

Hope this helps.


print value of email field from a node I am using the below code to get the value of email. It works fine if the field type is "Text". But the field type used is "Email"

<?php
  $node=node_load(14);
  print $node->field_contact_email[$node->language][0]['value'];
?>

Please help.

As it's an Email field, you need to query the array for email not value:

$node = node_load(14);
print $node->field_contact_email[$node->language][0]['email'];

// Outputs:
youremail@example.com

If you're intending on rendering the email address on a page, you should look into using field_view_value, which will give you a string of HTML markup for a field value. The benefit of this, is that it will use the rendering function for what ever field type you supply it with.

$node = node_load(14);
$email = field_get_items('node', $node, 'field_contact_email');
$output = field_view_value('node', $node, 'field_contact_email', $email[0]);
print $output['#markup'];

// Outputs:
youremail@example.com


Twig/Drupal caching and dynamic variables I have a template with a list of recent articles and an article itself. I want to check in the list of recent articles if the article currently viewed is there and if yes add a class to the div. This works all fine on a development environment but as soon as I turn on caching it goes haywire. The class is stuck on one item instead of switching to the active one.

How can I solve this?

My template:

<a class="news-block {{ node.id == current_id ? 'news-block--active' : '' }}" href="{{ url }}">
    ...
</a>

My preprocess:

function theme_preprocess_article(array &$variables) {
    $currentNode = \Drupal::routeMatch()->getParameter('node');
    $variables['current_id'] = $currentNode->get('nid')->getValue()[0]['value'];
}

My understanding is that this doesn't vary on the same URL, so both page_cache and dynamic_page_cache should be fine. However, each node is also cached on its own, a and that's your problem here.

As 4k4 said in the comment, you should be able to vary the cache with this: $variables['#cache']['contexts'][] = 'url'.

That's rather problematic however, because it means that every node needs to be cached differently on every page, which results in a huge amount of variations that fill up your cache tables.

You could define your own cache context for whether you are on the node page of a given node. Core actually should provide a cache context for that, since it has a similar problem when you'd e.g. use the default view mode somewhere else than on the node/N page. But it doesn't, there's an open issue for that.

As mentioned, the easiest fix is probably to use JS for this.


How to use Services Basic Authentication? How to use Services Basic Authentication module?

I want to add http basic auth for my service. I have installed it and enabled it on my end point configuration. I got this "HTTP basic authentication Services_basic_auth has no settings available" in my end point configuration. where is the setting page?

The module authenticates a web service call against drupal accounts.

Enable the module
Setup a drupal user
Make the web service call with the credentials of the user.

Note that with basic auth, the credential can be intercepted if SSL isn't used.

The module uses the standard PHP authentication headers and submits the standard drupal login form, without checking for any specific roles or permissions. So any drupal user will work.

Make a test web-service call with curl or wget to test it. There are also instructions in how to call with PHP in the call with curl stackoverflow answer.


PCI compatible recipe? I've struggled to find a really straight answer that makes me super comfortable to this question after searching SE, PCI basics, drupal.org, AWS resources, and reading the Drupal PCI Compliance White Paper.

I think I am just looking for some confirmation or denial from folks who have set up eCommerce environments before. Perhaps this is because I am overthinking it (I really don't want to expose a small business to unnecessary liability), and perhaps because environments are all different so it's difficult to say.

I'd like to be sure to create a PCI compatible environment using Drupal Commerce with an onsite payment gateway (Authorize.net). In our MOU it will be up to the site owner to ultimately write down their business processes and take the SAQ (recommended, as they should qualify for level 4 from Visa/Mastercard) to say they are PCI compliant, but since I am building the site out I would like to make sure they don't have any trouble with that piece of it.

As long as we are...

Hosted in a PCI compliant environment (AWS EC2 in this example)
Have firewall properly configured
Serving all relevant (but ideally all) pages over SSL
Use good passwords, no users are shared
All security updates are made for Drupal and modules promptly

Is that a recipe for a PCI compatible environment? Have I forgotten any pieces?

My second but related question is - Does using Drupal Commerce with Authorize.net (onsite processing) mean the business should use:

SAQ-A (Card-not-present merchants: all payment processing functions fully outsourced, no electronic cardholder data storage)

or

SAQ-EP (E-commerce merchants re-directing to a third-party, PCI compliant service provider for payment processing, no electronic cardholder data storage)

I know Drupal Commerce provides the 'no cardholder data storage' by design, but i'm very unclear on the definition difference between 'all payment processing functions fully outsourced' and 'merchants re-directing to a third-party compliant service provider for processing'.

Thanks for your thoughts!

Disclaimer: Keep in mind I am neither a lawyer nor a PCI QSA.

After doing more research - I'm convinced that using Drupal Commerce with authorize.net AIM (which is the method used by the authorize module that comes with the commerce kickstart profile) should land you directly into SAQ-D in almost all cases (do not pass go, do not collect $200).

This means you need all the things above plus much more management and policy on your end (or your clients end). It wouldn't be feasible for a small company without a huge budget for a custom project.

Here is the best/most robust explanation i've found of which SAQ to use in one place.

To reduce the scope of the CDE using Authorize.net, one would need to integrate with SIM (offsite form generation) to use SAQ-A, or DPM (direct post) to use SAQ-EP. This assumes you can say yes to the entire list of qualifications i.e. only take payment online, no POS etc. The latter option offers more customization but is more work.

This module looks like it will allow you to do so with Drupal Commerce, but I have done no testing or verification.

Looks like smaller budget clients should be briefed on PCI (always) and plan to use the off-site methods such as Authorize.net SIM or Paypal WPS where the form is generated by the CC processing organization's servers, and never touches your environment. This way your environment should be out of scope with proper configuration.

Here is a (albeit pretty old) thread from authorize.net development forum that has some general and scalable config insights I found very useful.

Here is another (1 year old) white paper that sets forth a framework for PCI compliance on AWS in general. Some of these pieces are not applicable to just a Drupal Commerce server, but still interesting and good.

Any more thoughts still welcome.


Rules Interface unresponsive and odd I am trying to set up a Rule to check if a user has added one of several states to an address field in a Profile2 profile. So I thought I'd do a Data Comparison.

I created a new rule called "Profile Save"
Added an Event from the drop down menu: "After saving a new profile"
Added "Entity has field"

Parameter: Entity:[profile2], Field:field_address
Added AND and Add Condition,
chose "Data comparison"

But the Data Comparison form is all wonky. The drop down has div tags in it. The "Data Selectors" isn't active.

Do I have to already know what the Data selector should be? Or should it be available in the drop down?

(See images)

Any idea what I'm doing wrong? Is this a known issue with Data Comparison.

That data selection interface often has jQuery Update-related issues; for the most part those should be solved by using the dev version (at the time of this answer) of jQuery Update and the current stable of Rules (7.x-2.7) as recommended by https://www.drupal.org/node/1810656#comment-9298435. That issue also has a good history of these problems.

Another issue appears to describe your exact issue and has a patch. It sounds like that resolved the problem, so future visitors might try that as well after seeing if updating jQuery Update doesn't work.


What should I do to use a more recent jQuery version? I am trying to use this jQuery Bubble script plugin with my Drupal 7 site. The plugin requires Jquery 1.6.2 (Drupal 7 only comes with 1.4.4).

There are some solutions on the net but none seem to work:

jQuery Update: It only updates jQuery to 1.5. There is a sandbox version that will update it to jQuery 1.8, but its too complicated to use.
jQuery Multi: I have installed 1.6.2 using this module; however, my site still loads the default jQuery 1.4.4. Version 1.6.2 does not seem to load.
Using Newer Versions of jQuery: This is a technique for loading multiple jQuery in Drupal 6. Although it works in Drupal 7, my Bubble plugin wont run.

My site is only a simple 1 page webform, so I would be happy if I could supress the default 1.4.4 and then just link to 1.6.

Looks like there is a patch for the jQuery Update module to update it to jQuery 1.7.


Webform 8.x-5.0-RC3 can't set custom settings Here is my problem. I have a drupal website I'm working on where I've got webform with custom settings (such as checklist with custom elements and some others). I was on 5.0-beta24 and everything was fine. I saw that an update to the RC3 was available so I tried to see if there was any breaking change. And it seems that my custom settings are no longer saved.

What is the breaking change, and is there a solution so I can still define my custom settings / another way to do it ?

You can find below my current function to alter the settings form and add my custom's one.

<?php
function mymodule__form_webform_settings_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $settings = $form_state->getFormObject()->getEntity()->getSettings();

  $form['general_settings']['description']['#title'] = t("Subtitle");
  $form['general_settings']['description']['#type'] = 'textfield';

  $form['form_settings_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => TRUE,
    '#input' => FALSE,
  ];

  $form['form_settings_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => $settings['categories'] ?? ['test'],
    '#required' => FALSE,
  ];

}

Edit :

After some research, it seems (but I can be wrong) that the line that cause trouble is this one

  /**
   * {@inheritdoc}
   */
  public function setSettings(array $settings) {
    // Always apply the default settings.
    $this->settings += static::getDefaultSettings();
    // Now apply new settings.
    foreach ($settings as $name => $value) {
    if (array_key_exists($name, $this->settings)) {
      $this->settings[$name] = $value;
    }
  }

  return $this;
}

As my custom setting is not is getDefaultSettings, I can't save it.

Is there any new way to save custom settings ?

Thanks

Finally, I found the answer. Webform implement ThirdPartySettingsInterface so I can edit my form_alter function to do the following :

// Because hidden by default.
$form["third_party_settings"]["#access"] = true;
$form['third_party_settings']['quizzes']['details_categories'] = [
    '#type' => 'details',
    '#title' => 'Catégories',
    '#open' => true,
    '#input' => false,
  ];

  $form['third_party_settings']['quizzes']['details_categories']['categories'] = [
    '#type' => 'checkboxes',
    '#options' => \Drupal\avantages\Services\PopulationsService::getPopulationList(),
    '#title' => t('Catégories'),
    '#default_value' => "",
    '#required' => false,
  ];

And to access my data, within the Webform entity :

$webform->getThirdPartySetting("quizzes", "categories");


How do I replace a plugin? Let's say that I want to replace the block_content_type plugin of the core block_content module to ad some features while not having to rewrite a whole module to achieve this.

It is very easy to replace a service by providing your own service definition with the same key as the to-be-replaced service. How do I replace a plugin with another one?

To answer the general question how do you do that with plugins: Each plugin type is managed by a plugin manager. You can list all plugin manager classes with this console command:

drupal debug:plugin

Most plugin managers provide an alter hook to change the plugin definitions. Look in the plugin manager class method __construct for a line with $this->alterInfo():

public function __construct(...) {
  ...
  $this->alterInfo('example_plugin_info');

In this alter hook you can replace the class of plugins managed by this plugin manager:

function mymodule_example_plugin_info_alter(array &$info) {
  if (isset($info['foo_plugin'])) {
    $info['foo_plugin']['class'] = '\Drupal\mymodule\Plugin\ExamplePlugin\MyCustomFooPlugin';
  }
}

You can check the result by executing the same console command, now providing the plugin type as parameter, to list the plugins of this type and their classes:

drupal debug:plugin example_plugin

Entity type classes

About your specific question, the plugin manager for entities is EntityTypeManager (not listed by the console command because it doesn't use the standard service name scheme). It provides an alter hook to alter entity types as well, so if you are referring to the bundle entity type class of Block Content, then you can change it here:

/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(array &$entity_types) {
  $entity_types['block_content_type']->setClass('...');
}


Ignore template from base theme I have written a D8 sub-theme.  Base theme is bootstrap, but I don't think it really matters.

My base theme defines a very specific template field--node--field-image--article.html.twig that I would like to ignore, as if it did not exist.  I would like to fallback to the next best match template, whatever that is.

I have already considered the following options, but they aren't entirely satisfactory.

Delete the unwanted template from the base theme.  However I then have to remember to delete the file again every time I update the base theme.
Override the unwanted template with an identically named file in my sub-theme.  In that file %include the preferred template.  However this requires me to name a specific preferred template.  I would rather let Drupal decide what template would be the best match excluding the unwanted one.
I have discovered the function hook_theme_suggestions_alter.  However I'm not sure that it solves my problem because I don't want to lose the ability to use any given suggestion in general - just that one very specific file.

I guess I will end up going with option 1) if I can't find a better idea.

One way to remove the template from being in the list of suggestions, and ultimately not being used, would be to implement hook_theme_suggestions_alter, and unset it from the $suggestions array. This should effectively remove it, and the next specific template will be used instead.

Alternatively, you can copy the template file in from the base theme, and overwrite it to be a default rendering that is preferable to you (without removing the suggestion) and it will be used instead.


nodeaccess prevent some roles to view views contents even if they allowed to access I'm using nodeaccess module to secure some published contents from being seen by normal users or anonymous.

I have a view allowed only to admin and moderator roles to access, but when nodeaccess module is enabled moderator role couldn't see the view contents.
the moderator have permissions to view and edit the content of this content type.

I tried to change the view permission access to "view publish content", it doesn't work until I disable nodeaccess.

So I want understand I what is them problem, and how can allow moderator user to view the view contents? Or at least if nodeaccess is not recommended in my usecase what I should do instead?

I found this module node_view_permissions, it did what I want in my use case, so I removed nodeaccess.

  Node view permissions module enables permissions "View own content"
  and "View any content" for each content type on permissions page as it
  was on Drupal 6. It's as simple as that.

  It's implemented in a non-conflict way, so you can use it with any
  other permissions related module.


How to theme the node edit form to group fields into collapsible containers? I'd like to tidy up an unwieldy node edit form using collapsible fieldset elements.

I can do this by implementing a form_alter hook but will this affect Drupal/other modules' ability to process/validate the fields? Obviously it will change the #parents of several elements, and I'm unclear whether this change will also affect $form_state['values'].

Is it safe to do this, or is there another way to achieve the same?

Example code

$form['group1'] = [
  '#type' => 'fieldset',
  '#title' => 'My Grouped Fields',
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  'children' => [
    'body' => $form['body'],
    'field_smallprint' => $form['field_smallprint']
    ],
  ];
unset($form['body'], $form['field_smallprint']);

It seems to me that this is probably safe unless #tree is TRUE, but I don't want to implement something that might lose data, hence the question here.

I would recommend you to first try the Field Group module that provides the option to do that kind of grouping and many more options.


Swap columns inside every other row with Views and Bootstrap i want to create block with views.I want style output like image bellow.
Sorry i add  image because my english is not good and i cant explain what i want

Use Views Bootstrap and implement it using the grid.

  Views Boostrap module enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.


Hitting a download link and displaying text in the same menu item page callback (7) I have a menu item for one of my content types that I want to be able to package up some different files, create a .zip file, link to start a download and then display some text which will describe what the user needs to do with the .zip file.

Here is my menu declaration:

        'title' => 'Download Icon',
        'description' => 'Package up the selected icon as a zip file and download it',
        'page callback' => 'download_icon_page_callback',
        'page arguments' => array(1),
        'access callback' => 'download_icon_access',
        'access arguments' => array(1),
        'type' => MENU_LOCAL_TASK,
        ),

And here is my page callback that doesn't work for obvious reason:

function download_icon_page_callback()
{
    // some code to compile my .zip file
    drupal_goto('path/to/my/file.zip');
    return t('Here are some inustrctions!');
}

So this above function can link to the file compiled .zip with a drupal_goto but since this a redirect the return t will not ever go through.  Is there anyway I can hit both of these in a single page callback?  Also, is there a better way to display formatted text from the menu item instead of just doing a return t() from my page callback?

A particularly low-tech solution using meta refresh (which should work cross-browser):

function download_icon_page_callback() {
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'refresh',
      'content' => '5', // Timeout in seconds
      'url' => '/path/to/my/file.zip'
    ),
  );

  drupal_add_html_head($element, 'download_icon_refresh');

  return array(
    'instructions' => array(
      '#markup' => t('Some instructions')
    ),
    'backup_link' => array(
      '#markup' => l('Click here if the file download does not automatically start.', 'path/to/my/file.zip'),
      '#prefix' => '<p>',
      '#suffix' => '</p>'
    )
  );
}

Although returning a string from a page callback function works fine (the return is run through render() which accepts a string or render array), returning a render array is preferred as it gives other parts of the system the chance to alter the output while it's still in a structured manner. The documentation for render arrays is a great place to start if you haven't used them before.


Display number of times content is referenced in content How would I go about implementing the following content types + fields

Parent

Name
Description
Other fields (e.g. location, date)
Number of children

Child

Name
Description
Other fields (e.g. location, date)
Parents (entity reference)

Children can have multiple parents.

Basically what I want to do is to create a new Child and "tag" a Parent in it. A View with a list of Parents would then display something like "[Parent Name] has x Children" for each Parent.

I'm very new to Drupal so if I'm going about this completely the wrong way, please let me know!

This video series helped me an infinite amount: http://vimeo.com/33251051, http://vimeo.com/33252553.

Make sure Child has an entity reference to Parent.
Create a new view
In Filter Criteria, add a new Type (= Parent)
In Advanced>Other, set Aggregation to YES
In Advanced>Relationships, add a new relationship for "A bridge to the Content entity that is referencing Content via field_parent" where field_parent is your entity reference. Call this "Parents"
In Fields, add Content: Title and when prompted set its Aggregation type to Group results together
In Fields, add Field: Parents and when prompted set its Aggregation type to COUNT (Distinct)
Ta-da


How to restrict access to a node via node/12 and allow access via a path like content/sometitle? Problem: I want to restrict direct node access using node number www.example.com/node/12 and allow access using pathauto alias www.example.com/content/sometitle to anonymous user. This user should be allowed to see all content of node using only Pathauto title path but not with node number to snoof.

Mostly I want to target anonymous users. Admin always has access to everything.

In simple terms, I want to redirect all node/Number paths (not node/add/ContentType) to say the Home page or No Access page.

The Global Redirect module does what you want (and more).

  ... Checks if the Clean URLs feature is enabled and then checks the
  current URL is being accessed using the clean method rather than the
  'unclean' method.

It redirects the node/xx to content/your-content etc if clean URLs feature is enabled.


Book outline in custom form I am creating a custom form which creates new nodes of type 'book'. I have been able to get the "book outline" to render on my form using

$nid = $node->nid ='nid';
module_load_include('inc', 'book', 'book.pages');
book_outline_form($form,$form_state,$node);
_book_add_form_elements($form,$form_state, $node);

My issue is when i select the drop-down for Book, it does not have "create a new book" as an option

Can someone help me with this issue? Has anyone experienced this before?

I got it to work! My issue was that $nid = $node->nid ='nid' should have been set to $nid = $node->nid ='new'.

I also added module_load_include('inc', 'book', 'book.pages'); to call the function book_outline_form();


How do I track a publicly downloaded file? I am creating a custom module to track the file download time and user id with a file link or path. I have tried multiple modules but the download the file time tracking option is not available.
How I can programmatically track the file download time?
This is the code I am using.
function mymodule_file_download($uri) {
$scheme = \Drupal::service('file_system')->uriScheme($uri);
  if (in_array($scheme, ['private', 'temporary', 'session'])) {
    $permission = "read $scheme files";
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
    if ($account->hasPermission($permission)) {
      return [
        'Content-Type: text/plain',
      ];
    }

    if (\Drupal::currentUser()->isAnonymous()) {
      throw new NotFoundHttpException();
   }

  }
  elseif (in_array($scheme, ['public'])){
    $current_user = \Drupal::currentUser();
    $account = $current_user->getAccount();
   \Drupal::logger('downloads_tracker1')->notice($account);
  }

}

hook_file_download doesn't run for public file downloads.

Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.
For example, track downloads with Google Analytics event tracking


"Manage display" tab missing in Manage fields window I am editing and working with fields for a Content type but can only see Field settings, widget type and delete tabs. The Manage display tab is missing.

How do I make it display?

I am running drupal 7

The tab might just be somewhere else. When you edit a content type, you see at least two tabs (provided that the core "Field UI" module is enabled):

Manage Fields
Manage Display

If you go to "Manage Fields" and then click on "Edit" for a given field, you will see the "Field Settings", "Widget type" and "Delete" tabs, as you say, but not the "Manage Display" tab. To see it, you need to go to the content type edit screen, it will display the list of fields and their display properties.

Hope that helps,


Admin menu issue with the modules tab I am using drupal 7, and i have a problem with the modules.The problem is when I login as an administrator i cant enter to the modules tab in the admin menu. there is a message say "500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed."
how can i enable a specific module?and how i fix this issue?

Thanks for your cooperation.

500 Internal server error is normally at Server level. To fix this, you'll first need to check is the actual error which you can check either Drupal Logs (located at "Admin => Reports => Recent Log message") or Apache error log (located at "/var/log" in Linux OS).


Multiple results in a view due to taxonomy? I have a content type called "Stuff". Which has a taxonomy term called "Area". There are three Areas: A, B and C. I have a view that lists the content. The problem is, I get duplicates based if a node is assigned to multiple terms.

So for example, if I have three nodes, each assigned to ONE taxonomy term, I end up with:

Stuff 1 | A
Stuff 2 | B
Stuff 3 | C

But if I assign a node to multiple terms I end up with:

Stuff 1 | A
Stuff 2 | B
Stuff 3 | C
Stuff 4 | A, B, C
Stuff 4 | A, B, C
Stuff 4 | A, B, C

I've tried:

Going under ADVANCED --> OTHER --> QUERY SETTINGS --> DISTINCT ...

Any ideas what could be causing this?

UPDATE

If I use aggregation, I get:

Stuff 1 | A
Stuff 2 | B
Stuff 3 | C
Stuff 4 | A
Stuff 4 | B
Stuff 4 | C

But I want:

Stuff 1 | A
Stuff 2 | B
Stuff 3 | C
Stuff 4 | A, B, C

What am I missing?

Use aggregation. It's just above query settings.


Drupal Join Query with entityCondition I have two content type A and B in which B content type node is reference in A content type node. In B content type node there is status field. I want to fetch the A content type node in which the status of B content type node is something.

Can you please guide me how can I use this?

Thanks

This is the best solution for you ==> https://www.drupal.org/node/1343708

EFQ an beautifull tools for manipulate the entities in drupal.

Do not hesitate if you need precision but this doc is verry good.

In the Entity Reference case

The column name for an entity reference field is target_id, so your code should be:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'custom_node_type', '=')
  ->fieldCondition('field_reference_name', 'target_id', $id, '=');

$entities = $query->execute();

For follow the relation of your entities you need to reference the A into B or B into A with a reference field. When you use EFQ to search the relation in node A with B you need to use fieldCondition in this reference field in my example is field_reference_name. If you list the content B (ids) into an array and you user this

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'a', '=')

$entities_a = $query->execute();

For search the relation A to B into A you need to use this :

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('type', 'b', '=')
  ->fieldCondition('field_reference', 'target_id', $entities_a, 'IN');

$entities_b_refered_into_a = $query->execute();

Good chance.


Making fields, condition and join dynamic in db_select query What is the Drupal way of creating queries which are dynamic in nature ?
What I mean is for example- In my module I am asking the user to select some content types and the fields associated with each of them. If node type "article" is present the user can select it and also select some fields lets say- field3, field4 - out of all the fields present field1-10. This custom selection is then stored in a table lets say "custom_table"

How can i create queries of the form-
db_select('node','n')
->fields('n','field3','field4') //fields are dynamic based on user's choice stored in custom_table
->condition('n.node-type', 'article') //node type is dynamic based on user's choice stored in custom_table
->join with fields table to get field value //only for value fields

I really dont want to use php string handling and create a "select from node..." type string while looping over values in custom_table.

Is there a less time and space complex drupal way to achieve this ?

Don't chain your query, just put in some ifs and add to the query.  Like so

$query = db_select('node', 'n');
if(isset($field)) {
  // Add each field separate
  $query->addField('n', 'title', 'title');
}

if(isset($article)) {
  $query->condition('n.node-type', 'article', '=');
}

if(isset($join)) {
  $query->join()....
}

$query->execute();

I think this will get you to where you want.  Please also see this thread: http://drupal.org/node/310075


enable viewing access to anonymous user I have the Content Access   7.x-1.2-beta1 module installed.  I would like to enable access to a few basic pages, not all of them, for everyone including unauthorized users.   I only see how to change the access for control for specific users or for all nodes of one type.  How would I fix this?  thanks!

Content Access has "Per content node access control settings" available for each content type.

If you navigate to the "Access control" tab for your content type (or navigate to admin/structure/types/manage/content_type/access) you should see the following fieldset:

As the description suggests, once you've enabled that setting each piece of content of that content type will have an 'Access Control' tab. From there you can decide which roles should be able to access that individual piece of content.

This is what the 'Access Control' tab looks like once you've enabled that setting:


Drupal 8 Link Autocomplete Filter by Bundle Does anyone know how to limit the autocomplete suggestions of Link Fields to only certain bundles -- not globally, but per Link Field instance? I nearly found a solution in customizing https://github.com/minnur/Alter-Entity-Autocomplete , but this is global for all autocompletes, and I need to get the calling Link Field instance somehow.

You can now use the following contributed module to solve the issue:

Link Field Autocomplete Filter

  This module adds a Link Field configuration for filtering the allowed
  content types in the autocomplete field.


How to place the pager for a view in page.tpl.php? I have a view on my front page showing the latest posts, but the design of the website implicates the pager to be located outside the content area of the view (way across in the sidebar). Is there a way I can place the pager in the sidebar in page.tpl.php? I'm using my own custom theme. Any help is greatly appreciated, otherwise I'll have to hack up some CSS positioning but I'd rather learn more about drupal 7!

Thanks!

The following steps might help you to extract the pager out of a view conatiner with a help of small css fix,

1 : Override the view template file
I have created a view called extract pager and created a custom tpl for the same views-view--extract-pagertpl.php

2 : The data-members for pager will be available in the above tpl file copy and place the code into to a sepearte div container

<div class="pager-extract">
  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>
</div>

3 : Rescan the template files in the views and save the view.

4 : The above steps will help you to bring out the pager up to the view content block, use few css styles to theme your pager as per your requirements.


How to make two date fields related to each other? H have a content type with a start date and an end date.
How can make the

end date defaut value adjusting depending on what is entered on the

start date choosen value, ensuring that

end_date always > start_date?

You can use Date module to create multi date field, Check this article for more information


Expand Addressfield Components in Views Situation :

I have added few more fields in user registration form using account settings->manage fields. The type of the field is cck address field.
I created a new view as json document, and I added that field to the view as well, but the problem is its not expanding it as the way I wanted.
What I mean is, I filled the user registration form address field as first name, last name, street etc etc. but I am either seeing the whole field in a single line under Address tag in json or just a tag like this {"nodes":[{"node":{"name":"admin","field_address":"1"}}]}
but what I want is like this:

{"nodes":[{"node":{"name":"admin","first_name":"xyz","last_name":"sdas","street":"ssdsf"}}]}

Any suggestions?

Current version of Addressfield (7.x-1.0-beta5) supports displaying address components in views as separate fields.


Problem with anonymous Flag and webform_select_ options_info() only visible to logged in users So I've been trying to implement an anonymous "wish list" for an eCommerce site using webform_select_options and Flag. My implementation uses an anonymous flag set on my products and uses webform_hook_select to add a select list of the flagged products to a webform.

The issue I have is that the webform_select_options only show up in the webform when the user's logged in, thus failing as an anonymous implementation.

UPDATE (number 2 8/12/15)

I can confirm that the items are flagged when an anonymous user flags them. I tested this with a block displaying the flagged items when the site was viewed in incognito mode, the list is modifiable (I can add and remove flagged items), so it behaves more or less the way I expect it to.

The view shows commerce products that have been flagged by the current user. This shows me that the items are flagged. I have tested this with multiple browsers in incognito mode and can confirm that the lists are different for different anonymous users.

I tried the dpm($view->result); and it looks like the function doesn't get called with anonymous users. The function prints results with an authenticated user, but no result with anonymous users. I adjusted anonymous permissions to see devel information and can confirm that the function is called with anonymous viewers but returns an array with 0 objects.

Here is the code I'm using, the flag is defined through the flag module UI.

<?php
 function webform_hook_webform_select_options_info() {
   $items = array();
   if (function_exists('webform_hook_user_flag_sample_requests')) {
     $items['webform_hook_user_flag_sample_requests'] = array(
      'title' => t("Sample Requests (User Flag list)"),
      'options callback' => 'webform_hook_user_flag_sample_requests',
     );
   }
   return $items;
 }
 function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
dpm($view->result);
       $options = array();
       if ($view->result) {
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }

So, I am at a loss at to what is wrong here, or how to approach this problem. I followed the tutorial here http://drupalsteve.com/node/57, but there doesn't seem to be an obvious way to resolve this.

I now strongly suspect that this is related to the general issue of showing a view to an anonymous user. Normally, you'd mitigate this by disabling SQL rewriting. Now, I wonder if my flags aren't showing up because I haven't programmaticaly set the advanced options of the "view" being created in the script.

So, I can think of two options: 1) create the flag array without generating a view; or 2) set the advanced query setting to disable sql rewriting.

thanks in advance.

So, after some frustration and headbanging, I was led to the answer by someone on #drupal-support IRC. The solution was in fact related to the SQL rewriting. The view was editable through the UI. There under the advanced section, I selected 'diasable sql rewriting.' This ultimately solved the problem.


How does one theme a panel (or add a style) I'm using drupal 7 and panels 3.

I'm looking for a good tutorial, or tutorial video that describes how to them panels. I understand generally hoe to theme nodes and them fields using the template files, but I don't really understand how to theme panels. I see that within the layout designer, it allows you to add a "style" to your panel panes. I understand this is probably theme based, but how would one add another style to this.

Any help would be great.

Thanks

P.S. I did do a search already for this info but was unable to find any really good info.

When you add a CSS class using the "CSS Settings" for the pane, Panels will tag the panel html with the classes you have identified.  You can then specifically change the css styling attributes by defining your class style using the local.css file found in the active theme directory (set in admin/appearance) to modify your targeted content.

IF you are not familiar with working with css , I suggest you get an intro level book on Drupal and theming, a basic primer on css coding, and upload firebug for Firefox browser to help you see which css styles are currently rendering any content you display on the site.

I have not found a good out-of-the-box solution for what you want to do. I hope this helps get you started on the 'custom route'.


.info file is not loading the JavaScript code I added the references to some JavaScript files, in my .info file, hoping that they would be output by the $scripts variable in my header. I cleared the cache, and they are still not there.

$Id$
name = site
base theme = boron
core = 6.x
engine = phptemplate
; We do not have a Left sidebar.
;regions[left] = Left sidebar
; We do not have a right sidebar.
;regions[right] = Right sidebar
regions[content] = Content
regions[header] = Header
regions[footer] = Footer
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js
scripts[] = sitename/sites/all/themes/custom/jivamukti/js/scripts/jquery-1.6.1.min.js

I put the JavaScript in the root of the themes folder I am using, instead of /js, and now it is output in this function in my header:

jQuery.extend(Drupal.settings,…);

How do I just get it to display inside the <script></script> tags?

The file path should be relative to the theme directory not the root directory; try it with js/jquery.nivo.slider.pack.js instead of sitename/sites/all/themes/custom/jivamukti/js/jquery.nivo.slider.pack.js.


how do I determine the field type within a field formatter? I have a field formatter that I would like to use on either a string or file field type. I have everything working as two separate field formatters, but with so much shared code, I'd like to make it just one. I've been digging in the API and the core sources, but nothing is jumping out at me.

/**
 * Plugin implementation of the 'jmol' formatter.
 *
 * @FieldFormatter(
 *   id = "jmol",
 *   label = @Translation("Create a Jmol object"),
 *   field_types = {
 *     "string",
 *     "file"
 *   }
 * )
 */
class SmilesFormatter extends FormatterBase {
public function viewElements(FieldItemListInterface $items, $langcode) {
  foreach ($items as $delta => $item) {
    // Can't figure this next line out
    $type = ($item->type);  // I assume it's something easy
    if ($type == 'string') {
      STUFF
    }
    else if ($type == 'file'){
      STUFF
    }
    COMMON STUFF
  }
}
}

Maybe it is better to keep the two formatters separated and just put the shared code into a new formatter. Your two formatters can then extend the new one and just overwride the things specific to them.


Getting Parse Error during installation of Drupal 8 I am getting the following error while Installing Drupal 8.

  Parse error: parse error, expecting T_CONSTANT_ENCAPSED_STRING' or'('' in var\www\html\core\includes\bootstrap.inc on line 3

When I checked the line number 3 in index.php I saw following two lines.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

I don't know what is the meaning of above two lines and why these are creating the above error.

Hopefully you're not installing Drupal 8 in the hope of using it as a stable website...it's nowhere near ready yet :)

That said, the reason you're getting the error is because the PHP const keyword has only been available for use in the global scope since PHP 5.3. Drupal 8 uses const in the global scope in a lot of places (correctly, as Drupal 8 will require at least PHP 5.3).

My guess is you have PHP 5.2 or lower installed on your server.

Some helpful links:

const docs
Drupal change record for using const instead of define()
Migrating from PHP 5.2.x to PHP 5.3.x


Show View Pane in Node Template based on Taxonomy Term I am trying to add a view pane to a node template. The node and the content type shown in the view panel both have a taxonomy term field, so it should be a simple matter to link them, but I can't figure it out.

My node template has the relationship  Taxonomy term from Node. The view pane has context "has taxonomy term id" and has Argument Input from context. Unfortunately, I can't figure out what combination of selections I need to make in context and argument input to make it all work.

Under Argument Input, do I pick the field that contains the term or do I pick one of the choices under Taxonomy Terms?

Under Context filter value type, do I pick Term Name, Term from ID or something else (or nothing at all)?

I think I've tried all possible combinations, but I have the view showing up on nodes whether they contain the context or not. Any help would be greatly appreciated.

Drupal 7.37, Panels 7.x-3.5 and Views 7.x-3.11.

Ok, I finally figured it out!

To show a view in a panel where the view and panel are related by a taxonomy term (in my case Team Term (field_team_term), do the following:

Use the view content panes module to create a view content pane (How can I show a view in panel with argument in Drupal 7).
In the view content pane use contextual filter "Has Taxonomy Term ID". When Filter Value is not available: Hide View. When Filter Value is available - specify validation criteria - choose taxonomy vocabulary - Filter Value Type: Term Name converted to Term ID. (Some writers suggested checking the "Allow Multiple Values" box at the bottom of the window under More; I found that unnecessary.)
In the Pane Settings - Argument Input, select "From Context".
Under Required Context, select Name under Taxonomy Term.

That completes the views setup.

In the panel settings,

Set up a relationship"Taxonomy term from Node (on Node: Team Term [field_team_term])" in the case of my taxonomy term field.
In content, add the view pane, and select the taxonomy term relationship as the argument.

As near as I can tell, that is only combination of panel context and view arguments that will get the job done. I hope this helps someone.


Drupal\Component\Plugin\Exception\PluginNotFoundException after upgrading drupal I tried to upgrade from version 8.0.x to 8.1.x. I used drush with the command drush up drupal.
The output shows some errors:
Do you wish to run all pending updates? (y/n): y
The "block_visibility_group" entity type does not exist.                                                                                [error]
Performing system_update_8200                                                                                [ok]
Performing block_content_update_8003                                                                                [ok]
Performing path_update_8200                                                                                [ok]
Performing views_update_8200                                                                                [ok]
PHP Fatal error:  Uncaught Error: Class name must be a valid object or a string in /Applications/MAMP/htdocs/drupal8.com/core/modules/field/src/FieldStorageConfigStorage.php:155
Stack trace:
#0 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php(189): Drupal\field\FieldStorageConfigStorage->mapFromStorageRecords(Array, Array)
#1 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Entity/EntityStorageBase.php(242): Drupal\Core\Config\Entity\ConfigEntityStorage->doLoadMultiple(Array)
#2 /Applications/MAMP/htdocs/drupal8.com/core/lib/Drupal/Core/Entity/Entity.php(507): Drupal\Core\Entity\EntityStorageBase->loadMultiple(Array)
#3 /Applications/MAMP/htdocs/drupal8.com/core/modules/field/field.module(181): Drupal\Core\Entity\Entity::loadMultiple(Array)
#4 [internal function]: field_entity_field_storage_info(Object(Drupal\Core\Entity\ContentEntityType))
#5 /Applications/MAMP/htdocs/drupal8 in /Applications/MAMP/htdocs/drupal8.com/core/modules/field/src/FieldStorageConfigStorage.php on line 155

After the update I just keep getting the following error on all pages:

The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "page_variant" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php).

I know this has something to do with the page_manager module. But actually I'm a bit helpless what I can try to resolve this problem. I even have no clue why this problem does occur. The page_manager module is still in the /modules folder.

That means you have a field with an unknown field type. Are you sure that you're not missing any modules that you used to have installed? And the the missing entity type sounds like you used to use https://www.drupal.org/project/block_visibility_groups but now it's gone?

My guess is that you accidently removed all/some contrib modules before updating, which you shouldn't do. Minor updates are like any other normal core update, except they come with some more changes.


Why does the eMail in my Rules Component use a theme that differs from page-theme? I use the Rules module to send follow-up emails, which works fine.

In the past I used a different theme for my site, and somehow this theme (call it "old-theme" for now) is applied when a follow-up email is sent (Mime Mail).

How do I apply the current site-theme to my Rules Component?

You may want to check the result you get if you do NOT tell Mime Mail to use the site's stylesheet. And combine this with creating a file in your theme that is named mail.css. If you do that, then Mime Mail should automatically use that when sending emails. For more details on that, refer to its README.txt, i.e.:

  Email messages are formatted using the mimemail-message.tpl.php template.
  This includes a CSS style sheet and uses an HTML version of the text.
  The included CSS is either:

  the mail.css file found anywhere in your theme folder or
  the combined CSS style sheets of your theme if enabled.

Also make sure your theme is set as "Theme to render the emails" within admin/config/system/mailsystem. Without that, the stylesheets used by emails sent via cron (for example) may not look like you want them to look.


Reverse geocoding (country) from geofield with coordinates is there a quick way to do a reverse geocoding from a geofield field containing geographical coordinates?

I just need the country name, so I wonder if there is some service with more allowance than the Google API, or even a hosted solution with country coordinates and a drupal module quering it???? (as it seems to be a Drupal module for everything)

this is a question that I asked to myself some time ago. I suggest to start from the geocoder module.
This module "translate" an address to a lat./lon. parameter that could be displayed in a map.
Reversing this process - if I understand correctly your question - seems to be a WIP: actually, no out-of-the-box solution.
But you can check and try the suggestions in this discussion.


Drupal multisite: Same theme, different colors I am looking for an answer to a quite specific theming question:

I have a Drupal multi-site installation. (Well, not yet actually, but I want clarity on my question first before I procees. Just asume that I have one.)

I have a team, called 'Theme', which has various files in the directory /sites/all/themes/Theme. In this folder, there are the .tpl.php files and a few folders like css/ and scripts/.

Then, I have 2 sites, which use the same theme: Theme. These sites are located in /sites/default and /sites/alternative.

What I want to do now is providing a file, colors.css in each sites directory (so /sites/default/colors.css and /sites/alternative/colors.css with something like:

@base: blue;
@light: lightblue;
@dark: darkblue;

This file should be read and these 'variables' should replace the variables in the css files located in /sites/all/themes/Theme/css so that I simply can define the colors in each site, without having to modify or to overwrite bits of the css files located in /sites/all/themes/Theme/css.

I already tried a few things, one which could work but I didn't like enough, so I am looking for a general, good and most important, fast method.

What I already have achieved and what (I think) is very usefull:

function theme_css_alter(&$css) {
    $css['sites/all/themes/Theme/css/colors.css']['data'] = conf_path() . '/colors.css';
}

This function changes the default colors.css provided in /sites/all/themes/Theme/css/colors.css and replaces it with /sites/default/colors.css OR /sites/alternative/colors.css, depending on where you are.

I have already tried the following:

Used PHP to get the correct colors.css file and use PHP-variables all over my CSS-files. This should actually work. But I don't quite like it because you end up with a lot of .php files which are actually .css and a lot of ugly php-syntax in the css files.
I tried the lessphp drupal plugin. This did it's work for replacing the variables but the caveat was this: If I want to include the correct colors.css file, I need to use php. Therefore, my less file needs to have the extension PHP. LESS is build so that you can only 'parse' files with the less extension, so this wouldn't work. I quite liked this though, it used some nice caching which would also be the quickest way. What I could do here is dive into the lessphp library and change the code that says 'only .less files please!' to also accept .less.php files.

So, my questions are:

Does anybody see a different approach that would also work and is fast?
If yes: please elaborate
If no: Which of my previous methods do you fancy and why? What would be the best approach?

Well, I found out something that is quite useful:

Instead of trying to import the color.less file in each 'basic' theme css file, I do it the other way around: I import all the basic theme css files in colors.less, like this:

@basis: blue;
@donker: black;
@licht: pink;

@import "../all/themes/Theme/css/basic.less";

Then I had to remove all the stylesheet definitions in the .info file and changed the template function to:

$css = drupal_add_css(conf_path() . '/colors.less', array('group' => CSS_THEME, 'weight' => 115, 'browsers' => array('IE' => 1, '!IE' => 1), 'preprocess' => FALSE));

No hassle with php, and it works, is cached when I want it, and fast!


Login error: call to undefined function entity_load in User module I’m new to Drupal and I have a problem where no users can login (HTTP 500 and WSOD on POST of valid credentials, Drupal 7). The error message is:

“E_ERROR Error in file »user.module« at line 291: Call to undefined function entity_load()”

Any ideas on how to approach troubleshooting this?

Your error's stating that it can't find a function that should be in drupal core. Check you includes folder. There should be a file in there called common.inc, make sure the function entity_load is defined in there.


hook_preprocess_page: "node_load() + node_page_view()" versus "%node + node_page_view()" A basic node (nid "123") exists and a module registered two paths using hook_menu:

first/%node
second

Both page callbacks use node_page_view($node) to display a fullpage view of the node,  except the second callback additionally uses node_load(123) to get a reference to $node.

Therefore http://localhost/first/123 and http://localhost/second look the same as far as the user is concerned.

However hook_preprocess_page receives the node variable only with the first path, therefore Drupal obviously does something beyond node_load when it sees a %node wildcard, any idea what it is so that hook_preprocess_page receives the reference to $node in both cases ? (because handling everything internally in the second path produces much more friendly urls than redirecting to the first path from the second).

Example:

<?php

/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
    if (@isset($vars['node'])) echo '
[mymodule.module] Node is defined
';
    else echo '
[mymodule.module] Node is NOT defined
';
}

/**
 * Implementation of hook_menu().
 */
function mymodule_menu(){
    return array(
        'first/%node' => array(
            'title' => 'First callback',
            'page callback' => 'mymodule_page_first',
            'page arguments' => array(1),
            'access callback' => TRUE,
        ),
        'second' => array(
            'title' => 'Second callback',
            'page callback' => 'mymodule_page_second',
            'access callback' => TRUE,
        ),
    );
}

/**
 * Page callback for url "http://localhost/first/123".
 */
function mymodule_page_first($node){
    echo '
[mymodule.module] Function mymodule_page_first

';
    var_dump($node);
    echo '
';

    return node_page_view($node);
}

/**
 * Page callback for url "http://localhost/second".
 */
function mymodule_page_second(){
    $node = node_load(123); //the ID of an existing node

    echo '
[mymodule.module] Function mymodule_page_second

';
    var_dump($node);
    echo '
';

    return node_page_view($node);
}

(Source of file mymodule.module)

My best/only hope so far is to dig in the source of node_page_view and all functions it consequently triggers until I find what happens between the moment node_page_view is called and the moment the module_invoke_all which triggers the hook is called.

When mymodule_preprocess_page() is invoked for the "first/%node" path, it gets the node object because the path is associated with a node from the module.
Drupal cannot associate a node object with a path like "/admin/content/node" (Drupal 6 path) because the path doesn't contain any reference to a node ID which is marked as node ID. Which node object should Drupal return for such paths, considering a Drupal website can contains hundreds of nodes?

Your question is "how can Drupal associate a node object in one case, but not in the other one?"

The answer is in the template_preprocess_page() code, which the function executed before the template page.tpl.php is rendered.
In that function, you will find the following code:

if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

The default parameters for menu_get_object() are $type = 'node', $position = 1, $path = NULL, which means template_preprocess_page() is asking for the node object that is associated with the placeholder in position #1, which is the value returned, for example, from arg(1).

Looking at the source of menu_get_object(), you will notice that the code being executed is the following:

function menu_get_object($type = 'node', $position = 1, $path = NULL) {
  $router_item = menu_get_item($path);
  if (isset($router_item['load_functions'][$position]) && !empty($router_item['map'][$position]) && $router_item['load_functions'][$position] == $type . '_load') {
    return $router_item['map'][$position];
  }
}

Using the default arguments, the function will verify the loading function associated with the route item #1 is node_load(). If the loading function is that, then it will return the value returned by the loading function to the calling function (in our case, template_preprocess_node()).

To automatically get a node object, your menu callback should use a path like "second/%node" (which would be compatible with the default menu_get_object() arguments). The only problem is that for such paths the node ID needs to be passed; if the URL is http://example.com/second, Drupal will show a 404 error page, as the placeholder require parameter that must be passed.
To resolve this problem, the module should define two menu callbacks: one associated with "second", and one associated with "second/%node". The first menu callback would not get a node object, while the second would get the node object (and mymodule_preprocess_page() would get it too).

As alternative, you should change the code of mymodule_preprocess_page() to something similar to:

/**
 * Implementation of hook_preprocess_page().
 */
function mymodule_preprocess_page(&$vars){
  // Check if the page being served is one of the pages handled by the module.
  if (arg(0) == 'first' || arg(0) == 'second') {
    if (isset($vars['node'])) {
      // The page is a node page.
    }
    else {
      $vars['node'] = mymodule_load_the_default_node();
    }
    // …
  }
}


How to stop spam in comments I've installed reCAPTCHA module but spam still bypass my security and leave nasty comments. What should I do? How to block them?

I made good experience with Mollom. But you need a free registration at their site.

Update: Unfortunately Mollom has announced the end-of-life for their service by April 2018.

Update 2020: I really like the antibot module. It's lightweight and pretty effective.


Custom Entity - use taxonomy fields in views I've created custom content entity, where one of fields defined in BaseFieldDefinitions() is

$fields['game_category'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Game category'))
    ->setDescription(t('Game category'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setRevisionable(false)
    ->setCardinality(-1);
;

Now, I'm trying to create a list using Views, where one of displayed fields will be "Game category" term name. What I managed to achieve is to display that term's tid.

QUESTION: How to display term's name ?

I suppose I should add a relationship, so Views is able to make a JOIN with taxonomy table

My class exposing fields to Views looks like this:

class GameViewsData extends EntityViewsData implements EntityViewsDataInterface  {

public function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
    return $entity_type->getDataTable() ? : $entity_type->getBaseTable();
}

public function getViewsData() {

$data = parent::getViewsData();

$data['game'] = array();
$data['game']['table']['group'] = t('Game Entity Table');
$data['game']['table']['provider'] = 'game_entity';

$data['game']['table']['base'] = array(
    'field' => 'id',
    'title' => t('Game Entity Table'),
    'help' => t('Game Entity Table'),
    'weight' => -10,
);

$data['game']['name'] = array(
    'title' => t('name'),
    'help' => t('name'),
    'field' => array(
        'id' => 'standard',
    ),
    'sort' => array(
        'id' => 'standard',
    ),
    'filter' => array(
        'id' => 'string',
    ),
    'argument' => array(
        'id' => 'string',
    ),
);

$data['game_entity_game__game_category'] = array();
$data['game_entity_game__game_category']['table']['group'] = t('Game Entity Table');
$data['game_entity_game__game_category']['table']['provider'] = 'game_entity';

$data['game_entity_game__game_category']['table']['join'] = array(
    'game' => array(
        'left_field' => 'id',
        'field' => 'entity_id',
    ),
);

$data['game_entity_game__game_category']['game_category_target_id'] = array(
    'title' => t('game_category_target_id'),
    'help' => t('game_category_target_id'),
    'field' => array(
        'id' => 'standard',
    ),
    'sort' => array(
        'id' => 'standard',
    ),
    'filter' => array(
        'id' => 'string',
    ),
    'argument' => array(
        'id' => 'string',
    ),
);

return $data;
}

}

You didn't say that you wanted to do this programmatically, so I'll give you the answer for doing it in the UI. Since you have defined the field game_category as an entity_reference, you can add a relationship in your view to Taxonomy. See Add a relationship to a view for an example.

Then, any field in Taxonomy will be available in your view, including the name. Since this is built into the Views UI by default, you do not need any of your getViewsData() custom code.


A good way to import tweets, blogpost, flickr photos, slideshare, I'm building a "social corner" on my website and I need to import quite a lot.

I've got these accounts:

Twitter
2 blog
Slideshare
Flickr
YouTube channel

I'm using the feeds-module at this moment, but for some reason, it got overwritten.

I tried with the Media module, but I got an error every time I tried to activate the modues, so that's not an option either.

There is a pretty good module for catching and showing tweets, but there seems none like it for YouTube posts, Slideshare, Blogs, Flickr,...

What is, in your opinion, the best way to import this kind of social media every 30 minutes or so. Because I can't think of any anymore.

You're on the right track, but it sounds like your site may have some "too many modules" issues.  If you're having modules randomly overwritten or enabling is throwing errors, it is usually time to clean up the site.  If you can, start with a brand new site and only enable the modules you absolutely need.  Keep things as basic as possible.  If you want to try out other modules do it on a separate "sandbox" site that is just for testing.

There isn't going to be a single-solution for all social media.  However some places to get started:

Feeds module - for anything using RSS (YouTube does, so does SlideShare, Twitter kinda does, etc)
Specific modules could be used too like Twitter Pull and the Media module as you mentioned.


how can i specify certain block for specific content type to get in there? In Drupal 7 every content type gets in the "Main page content" block,
so I want every node with "Product" content type to sits in some other block.
How could I?

It sounds like you're looking for the Views module; it's essentially a query builder with a simple-to-use UI.

You can make a View that lists all the content of type 'product', displayed in a choice of different formats (HTML list, table, unformatted list of content, etc.). You can create different display modes for the View, including a block which you can assign to a region in the blocks admin page as normal.

The best part is, though, that you also get the benefit of being able to easily choose the sort order of the list, set filters on certain criteria, add AJAX pagers automatically, and a lot more.

Check out Working with Views to get started; you'll be glad you did!


Views: output item fields grouped by field instead of item? So currently if I make up a view that outputs three articles with their title and body fields a cleaned up version of the html structure would be:

Item One Title

Blah Blah Blah......

Item Two Title

Blah Blah Blah......

Item Three Title

Blah Blah Blah......

Anyone know how I can, through Views or the best alternative, make the structure like this instead:

Item One Title

Item Two Title

Item Three Title

Blah Blah Blah......

Blah Blah Blah......

Blah Blah Blah......

Look at Views Attachments. Set up your first View w/ just titles. Then Add display > Attachment, override your Fields to get body and use Attachment settings to position it after the first. Should be a few tutorials out there if this is confusing. Hope it helps.


What do I need to install to run Drush make? I want to make a site using a drush make command.I have already Drush installed on my server.
When I try to run this command: drush make --prepare-install martplug-build.make mart plug I receive this message: The drush command 'make martplug-build.make martplug' could not be found.

Should I also install Drush Make? If so how to do this?

Did you have a look at the INSTALL.txt file. The easiest is to put it inside .drush folder


Drush over local network share? Can drush be run on a site when I have the server connected to my machine as a network share? I am running Win10 and the server is Windows based with IIS. The website folder mounted as a drive, so the path to it is something like Z:\website.

I noticed that I can switch between Acquia DevDesktop sites by changing the cmd line path (ie. from c:\devdesktop\site1 to c:\devdesktop\site2)

Can I essentially do the same by changing over to z:\website?

My thinking is that getting everything setup as if the webserver were remote (what most install tutorials asume) seems overkill. But, I am not really sure what DevDesktop is doing to get drush running on it's sites.

Is anyone doing anything similar?

In theory yes. Windows is a bit more difficult because, windows.

But if you have Drush installed locally, and it's the same PHP version as you have on the server machine it should work. You will need to modify your DB credentials to reference your database by network accessible hostname or IP so that your machine can connect to the database on the server remotely.

Disclaimer: I've never tried this, but it should work. YMMV etc.

The more "right" way to do this would be to set up an ssh server on the windows box server, and set up Drush aliases to act against the remote server with Drush installed locally on the server and client.

I don't know how well that works on Windows but quick reading suggests it should be possible.


How to have a separate image style for an image field for the 1st views row? First I tried with views_conditional (which was already installed on the site) to check for 1st row and output the specific image but it does not seem to work as per this issue

Ideally I want to do it without installing an extra module.

I tried with THEMENAME_preprocess_views_view_field but the image was already rendered at this stage.  Have used the somewhat hackish str_replace but it does not actually work.

function THEMENAME_preprocess_views_view_field(&$vars) {
  if($vars['view']->element['#name'] == "free_write"
      && $vars['field']->field == "field_main_image"
      && $vars['row']->index == 1
      ){
    $html = str_replace("teaser_media_small","teaser_media_medium",$vars["output"]->__toString());
    $vars["output"] = Drupal\Core\Render\Markup::create($html);
  }
}

what is the proper way to do this in a preprocess function or perhaps in a twig template ?

A solution can be Add an Attachment Display to the View, in the Attachment you can select to show only one element with a different style and you can give as position Before.

In the Page then you select to skip 1 element.

This will output something like this:


How to limit a user to one vote when using Fivestar? In Drupal 7 I have enabled the fivestar module to allow users to vote in their comments. The results are tallied and give an average vote. Cool stuff.

Problem is a person can just keep voting over and over in each new comment or reply.

How do I limited a person to just one vote per node, via the comments. In other words, once they have voted, either the stars disappear, or the persons other vote is the default and cannot be edited?

Thanks

You can easily do this using a custom module that contains code similar to the following one.

function YOURMODULENAME_print_rating($nid, $fivestar_widget) {
   $path = drupal_get_path('module', 'fivestar');
   drupal_add_js($path . '/js/fivestar.js');
   drupal_add_css($path . '/css/fivestar.css');
   $voting_message = '';
   $output = '';
   $is_login = user_is_logged_in();
   $rating = votingapi_select_single_result_value(array(
       'entity_id' => $nid,
       'entity_type' => 'node',
       'tag' => 'vote',
       'function' => 'average',
   ));
   if ($is_login) {
     if (isset($rating)) {
       $voting_message = "
You have already rated this.
";
       $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
     }
     else {
       $output = render($fivestar_widget);
     }
   }
   else {
     $fivestar_links = l('Login', 'user/login') . ' or ' . l('Register', 'user/register');
     $voting_message = "
Only registered user can rate this content type.
$fivestar_links to rate this content type.
";
     $output = theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')) . $voting_message;
   }
   return $output;
 }

Use the below snippet in your node template file.

hide($content['field_fivestar_rating']);// This line will hide the stars which are coming from the fivestar module.
print YOURMODULENAME_print_rating($node->nid, $content['field_fivestar_rating']);// This will print the fivestar.


How can I limit the number of chars/words in a long text field to 3000? I would like to limit the amount of text that my users can input in a text field. I want it to be a text area so I made a field called "Solution" then I made it a type "Long Text" and a widget type of "Text Area." I would like to limit the number of characters that the user can post to 3000 characters. Is there an easy way to do this?


How to add a radar chart to Views? I'm using the Charts module to create a chart in my view (using its Views integration). But the supported chart type doesn't include Radar chart, which is what I would want it to be.

I found a sample of such chart at https://www.drupal.org/files/RadarGraph.png, which looks like so:

Is there a way I can get that to work?

Solution 1 - Using module Charts (with Views)
There is no out-of-the-box answer to your question to make this work with the Charts module, at least not as of today (yet). That's because "Radar chart" is not one of the currently supported chart types (those that are supported are: Pie, Bar, column, Line, Area and Scatter).
But if you're willing (and able) to complete a few extra steps, you should get it to work. Use the details below as a guide, but know also that there are so many options / features in either of the supported charting engines (libraries), i.e. Google Charts and Highcharts. Which is also why it's virtually impossible to support all those options out-of-the-box.
Option 1
Refer to the issue about Stacking column/bar charts for an example of how you can do this with a custom module. Comment #3 in it contains a sample like so:
<?php
function MYMODULE_chart_alter(&$chart, $chart_id) {
  dsm($chart_id); // Need Developer module enabled for dsm to work
  if ($chart_id == 'MYCHARTVIEW__DISPLAY') { // Watch out for those double underscores
    $chart['#stacking'] = TRUE;
  }
}
?>

This should work for both Google Charts and Highcharts as the charting library (engine).
The remaining challenge for you is what exactly you should specify as chart_id, and which specific charting option is needed for such "radar chart". My best bet, for Highcharts, is that it is what that library calls a "Polar Chart" (would be too easy for all those charting libraries to use at least the same terminology ...).
Option 2
A possible alternative (or maybe refinement, depends on your needs) that you may want to look at is using the approach as described in the issue about Pass library-specific options via existing #raw_options, AFTER you apply the patch in comment nr 4 of this issue. If you're using the most recent dev version of the Charts module (which is stable and includes various patches on top of the rc1 release), then this patch is already available (no more need to apply it). Be aware that this only works for Highcharts as of right now (waiting for a similar patch to become available for Google charts also).
Refer to the question about "https://drupal.stackexchange.com/questions/183018" (and its answers) for an interesting use-case of these "raw options".
Solution 2 - Using module Forena (without Views)
The sample radar chart in your question is actually from the Supported chart types, one of the Community documentation pages from the Forena module.
The very same sample is also included in SVG Graph Demo, one of the samples that gets installed by the Forena module, such as in this demo site.
So such chart can ALSO be created with the Forena module, which uses the (free and open source) PHP SVG Graph library, without using Views. And by using the integration of Forena with the BEAN module (as explained in its documentation about Bean Integration, you can put such chart in a block that you'd put on your page where it fits your needs.
For (way) more details, head over to the Forena Documentation included with the module (or its equivalent in the demo site). Or have a look at various questions around here tagged with forena ... and add your own questions if needed (using this tag).
Disclosure: I'm a (co-)maintainer of Charts and Forena.


Problem creating nodes from XML using Feeds/ Feed XPath Parser I'm trying to create nodes from an XML feed using Feeds XPath Parser.

Some of the data appears to import, but not all fields are being populated or populated correctly.

Here's a snippet of the feed:

<merchantProductFeed>
<script/>
<SCRIPT/>
<merchant id="2607" name="Business IT Online Office Shop">
<prod id="49194411">
<pId>571895</pId>
<text>
<name>
Avery afterBURNER Label System Software with Applicator 10 Inserts Ref AB1800 [24 Labels]
</name>
<desc>
Avery afterBURNER Label System Software with Applicator 10 Inserts Ref AB1800 [24 Labels].- Includes software, applicator, 24 labels and 10 inserts.- For Professional CD labels and inserts.- No Touch labels - unique design of the label sheets mean you can apply the label to the CD/DVD without touching the printed design or the adhesive.- 20 premium matt and 4 photo quality glossy labels.- The curved design of the applicator means the label is rolled smoothly onto the CD/DVD.- Inserts include a CD jewel case insert cover and tray (including spine) - allowing design and print in one effort.- The software contains over 2000 clip art images, 120 pre-formatted label designs and much more.
</desc>
</text>
<uri>
<awTrack>
http://www.awin1.com/pclick.php?p=49194411&a=953&m=2607
</awTrack>
<awImage>
http://images.productserve.com/preview/2607/49194411.jpg
</awImage>
<mLink>
http://www.businessitonline.com/avery-afterburner-label-system-software-with-applicator-10-inserts-ref-ab1800-24-labels.bprod?inctax=true
</mLink>
<mImage>
http://www.businessitonline.com/eCommImages/571895.jpg
</mImage>
</uri>
<price curr="GBP">
<buynow>15.56</buynow>
<delivery>5.95</delivery>
</price>
<cat>
<awCatId>68</awCatId>
<awCat>Software</awCat>
<mCat>Machines and supplies>Computer Software</mCat>
</cat>
<brand/>
</prod>

There are several more products in the document, structured in the same way.

In the feed importer, I've set the context as //merchantProductFeed/merchant/prod.

I have two fields to populate: 'title' (text) and 'cost' (decimal).

The XPath query I'm using for title is 'text/name' and the query for cost is 'price/buynow'.

When creating the nodes, the title field is populated with the correct data, but includes the  and  element tags.

The cost field doesn't get populated.

I can't see where my XPath query is going wrong, so I'm unsure if it's a problem with that or something that isn't happening properly elsewhere in the XPath Parser module. So far as I can see, the mappings are set up as they should be.

Can anybody see if my XPath queries are correct for the XML feed above?

Have you tried turning on debugging in the Xpath Parser? It can give you an idea of what is going into the field before any interference like the formatting of the field itself.

I also use Firepath which is an add-on for Firefox for use with Firebug.
I don't use Xpath very often- kind of a quick means to an end- and the two of these tools have been invaluable. Firepath will help you find out if your Xpath is correct.


Can I track embedded pdf's in statistics module Client has pdf's embedded in pages. They want to track pdf clicks. Statistics tracks nodes and there are add-on modules that track file field clicks, but I haven't seen anything within Drupal to track the embedded files. Any suggestions?

The gist of most Drupal performance-tuning essays is don't use the statistics module, because it causes a lot more Drupal DB traffic.

I can't help with configuring the statistics module itself and I suspect the reason the links aren't being monitored is that those files are being delivered from the sites/.../files folder by Apache|Nginx directly, and Drupal isn't seeing them. As such, you might be able to monitor the webserver logs to get the info you need.

Alternatively I would start off by looking at google analytics or some similar client-side tool for this. If that isn't suitable (and it's not guaranteed it is), then next step could be to create a handler for your files, e.g. a ctools module, which parses the path to get the file to deliver, logs whatever info is appropriate and then sends the file onward. There are some issues re: caching and headers, but not very hard.

If you could do that, but are stymied because the file links are entered by the user within nodes, perhaps you could add a text content filter (such as those that break paragraphs at newlines) that read in the original URL and converted those matching the right pattern to the monitored form. That isn't hard either.


How to group taxonomy terms by their parent when using term reference field? Is there a way to group taxonomy terms by their parent name(as fieldsets) for term reference field in content creation?

For example: Cat#1 as parent and subCat#1, subCat#2 as children should be shown as a fieldset with Cat#1 as legend(and thus unselectable) and subCat#1 & subCat#2 should be shown in this fieldset.

I think Taxonomy Super Select does what you want for Drupal 6, but there's no Drupal 7 version available.

However, the module page recommends the Taxonomy Term Reference Tree Widget module to do the same thing

  This module provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


How to debug Drupal Forms Sometime back I'd gone through a Lullabot video that showed me how to simply click a form and see all its elements using Krumo using Devel module.

But I've searched all internet I'm not able to find this feature. How do I simply click a form and see all of it's elements in Krumo?

You need just to implement the hook_form_alter in a test module this way:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term':
      dpm($form);
      break;
  }
}

where $form_id is form identifier (in the example code I captured the new taxonomy term entry form) which you can find through firebug.


Unable to submit form to database in custom module I am building a custom module and I'm unable to get the form to talk to the database. The section for uploading to the file system works fine.

This is MyModuleBlock.php

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

use Drupal\my_module;

/**
 *  @Block(
 *    id = "my_module",
 *    admin_label = @Translation("Add Image"),
 *  )
 */

class ImageBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
      // stuff here;
  }

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

    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['image'] = array(
      '#title' => t('My Module'),
      '#type' => 'managed_file',
      '#upload_location'=> 'public://images/',
      '#required' => FALSE,
    );

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

    return $form;
  }

  /**
   * {@inheritdoc}
   */

  public function submitForm($form, FormStateInterface $form_state) {
      MyModuleDB::add();
  }
}

The MyModuleDB.php (I am trying out plain text to see if any errors or anything pops up):

<?php

namespace Drupal\my_module;

class MyModuleDB {
    static function add(){
        db_insert('my_table')
            ->fields(array('image' => 'img1'
            ))->execute();
    }
}

I'm at a total loss here. The tutorials I've found claim that this should work out fine, but it isn't working for me at all. I even tried inserting into the database directly from submitForm() in the main block class. I also tried to add redirects to the submitForm(). I'm thinking the issue is in that function, but I don't see what the issue could be.

If you write a block, use \Drupal\Core\Block\BlockPluginInterface::blockSubmit for submission


Drupal Commerce - Out of Stock, customer clicks to notify store owner to order more When a product is out of stock, the store owner wants customers to have the ability to pre-order, without paying.
Similar to stock notify, but the store owner will manually email back customers once the stock arrives.
Something like'This product is out of stock, notify us, and we will order it in for you within 1 week.'

So it needs to collect: customer email and product SKU.
As many customers will be non-registered users, what would be the best way of capturing this data, and emailing it to the store owner?

I was thinking flags/rules module, or do you think a custom module would be simpler?

Thanks in advance.

There are two similar kind of sandbox module for this particular functionality.

One was started by me - Commerce Stock Notify

Another by itamar - Commerce Stocklist.

Both can be starting point for further development. As I left doing anything else for this as he started it before me, but my module do what you want except mail template which I was supposed to do later.

But now I think, I will spend some time on it & try to release stable soon :)


Include multiple blocks in one responsive menu? It would be really handy to include not just one menu in a responsive dropdown menu, but also the user login block, the main menu etcetera. Is there a way to do that? I have tried several responsive menu modules, but it seems as though I always end up with several different dropdown menus. I only want one (for all).

You may want to investigate Mega menu options.

http://megadrupal.com/blog/7-mega-menu-modules-for-drupal

I've used OM Maximenu before when I wanted a ton of content on the dropdown:

https://www.drupal.org/project/om_maximenu


Change form list default value I want to change the default -select a value- from a text list to a something like -please select a choice-

This is what I have:

  function project_form_alter(&$form, &$form_state, $form_id){
    if($form['#id'] == 'edit-field-gen-list'){
    $form['field_gen_list']['#default_value'] = 'all';
    }
}

It's not picking up the value.

This is the HTML.

In Drupal 8 type-hint $form_state with the FormStateInterface & do not pass it by reference:

hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

See hook_form_alter() for further reference.
I see some confusion on your usage of the $form_id / $form['#id']. Dump your $form_id in the hook & see which is the correct form you want to alter. Because as others have mentioned already: edit-field-gen-list is not your form id but your field_gen_list field id. For example: the form id of the contact Website feedback is contact_message_feedback_form.
Given the HTML in your question, your $form['field_gen_list']['widget']['#options'] will not have a key for 'all'. So adding that as default value will not work unless you add such a key value to the options array

So instead try this:

function project_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    kint($form_id, 'Find correct form id');

    if ($form_id == 'contact_message_feedback_form') { // Change this

        // Add an 'all' key value option
        $form['field_gen_list']['widget']['#options']['all'] = '- All -';

        // Set newly added key 'all' as default value
        $form['field_gen_list']['widget']['#default_value'] = 'all';
    }

}


Using #states visible I am trying to make field_format visible after two select list fields have a specific values selected. I thought be not using 'or' 'xor' that both are required but its not working. this is doing the same thing as using 'or',

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form') {
    $form['field_format']['#states'] = array(
      'visible' => array(
          array(':input[name="field_item_type[und]"]' => array('value' =>     'tv_show')),
          array(':input[name="field_extra[und]"]' => array('value' =>     'bike')),
      ),
    );
  }
}

Here is some example code. Maybe your selector is incorrect?

$form['main']['elem1'] = array(
  '#type' => 'select',
  '#title' => t('1'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);
$form['main']['elem2'] = array(
  '#type' => 'select',
  '#title' => t('2'),
  '#options' => drupal_map_assoc(array('A', 'B')),
);

$form['main']['elem3'] = array(
  '#type' => 'textfield',
  '#value' => t('3'),
  '#states' => array(
    'visible' => array(
      'xor',
      array(':input[name="elem1"]' => array('value' => 'A')),
      // XOR.
      array(':input[name="elem2"]' => array('value' => 'A')),
    ),
  ),
);
$form['main']['elem4'] = array(
  '#type' => 'textfield',
  '#value' => t('4'),
);
$form['main']['elem5'] = array(
  '#type' => 'textfield',
  '#value' => t('5'),
  '#states' => array(
    'visible' => array(
      ':input[name="elem1"]' => array('value' => 'A'),
      ':input[name="elem2"]' => array('value' => 'A'),
    ),
  ),
);

And then the alter function.

function module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'af_aam_aam_form') {
    $form['main']['elem4']['#states'] = array(
      'visible' => array(
        array(':input[name="elem1"]' => array('value' => 'A')),
        // OR.
        array(':input[name="elem2"]' => array('value' => 'A')),
      ),
    );
  }
}


"Limit allowed HTML tags" filter is deleting Ckeditor table styles I'm using the "Limit allowed HTML tags" filter in my text format and put this to the allowed tags: <th style>

Anyway my table styling <th style="width: 60%;"> added in Ckeditor is filtered out. What have I missed?

style="width: 60%;" is an html attribute, not a tag.

  I put this to the allowed tags: <th style>

Therefore, you need to remove the style part and just put table header tag <th> in the allowed tags.


How to assign certain themes to certain to Content Types? I am trying to assign certain themes to certain content types. Is there any way to do this in the admin configurations? I don't particularly want to use a module or modify php code for this.

I know you said that you don't want to use a module, but ThemeKey does exactly what you need. There is no Drupal core functionality that provides this functionality.


Configuration management export blocks from Dev to Staging I created and placed some blocks in my local Drupal 8 Dev site. I exported the full configuration. After I import the configuration into my Staging site I get this error:

  This block is broken or missing. You may be missing content or you
  might need to enable the original module

What do I have to do? And what are best practices for exporting blocks from Dev to Staging and keep Configuration management synced and without errors?

Another approach for synchronizing content that is added as part of development to test and live environments is to use the Default Content module to export the content. It is built for the content to be exported to an installation profile's 'content' folder, and then the module, if enabled, automatically brings the content in when the site is installed.  It is also possible to import the content one item at a time, such as in an update hook, with the below code in your example.install or example.profile:

<?php
/**
* Import a piece of content exported by default content module.
*/
function example_import_default_content($path_to_content_json) {
  list($entity_type_id, $filename) = explode('/', $path_to_content_json);
  $p = drupal_get_path('profile', 'guts');
  $encoded_content = file_get_contents($p . '/content/' . $path_to_content_json);
  $serializer = \Drupal::service('serializer');
  $content = $serializer->decode($encoded_content, 'hal_json');
  global $base_url;
  $url = $base_url . base_path();
  $content['_links']['type']['href'] = str_replace('http://drupal.org/', $url, $content['_links']['type']['href']);
  $contents = $serializer->encode($content, 'hal_json');
  $class = 'Drupal\\' . $entity_type_id . '\Entity\\' . str_replace(' ', '', ucwords(str_replace('_', ' ', $entity_type_id)));
  $entity = $serializer->deserialize($contents, $class, 'hal_json', array('request_method' => 'POST'));
  $entity->enforceIsNew(TRUE);
  $entity->save();
}

Export a custom block with an ID of 8:

drush dcer block_content 8

(If you don't set your profile path in Drush settings you'll have to specify it above.)

And use the resultant export in your example.install file like this:

<?php
/**
* Add the footer block content.
*
* Implements hook_update_N().
*/
function example_update_8001() {
  example_import_default_content('block_content/136efd63-021e-42ea-8202-8b97305cc07f.json');
}

See easily add default content with update hooks for more.