How to add a Custom Serializer to alter the Output of REST EXPORT To the Response/Output of REST EXPORT of a view, I want to add one extra row.

So I created a Custom Serializer in my module.
The path of the file is:

My_Module/src/Plugin/views/style/HindiCustomSerializer.php

Here I extended the Serializer Class from core/modules/rest/src/Plugin/views/style/Serializer.php

And I am trying to override the render() method in my custom serializer like this. I am copying the render() method from original Serializer and adding one extra line from my side.

use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * Add and extra row to the output.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "hindi_custom_serializer",
 *   title = @Translation("Hindi Custom Serializer"),
 *   help = @Translation("Serializes views row data using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class HindiCustomSerializer extends Serializer implements CacheableDependencyInterface{

  public function render() {
    $rows = [];
    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[] = $this->view->rowPlugin->render($row);
    }

    $rows[] = "JUST ADDING AN EXTRA ROW!!";
    unset($this->view->row_index);
    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }
    return $this->serializer->serialize($rows, $content_type, ['views_style_plugin' => $this]);
  }

}

The option to choose the custom serializer MyCustomSerializer should be visible in Format section of view settings.

But its not displaying. Is there any step I am missing? Do I need to add some extra information regarding the serializer in .info file or any such steps needed ?

PS: If I add this line directly to the original Serializer code, I see the extra row coming in the response.

$rows[] = "JUST ADDING AN EXTRA ROW!!";

But of course that's not the correct way.

The plugin was missing the proper annotation (added now in the question). Views plugins use Annotation Discovery.

Adding something like the following solved the problem:

/**
 * My custom serializer
 *
 * @ViewsStyle(
 *   id = "hindi_custom_serializer",
 *   title = @Translation("Hindi Custom Serializer"),
 *   help = @Translation("Serializes views row data using the Serializer component."),
 *   display_types = {"data"}
 * )
 */
class HindiCustomSerializer extends Serializer {
  ....
}

Also worth noting that you don't need to include the implements CacheableDependencyInterface since is already declared by the \Drupal\rest\Plugin\views\style\Serializer plugin which you are extending from.


how to display filed values form People » Account settings » Manage fields I've added few more fields in "Administration » Configuration » People » Account settings » Manage fields". See the attached screenshots for more details.
Now I want to display user's First name & Last name in page.tpl file. I know that name can be diplayed like this "$user->name". But I want to know how other filed values can be displayed. I want to display the fileds First name, Last name, Phone, Address

If you want to display first name and last name of the logged in user, then you can follow the below code snippets.

global $user;

$account = user_load($user->uid);

print "First name:" . $account->field_f_name[LANGUAGE_NONE][0]['value'];
print "Last name:" . $account->field_l_name[LANGUAGE_NONE][0]['value'];

The global $user object does not load the fields which are attached to user profile. So, We need to use function user_load() in code.

If you want to display First Name and Last Name of the user profile, then you need get uid of the user from the arguments.

$uid = arg(1);

$account = user_load($uid)


Multisites placed inside sub site folder? I have my main plain html site in root folder and drupal site in sub site folder. Now I am wanting to create multisites and wonder if  sub sites can reside in drupal sub site sites folder?

www.subdrupal.mainsite.com/subdrupal/sites/sub2drupal  etc.

Or must I start again as it can only be www.subdrupal.mainsite.com/sites/subdrupal ?

Good question. It is possible to run drupal multisites as a subdirectory even if your Drupal installation is in a subdirectory itself.

  Side note: the /sites/ directory in your examples is not necessary.

Given that your main Drupal install is accesible at domain.com/drupal the solution is to use symlinks to tell your webserver that the document root for domain.com/drupal/multisite is the same as your main drupal install (domain.com/drupal).

The first step is to create a directory for the multisite. The syntax is a little different for subdirectory multisites: domain.com.multisite. So, inside your /sites directory, you will have something like this:

-|/sites
--|----/all
--|----/default
--|----/domains.com.multisite

Place a copy of default.settings.php in domains.com.multisite and rename it to settings.php.
Then create the symlink described above by running the following command from your main website's docroot (not Drupal's docroot, the main website's docroot - usually public_html or something similar):

ln -s [drupal-directory-name] [multisite-directory-name]

Or, using the names in our example above:

ln -s drupal multisite

See Drupal's multisite documentation for more information.


How to style overall form Problem

I have a lot of pages with standalone forms. Because of webdesign issues I ended up using the form element to style.

The problem is certain actions cause the form-id to change.

<form id="user-profile-form">

 //a failed file upload causes the above to become

<form id="user-profile-form--2">

Which breaks a lot of my css.

An example form HTML profile:

<form id="user-profile-form" accept-charset="UTF-8" method="post" action="/drupalie/user/184/edit" enctype="multipart/form-data">
    <div>
        /*form is built in here*/
    </div>
</form>

Is there a way to add a CSS class to my form, add a class to the empty div which surrounds all the form elements or as a last resort, prevent the form increment on certain forms.

You can add classes you need directly to your form with #attributes. This is example directly from the official documentation:

$form['#attributes'] = array('class' => array('search-form'));

If it's not your code that creates form, you can add this with hook_form_alter(). Just be careful not to overwrite any attributes or classes that might be already in place:

$form['#attributes']['class'][] = 'search-form';


Token's available "Replacement patterns" nested table should only be displayed on-demand The Token module provides hooks to other modules to serve their own tokens. Multiple modules that support Token integration can generate a really huge nested table tree when displaying the available tokens in the field settings:

This can lead to out-of-memory issues in Views settings or regular field settings:

Earlier I created an issue related to this problem: http://drupal.org/node/1836264. Until a possible solution comes there (e.g. a patch), I would like to solve it my own (it doesn't matter if I temporarily have to "hack" Token's core): I would only like to load this table with the available tokens "on-demand" with AJAX or any other possible solution.

Do you have any ideas how to solve this?

The default token tree can contain many thousands of lines of HTML, and the corresponding Javascript listeners and functionality can totally break things memory wise (or just give you a darn laggy experience). Plus it can confuse the heck out of site administrators.

These issues refer to current developments for loading the token tree 'on demand' or via a popup:

http://drupal.org/node/1684984
http://drupal.org/node/1229568

And OP pointed out in his comments, the Token tweaks module lets you set a depth limit for the token tree, which seems to have solved his memory problem.


How do I change the price of a flat rate shipping fee depending on a type of Product? I am trying to create a different price for shipping of heavy items. I have light and heavy items and they are categorized via taxonomy heavy/light. How do I change the shipping price via Shipping Rules to detect if its a heavy or light item?

figured it out .. but not sure if its the best way i think it is. for reference:

created a light & heavy shipping flat rate option.
added in new conditions matching if its a heavy or light via taxonomy terms.
added in an extra condition for LIGHT shipping to make it disappear by detecting if there is a heavy item in the cart by doing a negate on the same above condition.

To make this work you will need https://drupal.org/project/commerce_rules_extra

As you need the Total quantity of selected product comparison condition to loop through the entire cart and match what you need in accordance to the terms you select.


What are the Steps to Translate the Current Search Block and Facet Search block(s) I have been unable to configure things such that the Current Search Block or Search Facet block(s) have their strings show up in the Translation tool at :

  admin/config/regional/translate/translate

They are however available in options in the translation tools filter

I do have Facet API Translation installed

I have tried refreshing String translations at:

  admin/config/regional/translate/i18n_string

And I have tried specifying the blocks as translatable on their respective blocks configuration forms (the form states that because the module is responsible for the content of the block that only Title translations are possible ... this is obviously not what I need to do to translate the blocks contents)

What are the Steps required to Translate Facet Search Block(s) and Current Search Block ?

I was able to solve this issue; however not in an ideal way:

see: https://drupal.org/node/1478908

see: https://drupal.org/node/1387504

see: https://drupal.org/node/1376786

see: https://drupal.org/project/facetapi_i18n

By implementing hook_block_view_alter and passing pieces of the markup to the translation function.

function MY_MODULE_block_view_alter(&$data, $block) {
    if($block->module == 'current_search'){
            $original_markup = $data['content']['results']['#markup'];
            $original_filtered = strip_tags($original_markup);
            $results_count_int = filter_var($original_filtered, FILTER_SANITIZE_NUMBER_INT);
            if($results_count_int){
                    $new_text = t('Search found @count item(s)', array('@count' => $results_count_int));
                    $new_markup = "
$new_text
";
                    $data['content']['results']['#markup'] = $new_markup;
            }
    }

}


content type view into hidden region I would like to create and display content type in a hidden region. The only reason to hide the region is to prevent moving the location. It is for flash file header banner that will be changed by a user by adding or modifying the content type. If it must be a block, then I suppose it doesn't much matter if the region is visible or not. Any suggestions?

If I understand correctly what you want to achieve, you could also try the Boxes module or even Panels and Panels Everywhere.


How can I bulk delete Menu Itemes in Drupal 8 is it possible to bulk delete and bulk edit menu items in Drupal 8?

Question for Drupal 7: Any way to bulk delete menu items?

Bulk delete

there is module https://github.com/robdecker/menu_delete which you can use that provides checkboxes for easier delete of menu items.

its at the time of this writing missing a SELECT ALL feature which would make it even more helpful

its proposed to be included in core but there is no sign that it will https://www.drupal.org/node/2772961

so you can install it and take advantage of it using following commands

cd modules
git clone https://github.com/robdecker/menu_delete.git
drush en menu_delete -y

and then go into your menu and you should have available checkboxes and delete selected button

Bulk delete alternative process

1. create a custom menu
2. edit items that you want to delete and try to put them under 1 parent (or few parent items)
3. edit those parent menu items and reassign them to the custom menu
4. delete the custom menu

Bulk edit

For bulk edit the https://www.drupal.org/project/menu_editor module is not yet ported to drupal 8 but it will be a good candidate if it gets ported


Some basic questions about creating a webform handler from the module webform_example_handler I'm "cutting my teeth" in Drupal 8 on the Webform module so these are going to be rather naive questions.

I need to programmatically fill a URL field in the form with an XML file that
I generate from the other data in the form and do it just before the submit
so that the form is complete. To do so I figured using a webform handler is
the way to go and I have been using webform_example_handler as my
template.

Now for my ridiculous naivety, just a few basic questions:

In webform_example_handler.schema.yml the first line is:
"webform.handler.example". Is this a standard Drupal construct of <webform>.<handler>.<my_module>, or
something specific that must be followed set by the webform module
or am I completely off base on how this is derived?

I would guess that for my
module the line would be: webform.handler.dis_doc_gen?

The "webform.webform.webform_example_handler.yml" file: could someone explain the parts? In my module would it be: webform.webform.dis_doc_gen.yml ?

Last: I have built my webform through the interface so I assume that I don't
need the file "webform.webform.webform_example_handler.yml" as that would
only be for creating a webform from a yml file upon installing the module as
far as I can tell. However, is there something in my webform that I need to
set so that it knows about my
".../dis_doc_gen/src/Plugin/WebformHandler/DISDocGenWebformHandler.php"
handler?

Could someone please tell me what key thing(s) I need to do to make that connection or is that all automatic as long as you clear the Plugin cache? (I just discovered that cache through the "Admin Toolbar" module).

I realize this could be done through one of the webform hooks but I would rather use a handler as part of getting familiar with Drupal 8 in general.

Could someone please tell me what key thing(s) I need to do to make
  that connection

There are 4 ways that you can tell Drupal that your plugin exists.

You can read about the other 3 at D8 Plugin discovery

In this case Webform uses:

  AnnotatedClassDiscovery

  The AnnotatedClassDiscovery class uses name of the annotations that
  contains the plugin definition, e.g., @Plugin, @EntityType, in plugin
  docblocks to discover plugins, minimizing memory usage during the
  discovery phase. The AnnotatedClassDiscovery class takes an argument
  in its constructor, $subdir, which specifies the
  sub-directory/sub-namespace for this plugin type. The
  AnnotatedClassDiscovery class scans PSR-4 classes inside those
  sub-directories of Plugin folders to find plugins (see a
  "Annotations-based plugins").

Side Note: Entities and blocks also use this "annotation" method.

This "annotation" is seen in webform_example_handler/src/Plugin/WebformHandler/ExampleWebformHandler.php

Yes, this info is inside a comment block, weird, but that's just how it works.

  In webform_example_handler.schema.yml the first line is:
  webform.handler.example. Is this a standard Drupal construct of
  <webform>.<handler>.<my_module>, or something specific that must be
  followed set by the webform module or am I completely off base on how
  this is derived?

Wrong, otherwise it would've been named webform.handler.webform_example_handler.

It's actually webform.handler.<WebformHandler_id> (The ID you use in the annotation).

This is because your module can have multiple plugins, so it makes no sense to use the module's name here.

The webform.webform.webform_example_handler.yml file: could someone explain the parts? In my module would it be: webform.webform.dis_doc_gen.yml ?

Assuming your module is named dis_doc_gen, correct.

  Last: I have built my webform through the interface so I assume that I
  don't need the file webform.webform.webform_example_handler.yml as
  that would only be for creating a webform from a yml file upon
  installing the module as far as I can tell

Correct, anything inside the /install folder, runs on install and that file is creating a form. Since you created one via the UI, you don't need this in your use case.


How to make certain nodes available to anonymous users? I am having a site that hosts a number of content items (nodes) that are available to registered users. We would like to make some of those data available to anonymous users, too, via a view. I have encountered so far two issues:

The nodes have attachments and currently the attachments are saved
in Drupal's private storage. When an anonymous user will try to
access the attachment directly, they will see an error.
Currently, I deny to anonymous users the permission to View published content. Thus, when a user clicks a link to a node, he will see an Access Denied error. This can be perhaps solved by using Content Access.

The solution I can think of is to clone the nodes I want to make public and make public their cloned counterparts but I dislike data copying as a practise. Any other ideas?

Just add a field to your nodes, similar to the "checkbox" as described in the question "How to allow users to post content and easily overrule its default access settings?". That field is used when creating a node, to indicate if the node should be viewable by anonymous users also (the default probably being "no").

With that, you could use the Rules module and the Content Access module to implement what you're looking for, similar to what I described in my answer to that same question mentioned above.

This approach should work for brand new nodes being created, while it should also work if you add such field to existing nodes. Though you'd have to experiment a bit to see which Rules "Event" is the bet fit in your case (I'd assume that node create and/or node update is what you'd need).

If you only want "some of those data" to be available to anonymous users, then you may want to add the Field Permissions module also (so that only the relevant fields can be viewed by anonymous users.

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


Add an Administrator? I've added a new Drupal user, so how do I make them an administrator of the site?

I can't seem to find a setting to do this? User roles are Authenticated and Anonymous.

But the default login username definitely has some kind of administrator permission. How do I grant this same privilege to a new user?

In Config > People there is setting Administrator role which is a select menu, but it only has the disabled option :S

The 'super user' (user 1) has privileges that you won't be able to completely emulate for other users. There are hard-coded bypasses in functions like user_access() that allow that user to do pretty much anything they want.

Permissions are granular in Drupal, so the idea is you give a certain role a certain set of permissions based on what they should be allowed to do.

To get as near as possible to another role being able to do everything the super user can, you just need to go to admin/people/permissions and tick all of the permission boxes for the administrator role. I'd advise checking each permission (if only this once) as you do this, to make sure you're definitely giving that role the access you expect.

When you then assign the administrator role to other users, they'll essentially be able to do anything on the site that you've allowed them to do through the permissions page.


Pass nid variable to Ubercart order in D7 How can I pass a node's nid variable to Ubercart so that when the user pays for publishing his node, the nid shows in the cart?

I tried to add a field to the Ubercart Order fields, with widget node reference which is passed by the URL. When my user clicks on "Pay for node" link, it sends him to the Ubercart "node" product page "pay?23" 23 being the node they are paying for. When the user presses Add to Cart, I cannot see this value 23 in any of the user's order or checkout details. How can I get this value attached to the order?

I've googled for a while now and cannot find anything about this for D7. Any help will be much appreciated!

If you are using Cart Links (/admin/help/uc_cart_links), you could pass a value for a text-field type of attribute on your product.
You'd have to add an attribute to the product node, and hide it via css or form_alter method on the product view page so that they couldn't overwrite it or delete it.
When they add attribute to the cart with the cart link, you can feed in the value with the url parameter like ( /cart/add/e-p23_q5_aThisNiceEscapedString. ).
Note that you can't just pass an integer to it, or Cart Links will think you are passing the AID (attribute ID)


How to switch language on login based on user profile? Is there a way when a user login to automatically switch him in then language setup in his user profile.

In "Configuration -> Regional and language -> Languages -> Detection and Selection" enable detection method "User -> Follow the user's language preference." and drag it to the top of the list. Do same in both sections: User interface & Content language detection.

UPDATE:
As an alternative to GUI method you can add the code pasted below in your theme's template.php file (but first, disable detection of user language in Language settings).

The code below uses hook_user_login which runs when the user successfully logs in and passes the user object as an argument. User language is then used for a redirect (drupal_goto).

function yourthemename_user_login(&$edit, $account)
    {
      // get current user's language from the user account
      $user_language = $account->language;

      // if account has no preferred language set - do nothing
      if (!$user_language) {
          return;
      }
      // if the language is set - do additional checks and then redirect
      else {
        // get a list of installed languages
        $languages = language_list();
        // check if language retrieved from user account exists
        if (!isset($languages[$user_language])) {
            return;
        }
        else {
          // verify if language is enabled
          if (!$languages[$user_language]->enabled) {
              return;
          }
          else {
            // if enabled - redirect to user profile in preferred language
            $user_profile_url = drupal_get_path_alias('user/' . $account->uid);
            drupal_goto($user_profile_url, array(
                'language' => $languages[$user_language],
            ));
          }
        }
      }
    }


How to render a text with linebreak saved from a textarea form? Unfortunately I haven't found anything on the web with this specific problem.

I have a field (text, formatted, long) and a form with a textarea element that should save the entered text to this field.

Now I want to render it in my twig template. I access the value like this in my controller:

'text' => $node->field_text->value

And I render it in twig normally:

<p>{{ text }}</p>

But whenever I entered a new line by pressing enter in the textarea, it doesn't render the new line. The same thing in the CKEditor when I edit the node and look at the content, there's no new line.

I'm sure that there's a linebreak though, because when I dpm() this value, it prints that.

I tried putting the value in a '#markup' => $text render array, but it was the same. How can I render this new line?

I tried putting the value in a '#markup' => $text render array, but it
  was the same. How can I render this new line?

Yes, you need to put the text in a render element, but for a formatted text field the correct element is processed_text:

'text' => [
  '#type' => 'processed_text',
  '#text' => $node->field_text->value,
  '#format' => $node->field_text->format,
],


How to use Views/Contextual Filters with a referenced entity So, I have a site with two content types:

Sermon Series
Sermon

The sermon content type has an entity reference field selecting a sermon series that it relates to.

On the page for a sermon series, I am attaching a view to list all the sermons that have the "Sermon Series" field set to that particular series.

Ideally, I'd like to only create one view that will work for every sermon/sermon series.

I know that I need to use contextual filters to do this, but I'm having an exceptionally difficult time wrapping my mind around what settings I need to use, and spending several hours trying stuff out has been to no avail.

Could someone please explain the process to me?

For bonus points- I'd also like to use a view on the sermon page to display an image from the referenced sermon series. I am also not exactly sure how to set this up.

To help clarify, here's the workflow that I want to end up with:

User creates a new "Sermon Series" with a title and an image.
User creates a new "Sermon", and they can select which "Sermon Series" it belongs to.
The new sermon shows up in a list on the corresponding "Sermon Series" page.
The image related to the "Sermon Series" shows up on the "Sermon" page.

Did you try to use module EVA: Entity Views Attachment it provides a Views display plugin that allows the output of a View to be attached to the content of any Drupal entity. The body of a node or comment, the profile of a user account, or the listing page for a Taxonomy term are all examples of entity content.

There is a screencast on how to use that module

hope that helps for you...


Helper to get the raw value of a node field? I wonder if something "core" already exists that gives me the raw value of a field inside a node. For that matter I wrote this little helper, but it seems too strange not to be able to do it with a core function:

function mymodule_get_node_field($node, $name, $lang = 'und', $key = 'value') {

  if (substr($name, 0, 6) != 'field_') {
    $name = "field_{$name}";
  }

  if (!is_object($node) || !isset($node->{$name}) || !isset($node->{$name}[$lang])) {
    return null;
  }

  return $node->{$name}[$lang][0][$key];
}

The only thing I know is field_get_items().

Your function makes a lot of assumptions that don't work for a core function.

Not all fields are prefixed with field_, only those created through the UI. body for example not.
Some fields have multiple values, your function only returns the first.

If you want a function that makes these assumptions, you could write a simple wrapper for field_get_items() that takes care of that.


Template suggestion doesn't work with a custom menu link (custom route) In a module I have created a custom link by creating a custom route inside the mymodule.routing.file.yml and the mymodule.links.menu.yml file.
In my theme.theme file I have defined a hook_page_alter to add a template suggestion. With the debug mode and in the html code of the custom page, I see the proposed template suggestions.

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
* page--mycustomtemplate.html.twig
x page.html.twig

I have build a new template with this name 'page--mycustomtemplate.html.twig'. After clearing the cache, the new template isn't called, and the default page template is always actived.

Did I forget something?

I'm guessing you put the template in your module folder and not in a theme?

You need to register the template with something like this in your .module file:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  $theme['page__mycustomtemplate'] = [
    'template' => 'page--mycustomtemplate',
  ];

    return $theme;
}


Translation issues-How can we set admin in default English language in multilingual site Possible Duplicate:
  Do not translate the admin area / How can I set the language of the admin area to English?

I have a problem with a multilingual website.I used English and Arabic as two languages .Done all the laguage settings.But when i tried to translate a basic page content to arabic ,the whole admin turned to arabic and showed rtl mode.I need to fix it asap.Please guide me.

NB: i have all the modules related to multilingual site at local and transferred the whole files and same database to server.At local it was working fine.But at live it won't!.please

Try setting your language detection to be "user preference" first.  That way your account setting will override any other detection.


Hiding block title when customizing I would like to hide the block title when customizing a block, but I didn't find any solution on the internet, Can you please help me?

function custom_theme(&$existing, $type, $theme, $path) {

  $hooks['user_login_block'] = array(
    'template' => 'templates/user_login',
    'render element' => 'form',
    // other theme registration code...
  );
  return $hooks;
}

You can do it easily directly in the configuration page of block by adding <none> in the title field setting.


Views slideshow with multi value imagefield I have created a content type and added an image field with unlimited option. Now I want to setup a views slideshow. Some nodes have single whereas others have multiple images. So my slideshow should show single image as well as all the images if the node has multiple images grouped together.

Try field slideshow. It bypasses views entirely, which makes it easy when all your images are in one node.

I don't think it works with the media module, yet, and you have to set your field type has to be "image". You select the slideshow options in the display fields portion.


how would i go about creating variable menu links I would like to display different menu links on each page depending on the content and relevance of each page. How would I do this?

You should try Context

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.


Making user reference field in Drupal 7? I have searched in Google with queries like "User reference drupal 7" or "User taxonomy vocabulary drupal" "user field drupal 7" "cck drupal 7" but I couldn't find any way to make a field that links for a user profile page... Do you know how to make this as a simple field can be done with CCK in Drupal 6? thanks.

Another alternative to References is the Entity Reference module. It can do user reference fields as well.


How to relate the user table with the fboauth table to show up who's logged in through fb? I have created a view which shows up the user details like username, email, active(user), accepted challenges in a tabular format. Now i want to include a column to it which shows up the users who uses their fb account to login to the website.I have used fboauth module to allow users to login to the website through their fb account and i am unable to add a relationship which relates the users table and the fboauth table. Can anyone suggest me a way to resolve this?

I am using drupal 7

You have two options.

First is that you can add a field to the USER, named as fb_user(Keep the default value as "no"). Now look into the fbouth code where a user is being created. Write a sql query there using Database API to update the field fb_user as "yes". Now you can easily add the field in views to find out FB users.
Create a custom module. Inside that write a hooks_views_query_alter:-https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
Custom query in Views?


Creating a Paragraph type programmatically I have a custom module that is installed on a number of sites. In an hook_update_n function I would like to add a completely new Paragraph type (not actual instance of a Paragraph) to every site, using the same configuration.

Adding or updating fields to an existing type is well documented, but I can't find out how to create an actual type (node or paragraph) programmatically.

There are two issues here. To start with, the config files for a paragraph type should be placed in the config folder of the module, for which there is now a console command. See Export Paragraph bundle with Drupal Console

Then there is the general problem, how sites can update the config of an already installed module. You'll find different solutions in this topic How do I update the configuration of a module?


Update theme table using callback function in Ajax I have two elements in my form: a select and a table element. Everytime onchange event is triggered on select element, I want to update the values in my table. I want to do query and change the values of '#rows' in the table.

function myid_print_user_page_form($form, &$form_state)
{
    $form = array();
    $form['myid_print']['option'] = array(
        '#type' => 'select',
        '#options' => array(
            0 => t('All'),
            1 => t("Printed ID's"),
            2 => t("Unprinted ID's"),
        ),
        '#default_value' => 0,
        '#ajax' => array(
            'callback' => 'myid_print_all_submitted_id_callback',
            'wrapper' => 'myid_table_wrapper',
        ),
    );

    // Build the sortable table header.
    $header = array(
        'id_number' => array('data' => t('ID Number'), 'field' => 'id_number','sort' => 'asc'),
        'student' => array('data' => t('Student'), 'field' => 'student', 'sort' => 'asc')
    );

    //Get the node data.

    $query = db_select('student', 't1',array('target' => 'import'));
    $result = $query
        ->fields('t1', array('studid','lastname', 'firstname', 'middlename', 'extname'))
        ->condition('t1.id_status',1,'=')
        ->distinct()
        ->execute();

    //Build the rows.
    $rows = array();
    foreach($result as $record){
        $rows[$record->studid] = array(
            'id_number' => $record->studid,
            'student' => $record->firstname . ' ' . $record->middlename . ' ' . $record->lastname . ' ' . $record->extname,
        );
    }

    //Build the table
    $form['table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#prefix' => '
',
        '#suffix' => '
',
    );
    return $form;
}

I'm stuck here, I don't know what to put in my callback function.

function myid_print_all_submitted_id_callback($form, $form_state)
{
    //Do query here and put the query results in the table.
}

Any help would be very much appreciated.

You can access the values of the form elements using the $form_state parameter. So when you have the value of the select element, you can perform the query as required, build the table using theme_table and return the result. The returned result can be replaced or appended to the ajax wrapper defined in your form.


Contact form SOMETIMES doesn't work I'm using the contact form, smtp module and secureserver as the mail server. When I run tests via the smtp settings page. Everything works as it should. When I use the contact form, SOMETIMES I get an error other times I don't. After reviewing the drupal log as to what the issue might be. I get the 2 following error for the ones that don't mail out.
I get this smtp error;

Error sending e-mail from *@something.com to *@something.com : The following From address failed: *@something.com

SMTP server error: Sorry, your envelope sender is in my badmailfrom list.

and another error which simply states it couldn't send the email. After running some tests and reviewing the mail headers of the emails that did go through. It seems as thou it sends FROM the email address the user is inputting. This to me like the server would deny it because this essentially is a 'spoof'. On the site information email, we are using "info@ourdomain.com". On the smtp settings, we are using a "donotreply@ourdomain.com". I tried a test by changing the dnr email to the info and it still has the intermittent fails.

Update: I've narrowed down the problem to a Godaddy issue. We don't use the 'web' hosting server as our email server. We use their "Email" server which is the "secureserver" most people have problems with in the threads I've read. We ended up switching over to gmail and everything works as it.

@Citricguy: Naw, we aren't blacklisted. It's just that they have several configuration issues with those email servers. To the point that their own techs don't know what they are talking about half the time..

You may have been blacklisted by the server you're try to send mail to.  Check this first.

To help from being marked as spam send from an address ending with your domain name.

For example: do-not-reply@example.com or notifications@example.com

Then you can set the "Reply-To" header email address to your users email using hook_mail().

Something like this maybe?

$params['reply-to'] = $user->mail;

function HOOK_mail($key, &$message, $params) {
    switch ($key) {
        case 'your-key-here':
            $message['Reply-To'] = $params['reply-to'];
            $message['subject'] = $params['subject'];
            $message['body'] = $params['body'];
            $message['headers']['Reply-To'] = $params['reply-to'];
            $message['headers']['Return-Path'] = $params['return-path'];
            break;
    }
}

It has been forever and a day sense I've looked at this last, but you may want to scope out RFC822.

Note that ['Return-Path'] is important here as well if you monitor emails for bounces (hard/soft/etc).  Where ['Reply-To'] directs replies, I believe ['Return-Path'] directs bounces and errors.


How to get CSS to target new nodes being inserted? I am customizing nodes for a blog entree's so they have a certain aesthetic look to it. However, I ran into a problem.

I can enter custom CSS code to style the nodes for already existing ones and set them with classes, but if someone is going to create a new node on the site, the blog CSS doesn't appear because I have to go in to each one and constantly hand-code it.

Obviously this is time-consuming and not the right way to go about it, because anyone who creates a blog would have to wait for me to style it for them. Is there a way where I can make a CSS code that will keep the look and feel every time someone creates a new blog entree?

I'm not sure I get the scenario.
What if you apply your css to both old and new classes?

Example

.old_nodes .content, .new_nodes .content {
   color:red;
}

This will give same style to both new and old nodes.


How do I make an object available as a token? I have created a custom token. Inside my token's code, I'm getting a node object. I want to give the users the option of displaying this node's properties. So, for example, assuming that my token's name is [mycustomtoken] I want them to be able to write:

[mycustomtoken:author] so that they get the node's author or

[mycustomtoken:title] to get the node's title.

Is there a way to do this in Drupal?

Yes, by making your token a dynamic token in HOOK_token_info() and using the provided name during HOOK_tokens() to dynamically create your replacements.

Example

function HOOK_token_info() {
  ...

  $tokens['mycustomtoken'] = array(
     ...
     'dynamic' => TRUE,
  );

  ...
}

function HOOK_tokens($type, $tokens, array $data = array(), array $options = array()) {
  ...

  if ($type == 'mycustomtoken' && !empty($data['node'])) {
    $node = $data['node'];

    foreach ($tokens as $name => $original) {
      if (isset($node->{$name})) {
        $replacements[$original] = $node->{$name};
      }
    }
  }

  ...
}


Bartik theme main menu I am dabbling fresh with Drupal 7 and so far having little success with getting the Menu to behave the way I want it to. My CSS and PHP basics are strong, but understanding Drupal's system is in itself a huge challenge and hence my doubts.

For those acquainted with the Bartik theme, the main menu defaults itself in the header.

I am trying to create a floating/persistent menu that encapsulates the entire width of the website. But I am not sure where I need to go in and make the required changes.

One option I have is to remove the main menu from the Bartik header and then introduce the main menu block in the 'featured' region. Here the menu is rendering itself horizontally instead of vertically the way i want it to be.

Essentially the question is, How do I alter the main menu in the Bartik theme? Where do I need to get in and make changes.OH, and I have sub-themed it, just to let you know.

Take a look at the module Nice Menus or Superfish menus.  Both offer a lot of flexiblity and control for managing menus.  In both cases you will configure the module to provide some menu blocks and configure the blocks to attach them to your main menu.  You will then put the Nice Menu (or Superfish) block where you want it and hide the main menu block.  (I like superfish)


Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'? Is the use of the $GLOBALS array in Drupal in anyway 'less secure' or 'bad practice'. Like using:

$GLOBALS['user']->uid

instead of

$account->uid

if it were avialable?

Thanks.

Directing using

global $user
$user->uid

adds a new variable to your current scope, which adds potential for misuse and other accidents.

Using

$GLOBALS['user']->uid

can be seen as a safety precaution.  You can still mess things up, but it is somewhat harder, and you don't introduce a new variable.

However, directly poking around in the $user object is bad in a lot of cases, especially explicitly using $user->uid.

Whenever possible, you should leverage the API.  For example, use

if (user_is_logged_in()) { ... }

instead of

global $user;
if ($user->uid) { ... }

and use user_access() instead of using $user->roles.

One place where explicit $user->uid use may be needed is with database queries, though that can be lessened somewhat with EntityFieldQuery->addAccount and db_select->addtag('node_access').


cannot validate custom field widget for user profile field when editing node I have defined a field widget and set #element_validate to validate the input. This works fine when I create an account, but when I update the account, the field is not validated and does not even save the changes. It is as though the field doesn't exist

I got around it by attaching the validation in hook_form_alter:

function referrer_widget_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "user_profile_form") {
        $form["field_who_referred_you"]["#element_validate"] = array('referrer_widget_field_widget_validate');
    }
}


Check if the user is logged-in in a theme In Drupal 7 we can simply check if the current user is logged-in in a theme by checking $GLOBAL['user']->uid or  using user_is_logged_in().

How can I check if a user is logged-in in a page template, in Drupal 8?

A solution is to manually check in hook_preprocess_page(), but since this is very popular, I think  Drupal provides something by default for the Twig theme engine.

If you just to check the current user is logged-in, you can use $variables['logged_in'], which is generally available in all the template files.

For example, the mark.html.twig file uses the following code, although the only documented variable is status.

{% if logged_in %}
  {% if status is constant('MARK_NEW') %}
    {{ 'New'|t }}
  {% elseif status is constant('MARK_UPDATED') %}
    {{ 'Updated'|t }}
  {% endif %}
{% endif %}

The variable is explicitly documented in other template files, such as html.html.twig, page.html.twig, and node.html.twig.

The variable is available in all the template files, since it is initialized in _template_preprocess_default_variables() that invokes user_template_preprocess_default_variables_alter() (an implementation of hook_template_preprocess_default_variables_alter()), which contains the following code.

  $user = \Drupal::currentUser();

  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = $user->hasPermission('access administration pages');
  $variables['logged_in'] = $user->isAuthenticated();

_template_preprocess_default_variables() is called by template_preprocess(), which is the function called for theme hooks implemented as templates; this guarantees the variable is available in all the template files.

Keep in mind that macros don't have access to the current template variables, so trying to access logged_in in the code of a macro would not have any effect.
Between the template files used from Drupal core modules, the ones using a macro are:

menu.html.twig

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

book-tree.html.twig

{% macro book_links(items, attributes, menu_level) %}
  {% import _self as book_tree %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ book_tree.book_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

menu--toolbar.html.twig

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

For example, changing the last macro with the following code would not have the expected result.

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          logged_in ? 'menu-item--logged-in-user',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}


Message - Item already in cart (commerce) I want to disable the ability of adding a product twice to the shopping cart.

Is there a way to prevent or prompt a message when a user tries to add the same product twice?

<?php
/**
 * Implements hook_form_FORMID_alter().
 */
function mymodule_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $product_ids = mymodule_get_products_in_cart();

  $line_item = $form_state['line_item'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);
  if ($product->type == 'program') {
    if (in_array($product->product_id, $product_ids)) {
      // Product is already in cart! We only want to allow a quantity of 1,
      // so disable the submit button and change its text accordingly
      $form['submit']['#disabled'] = TRUE;
      $form['submit']['#value'] = t('Already in cart');
    }
  }
}

/**
 * Return the product_id values for all products in the cart
 *
 * @return
 *  An array of product ids
 */
function mymodule_get_products_in_cart() {
  $product_ids = &drupal_static(__FUNCTION__);

  if (!isset($product_ids)) {
    global $user;
    $product_ids = array();
    $order = commerce_cart_order_load($user->uid);
    if ($order) {
      $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
      foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
        $product_wrapper = $line_item_wrapper->commerce_product;
        $product_ids[] = $product_wrapper->product_id->value();
      }
    }
  }

  return array_unique($product_ids);
}
?>


Registration problem I was testing my users accounts on my site, and login works fine for my admin account I created with MySQL in terminal.

But when I try to create a new account with the registration form I have, it shows the succeed message I created:

  Thank you for registering

Still the succeed message is shown, the account isn't created and an error occurs:

  Unable to send email. Contact the site administrator if the problem
  persists.

Unable to send email. Contact the site administrator if the problem persists.

This error is due to email sending failed.

You can use SMTP Authentication Support module for sending email.

  This module allows Drupal to bypass the PHP mail() function and send
  email directly to an SMTP server. The module supports SMTP
  authentication and can even connect to servers using SSL if supported
  by PHP.

You can take the picture as reference for SMTP configuration.


Permissions to see all users products, not just the orders on UberCart I am trying to figure out what permission in ubercart to set that would allow a user to see just the products they put in.  It show them orders but not a list of their own items. Any help?

The permission manage products must be turned off. The permission for to create a product, edit and delete own product must be turned on.


How to alter commerce order view access? When viewing an order, I want to do checks per order, whether the user may view that order or not.

function my_commerce_entity_info_alter(&$entity_info) {
  $entity_info['commerce_order']['access callback'] = '_my_commerce_commerce_order_access';
}

function _my_commerce_commerce_order_access($op, $entity = NULL, $account = NULL) {
  return $entity->id == 99; // just for example
}

The above did not work.

I didnt find anything like entity_access_alter or similar.

What do I do wrong?

You should be using hook_commerce_entity_access_condition_ENTITY_TYPE_alter() for commerce orders.

You receive the following parameters:

$conditions: The OR conditions group used for the view access query.
$context: An array of contextual information including:

account: the account whose access to view the entity is being checked
entity_type: the type of entity in the query
base_table: the name of the table for the entity type

So it becomes:

hook_commerce_entity_access_condition_commerce_order_alter(&$conditions, $context) {
  // If we are not allowed to view the order, leave.
  if (!user_access('some_permission', $context['account'])) {
    return;
  }

  $orders = array(99);

  // add a condition
  $conditions->condition(db_and()
    ->condition($context['base_table'] . '.order_id', $orders, 'IN')
  );
}


Rendering a Block Region in My Custom Theme I am having my custom theme. In the theme.info i have a region latest defined

regions[latest] = Latest

How do i print that region in my theme? Is the below code correct?

<?php print render($latest);?>

I tried dragging the Recent Posts block to this, but nothing appears. What am i doing wrong?

clear your theme cache to see your custom regions working: http://drupal.org/node/337176

Also see this link to review if something more is missing in your process: How-to create custom regions in a theme?


Creating a page only to be accessed by registered users at my site tobynews I have users that would be registered as an "author." What I'd like to do is create a page such as an "Author's Resources" page that would only be accessible by someone who is registered as an author through the site. I'm not exactly sure how to approach this, other than trying to connect to the database's user table with a form. Any help is greatly appreciated.

You could do that using Drupal's role based access control system.

For example, assign the role of "author" to the author users.
You can then restrict access to the "Author Resources" page by user role.
e.g

Create a page using the Views module and adding an access restriction.
Create a page using hook_menu and restrict access to that role in the "access callback"


How to write a property callback for a custom field to use with the Entity module I have a custom field with multiple values. I would like it to work with the Entity module. I need to create the correct property_callbacks in hook_field_info(). My field schema looks like this:

'ref' => array(
  'type' => 'varchar',
  'length' => 32,
  'not null' => TRUE,
),
'title' => array(
  'type' => 'varchar',
  'length' => 255,
  'not null' => TRUE,
  'default' => '',
),
'description' => array(
  'type' => 'text',
  'not null' => TRUE,
  'size' => 'big',
),
'weight' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 0,
),
'status' => array(
  'type' => 'int',
  'unsigned' => TRUE,
  'not null' => TRUE,
  'default' => 1,
),

Does anyone know how to actually do this? There is very little documentation around for it.

Kind of :) ... if its just numbers and strings you can cheat a little. I added some basic integer columns to the User table and wanted EntityAPI and views etc to be aware of them and did the following:

/**
 * Implementation of hook_entity_property_info(). This dpeends on the EntityAPI.
 *
 * This defines the properties/attributes/"fields" of our Entity regardless of
 * whether they are drupal Fields or custom data (in the base table).
 */
function dew_nagging_entity_property_info_alter(&$info) {
  $properties = &$info['user']['properties'];
  $properties['dew_survey_count_to_complete'] = array(
    'label' => t('Number of Surveys to Complete'),
    'type' => 'integer',
    'description' => 'When a student logs in the system derives how many surveys they must complete. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_count_to_complete',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_survey_completed_count'] = array(
    'label' => t('Number of Completed Surveys to Date'),
    'type' => 'integer',
    'description' => 'This is a count of the completed surveys completed by a student in real-time. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_survey_completed_count',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  $properties['dew_surveys_all_completed'] = array(
    'label' => t('Has the student completed all their Surveys?'),
    'type' => 'integer',
    'description' => 'This is a boolean indictator (0,1) of whether or not a student has completed their surveys. We store this value to make sending the nag email business logic easier.',
    'schema field' => 'dew_surveys_all_completed',
    'getter callback' => 'entity_property_verbatim_get',
    'setter callback' => 'entity_property_verbatim_set',
  );
  return $info;
}

entity_property_verbatim_set and *_get just pull the field from the database if $info['schema field'] is defined.

I also had to make the DB changes in my .install file with db_add_field() for each database column. I also had to notify EntityAPI of my schema changes to the user table via hook_schema_alter(). All these DB schema fields and EntityAPI meta data field defintions must correlate properly.

if its more complicated, you do something like found in Ubercart products, you're just returning the item from the given Node and Field.

See http://api.ubercart.me/api/drupal/ubercart%21uc_order%21uc_order.module/function/uc_order_uc_order_get_properties/7.

EDIT

Apparently the entity_metadata_* functions have been deprecated and you should call entity_property_verbatim_get(), or entity_property_verbatim_set().


How do I use React components? I'm going to use React with D8 and perform so-called Progressive decoupling, i.e. use React Components on existing Drupal pages.

There are several articles on this topic but the information is not complete. It would be great to summarize it and define the best method of implementing React.

I've chosen this guide to start with and created a React App inside my custom module folder. I've also decided to use JSON API instead of RESTful Services, according to the recommendations.

After that author recommends to use Paragraph module to implement separate paragraphs which will be replaced by React components.

It is not clear to me what structure should my custom module have? Do I need a router, controller, .module file or maybe a plugin? Where should I put hook_preprocess_paragraph__HOOK function?

My idea is simple - to use different paragraphs for different React components and insert them into an existing layout.

Any best practices?

The 'React block'
module aims to add some more structure around React components and Redux state management in Drupal.

React blocks are defined by adding a simple YML file to your exising React component. This allows front end devlopers to create and manage React components as they normally would, and by including this YML file they can make the component available inside Drupal.


Theme twig files front page is empty I am trying to build a custom theme in drupal.
I have two page files:

page.html.twig
page--front.html.twig

both files have the same code:

    {{ page.myheader }}

            {{ page.sitebrand }}

The Problem:
I see the blocks in all the pages except the front page.

by the way:
I did set my front page as this:

I created a simple page with 'front' alias.

Is this cousing a problem?

The question:
What am I doing wrong?
How can make different display in the front page?

full page--front.html.twig

<!DOCTYPE html>

    <title></title>

    {{ page.myheader }}

            {{ page.sitebrand }}

xxx dagfv

            <button type="button" class="btn btn-lg btn-block">
                Default
            </button>

                <button class="btn btn-default">
                    Action
                </button>
                <button data-toggle="dropdown" class="btn btn-default dropdown-toggle">

                </button>

                        Action

                        Another action

                        Something else here

                {{ page.mainmenu }}

        {{ page.content }}

You have two problem.

page--front.html.twig is special suggestion template for front page. Any url set to front page always use this template => You don't need set alias for this.Just set page you want to front page.
Don't add html tag to page template. The tree of template is html=>page=>region=>block... Html tag exited in template html.html.twig.

And more you can setting twig debug to see current home page use template?


Modify user submitted form data before it is saved an emails are sent I am new to drupal but I do have php experience. I am trying to modify an existing custom module that handles some forms on our site. The form in question is used to send an email to the address that is included as a hidden item.

I need to change this email address based on an option the user chooses.

Here is an outline of what I need to happen

user goes to form (hidden email field is already set)
user enters their options
user clicks submit button
check users options and modify email field accordingly
save values to database
send email to new modified email address

Below is the code I am working with now

function bp_bottled_water_redirect(&$form, &$form_state, $form_id){
$interest = $form_state['input']['submitted']['primary_interest'];
$email = $form['submitted']['dealer_e_mail']['#webform_component']['value'];
//drupal_set_message("email is " . $email);
//drupal_set_message("interest is " . $interest);

if($interest == "bottled_water" && $email == "info.minnetonka@culliganwater.com"){
    //$form_state['input']['submitted']['dealer_e_mail'] = "info.bottledwater@culliganwater.com";
    //$email = $form_state['input']['submitted']['dealer_e_mail'];
    $form_state['values']['dealer_e_mail'][LANGUAGE_NONE][0]['value'] = "info.bottledwater@culliganwater.com";
    drupal_set_message("changed email to: " . $form_state['values']['dealer_e_mail'][LANGUAGE_NONE][0]['value']);

}
else{
    $form['submitted']['dealer_e_mail']['#webform_component']['value'] = $email;
    drupal_set_message("email remains: " . $email);
    drupal_set_message("interest is " . $interest);
    }
}

/**
 * Implements hook_form_alter().
 */
function dealers_form_alter(&$form, &$form_state, $form_id) {
//drupal_set_message("Form ID is : " . $form_id);

if ($form_id == 'webform_client_form_960') {
//drupal_set_message("found form");
$form['#submit'][]='bp_bottled_water_redirect';

}

  // Act only on 'webforms'
  if (isset($form['#node']->type) && $form['#node']->type == 'webform') {

    $require_zip = FALSE;
    if (isset($form['#node']->field_form_display_options['und'])){
      foreach ($form['#node']->field_form_display_options['und'] as &$key) {
        if ($key['tid'] == 13) {
          $require_zip = TRUE;
        }
      }
    }
    switch($require_zip){
      case TRUE:
        $zip = _session_get('zip', '');
        if (dealers_is_local($zip) && $require_zip == TRUE && $zip !== '') {
          $zipinfo = json_decode(file_get_contents('http://zip.elevenbasetwo.com/'. $zip));
          $simplexml_obj = dealers_get_local($zip);
          $form['submitted']['5_digit_zip_code']['#default_value'] = $zip;
          // $form['submitted']['city']['#default_value'] = ucwords(strtolower($zipinfo->city));
          $form['submitted']['state']['#default_value'] = $zipinfo->state;
          $form['submitted']['dealer_e_mail']['#default_value'] = $simplexml_obj->DealerList->DealerRecord->EMail;
          $form['submitted']['dealer_e_mail']['#webform_component']['value'] = $simplexml_obj->DealerList->DealerRecord->EMail;
        }
        else {
          drupal_goto('dealers/'. substr($_SERVER['REQUEST_URI'], 1));
        }
        break;
    }
  }
}

The issue I am having is I can change the values according to the drupal_set_message. But it seems to be taking place after the data is saved. Because the email shown when viewing my submission is still the old one.  I think my code may be running to late.

How can I modify the email address before the data is saved?

You maybe able to add a submit handler or validate handler.

How do I add an additional submit handler in commerce checkout form?

https://stackoverflow.com/questions/15375616/how-to-use-form-validation-in-drupal-7

See the form examples >  https://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/7


How to tell if my Drupal site is comprised from the SA-CORE-2018-002 -- 2018 March exploit? Just released exploit: https://www.drupal.org/sa-core-2018-002 --- Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002

How can I tell if someone used this exploit to hack my site?
What can they do with this exploit if executed properly?
I can't update my Drupal sites now, what is a good alternative to patch up this hole easily?

How can I tell if someone used this exploit to hack my site?
Your Drupal 7 or 8 site can experience loss or theft of data, data can be removed, deleted or changed, wreaking havoc on the site in many different ways.
See this Stack Exchange post for general information on checking to see if your website has been hacked.
What can they do with this exploit if executed properly?
The exploit is a remote code execution vulnerability, which means any data has the potential of being affected.
This exploit has been given a risk score of 21/25, which is almost the highest that it gets. This risk score also defines the following vulnerabilities, among others:

AC (Access complexity): easy (no skill) to access and exploit
A (Authentication): no special authentication needed
Cl (Confidentiality impact): all non-public data is accessible
II (Integrity impact): All data can be modified or deleted

Read more about risk scoring and definitions here.
I can't update my Drupal sites now, what is a good alternative to patch up this hole easily?
There is a patch available if you are unable to update core right away. From Drupal.org:

If you are running 7.x, upgrade to Drupal 7.58. (If you are unable to
update immediately, you can attempt to apply this patch to fix the
vulnerability until such time as you are able to completely update.)
If you are running 8.5.x, upgrade to Drupal 8.5.1. (If you are unable
to update immediately, you can attempt to apply this patch to fix the
vulnerability until such time as you are able to completely update.)

To read more, here is an FAQ about the exploit


What are some quick ways to setup Product Displays in Drupal Commerce? What is a fast way to create product displays in drupal commerce? Say I created 50 different unique products and now they are all over the place on the product list, how can I intuitively add these 50 products to a product display?

If you are adding product manually then you can use Auto Product Display module to set display of the product at the same time when you create product. But if you are using commerce feed along with feed then you will have to set two separate importer for each of them.


MySQL join custom field to uid I need to export some data directly from a D7 DB. I'm not that familiar with the Drupal DB schema. Some additional profile fields have been added to users profiles and I would like to export that along with some columns from the users table.

In this case the job_title custom field data appears to be stored in the field_data_field_user_job_title table.

In that table I notice there are columns entity_type and entity_id. The value entity_type is set as user for all rows in this table.

Does this mean that the entity_id field for rows in this table where entity_type='user' can be joined to users.uid to associate the custom profile data with the correct user record?

If the fields you're interested in are attached to the user entity directly (i.e. not using something extra like the Profile2 module), then your assumption is 100% correct. You'll also see a field_revision_field_user_job_title, which is used to store the current revision (for entities that have that functionality).

The user entity doesn't have revisions, so in my experience if you need to go directly into tables, the field_data_* ones are the best bet.

To get as much reusability as possible, though, you should really use the EntityFieldQuery class to perform such queries. For example, if you wanted to get all users with a certain "job_title", you can use something like this:

$query = new \EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->fieldCondition('field_title', 'value', 'foo');

$results = $query->execute();
if (!empty($results['user'])) {
  $users = user_load_multiple(array_keys($results['user']));
}


Formatting is lost after publishing the content I am using WYSIWYG with TinyMCE in my Drupal 7 website. I observed that the copied content looks similar in editor and even preview also looks nice. But all the formatting is lost after publishing the content.

To debug the issue, I checked the HTML and found that the actual style is present in the code. Please see the below screenshot-

I noticed that after disabling the color property of background for td element, the original color appears. Please see the below screenshot-

Please suggest any way to solve this issue.

Is it possible your input format is a "filtered HTML"? If I'm not in wrong it removes a lot of attributes: try to change it to "Full HTML" and verify the behaviour...


Serve Drupal files from subdomain On Drupal 7, I want all files to be served from a a subdomain of my site (eg. files.mydomain.com) for the simple reason that it allows a bit of flexibility going forward. So uploaded files, css and js caches, etc. would all be served from this subdomain.

The files are still located on the same server as Drupal and in a location writable by Drupal.

How can I do this?

Take a look at the CDN module it helps you serve files from a different domain.
I'm using it myself on a drupal 6 site, and it works great.


Problems linking Image to product display node I'm trying to implement something like what's referenced here Image redirection problem, but I closer to the mark with this method http://www.drupalcommerce.org/node/556. The problem I'm having is that this sends me to a 404 page somehow the path is corrupted to this "localhost/drupal//drupal/node/437"

This was done by adding the field Content:Path to my view and excluding it from the display, placed it first in the field order, and then changed the image field by rewriting the result, exporting as link, and using the [path] token as the link itself.

I also tried the same thing with Content: Nid, first field but excluded from display, ditto with the image field but I used the [nid] token. This got me a cleaner path  "localhost/drupal/437" but it's still going to a 404 page.

So in the first instance it's writing too much of the path into the link and in the second instance it's not inserting enough of it.

This problem is solved by changing the Content: Path rewrite options to using absolute path.


How to delete Panel variant programmatically I have a "node_view" panel pane, with a few variants.

Say a variant called node_view_panel_context_9, and I would like to delete this variant programmatically using code (from a hook_update_N hook to be specific).

What are the correct API functions/methods to use?

I just had to do this recently. If the variant is exported to code (like in a Feature) this will revert it. Otherwise it will just delete it.

   function MY_MODULE_update_N() {
     ctools_include('export');
     $page = ctools_export_crud_load('page_manager_handlers', 'node_view__test123');
     ctools_export_crud_delete('page_manager_handlers', $page);
   }


geolocation_views: show combined data in tooltip I have two content types that work together:

"place": a place on a map (via a geolocation field)
"object": an object that is in a specific "place" (referenced via an entityreference field)

Several "objects" can be stored in the same "place".

Now I want to display a map showing the location of each object (via geolocation_views).

My problem:

either the view shows OBJECTS, but then if there are several objects in the same place, several "pins" will appear on the exact same spot on the map, which doesn't work well (you can only click on the topmost pin)
or the view shows PLACES, but then the information about what object is stored in that place is absent.

For now, I have the following:

the main view is the map and shows places
and then I added a second view, as an attachment next to the map; this view lists (textually) all objects, grouped by places.

This works, but it means that the map is pretty much useless: you can click on a place, see its name, but you have no information about the objects and so you have to search the name of this place in the second view and then you will see the objects. Since there are several dozen of places, it's really cumbersome.

Ideally, I'd like that when the user clicks on a "place" on the map, the tooltip shows not only the name and address of the place (it's already the case), but also the list of objects stored in that place.

How can I achieve that?

You're incredibly close. What you need to do is incorporate the objects related to the place into the place view itself.

You do this by means of a Relationship. You can find that, when you're editing the view, in the right-hand Advanced column. When you click Add, you'll see something like Entity Reference: Referenced Entity, A bridge to the Content entity that is referenced via your relate field.

This puts the JOIN in the FROM clause of the underlying SQL query.


Migrating csv data as array into multi-field How do I migrate a sequence of data into a multi-value field?

I am learning D8 migration and working on a large CSV of historic census data from around the world. Example below:

id,Country Name,Country Code,Indicator Name,Indicator Code,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018
1,Aruba,ABW,"Population, total",SP.POP.TOTL,54211,55438,56225,56695,57032,57360,57715,58055,58386,58726,59063,59440,59840,60243,60528,60657,60586,60366,60103,59980,60096,60567,61345,62201,62836,63026,62644,61833,61079,61032,62149,64622,68235,72504,76700,80324,83200,85451,87277,89005,90853,92898,94992,97017,98737,100031,100834,101222,101358,101455,101669,102046,102560,103159,103774,104341,104872,105366,105845

My migration yml file is as follows:

uuid: 6c54b8f4-96c7-4678-8919-b20c8b318c82
langcode: en
status: true
dependencies: {  }
id: World_Census_Data
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - CSV
migration_group: random_migrations
label: 'International census csv data'
source:
  plugin: csv
  path: /var/www/random-migrations/modules/custom/random_migrations/sources/census-58-years.csv
  ids:
    - id
  delimiter: ','
  track_changes: true
process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count:
    plugin: array_build
    default_value: 0
    value:
      - 1960
      - 1961
destination:
  plugin: 'entity:node'
migration_dependencies: {}

Instead of manually creating an individual field for each year, I created the field_count field which is an Interger field set to allow unlimited entries. My idea is to import all the population numbers from 1960 to 2018 as new entries of field_count for each country.

My problem is the population data is not being imported. Can anyone advice if my proposed solution possible and if it is, what I need to change/fix in my yml to get my migration working?

Help, please.

I figured it out.
The issue was the plugin. Rather than * array_build*, I should have been using the get plugin, as follows:

process:
  type:
    plugin: default_value
    default_value: census
  title: 'Country Name'
  field_country_code: 'Country Code'
  field_count:
    plugin: get
    default_value: 0
    source:
      - 1960
      - 1961
      - 1962
     .
     .
     .

That migrates the value of the array indexed by those years into the field_count field. And because the field has multiple cardinality, each row is written in as a new value.


In the Features module, what does "Recreate" do? What does it mean to "recreate" a feature? How does this affect the database?  How does it affect the files, if at all?

Recreate allows you to re download the feature, including any changes made to config along with the option to add new config.


How to add a class to a checkbox in a form? I would like to add the class 'checkradios' to checkboxes in an entity form, is it possible do this in the theme layer?

Sure.  You can copy theme_checkbox() from includes/form.inc:

function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

into your theme's template.php file and rename it accordingly:

function YOURTHEME_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox', 'checkradios')); // <-- checkradios added in here

  return '<input' . drupal_attributes($element['#attributes']) . ' />';
}

along with the addition of the checkradios class and this will be added to each checkbox.

Now, if you want to restrict it to certain fields, you can look inside $element and add some additional logic to this.


Custom template for view page When i created custom template for view page using 'theme information' in views,it's not affecting the page.What is the proper way to create template for view pages?

I think this pretty well covers it: Views template files


Notify node author of new comments Has anyone been able to figure out how to notify the node author when new comments are posted on their content?

I understand Rules for Drupal 8 is still in its infancy.  When I used various tokes for the TO filed nothing worked.

If anyone could share their solution that would be great.

... how to notify the node author when new comments are posted on their content??

To my knowledge, the current answer to this question is: not possible yet.
More info

Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some (scary) quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

Start here if you wonder how to contribute.

One never realizes what has been done, only what remains to be done ...

Plan B
You might want to look at the Message module (and the related modules that belong to the Message Stack), which has a pretty stable release already, and which you could use to create similar functionality.


How do I dynamically change an autocomplete route for a field depending on another field's value? On my node edit form, I have a select field (Field A) and another taxonomy reference field (Field B). Field B is currently using "views" as a reference method to filter for the options.

When the select field has a value selected, I want the taxonomy reference field to show a different set of autocomplete options.

I was wondering if there was a good way to dynamically update the "argument" for the views reference filter for the taxonomy reference field depending on what was selected in the select field?

If I understand your question correctly, you may want to include one term reference field for each taxonomy you want included on the form. You could then create a template for the page and use Javascript to control which fields are visible. So if the user chooses Option A  it gives them one set of choices for the Taxonomy and if they choose B it gives them another..

You may also have luck with https://www.drupal.org/project/conditional_fields


How can I set the energy settings for the Radioactivity module? I saw in this screencast (from 4m 20s) that a lot of cool features were available to set the energy settings in Drupal 6. One could for example give specific scores when nodes were viewed or evaluated with Fivestar.

Is this possible in Drupal 7 too? I can't find any documentation about it...

All those cool features are still there, you just need to set up a "Decay profile". You can do this at /admin/structure/radioactivity.

Once you've got the profile setup (with the "Advanced" method by the sounds of what you're looking for), you can edit the Radioactivity field on the entity, and choose that profile. When the entity is viewed, the tracking will kick in automatically.

To respond to events such as fivestar ratings, you need to use the Rules module as everything's been decoupled for flexbility.


Drupal 8 Rules and Media I want to publish Media associated with content when the content is published.

Is that possible with rules?

If so, what are the conditions I need to set?

The conditions I have set are:

  Node is published - data selector: node
  entity has field - data selector: node, value: field_my_media_field

Is that possible with rules?

I'm a bit familiar with the (amazing!) Rules module. But to my knowledge the current answer to this question is No, Non, Neen, Nein.
More info

Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8. Here are some (scary) quotes from it:

... Fago can’t dedicate time required to develop the module further. What Rules is really missing at the moment is development capacity to help finish the last milestone.

... Even if we got more funding today, fago the current principal maintainer of the Rules module wouldn’t have enough capacity to do the work himself.

Start here if you wonder how to contribute.

One never realizes what has been done, only what remains to be done ...


edit node attribute in view In Drupal 7, is there a way to edit nodes from a view? For example, could I add a checkbox or drop down menu for each node in the view to set a particular attribute of that node?

The EditableViews module should serve your purpose well. Here is part of the module's project page:

  Editable Views lets you create Views where the fields can be edited. Fields show both the current value and a form to edit it. A 'Save' button allows saving of all the entities shown in the View.


The theme is broken when I enable the "Optimize CSS files" option The theme I made is broken, when I enable the "Optimize CSS files" option. I have cleared the cache, but the theme still doesn't work. With Firefox and Internet Explorer it is OK, but with Google Chrome is not OK at all.
How can I fix this?

I have that in all my CSS files, and it works fine in Chrome.

try:

converting the CSS file to UTF-8 (if it's not)
removing any multiline comments

/*
This is a

multi-line comment.
*/


How do I override menu items with my own implementation? My specific use case is this: I don't want users accessing the user/%user/edit menu. This is awkward because it's quite embedded in Drupal, e.g. forgotten password system. I want the drupal form for admins, but I want a different form for end-users because I do not want to expose certain user fields to them, and because some updates they may need to do need to be handled by an external database, so changing them in Drupal is unhelpful.

Using hook_form_alter() is not really going to cut it; it really does need to be quite a different form.

I had planned to override the user/%user/edit path by using my own module. This would then check if the accessing user was an admin, and if so, present the stock form, but if not it would drupal_goto('client/updates'); but this doesn't work; my module's page callback never gets called.

You can use hook_menu_alter() to reroute the request for that page to your own module's functions:

function MYMODULE_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'MYMODULE_access_callback';
  $items['user/%user/edit']['page callback'] = 'MYMODULE_user_edit_page_callback';
}

function MYMODULE_access_callback($account) {
  if ($something) {
    return FALSE;
  }

  return TRUE;
}

function MYMODULE_user_edit_page_callback($account) {
  if ($something) {
    return drupal_get_form('some_form');
  }
  else {
    return drupal_get_form('some_other_form');
  }
}


Stale Pathauto Alias I'm just curious how other Drupal developers handle nested path aliases when they are based on another page's url pattern.

I have a product landing page (it's a "basic page" node). When it's created, right now, the url is:

/product

For my product nodes, I set up a path alias to be

/product/[node:title]

This makes my product detail pages nicely nested under "product." This works fine for a while. But later, if someone changes the product landing page url, the alias for the product nodes will not match.

Say someone edits the product landing url to be:

/widgets

Then I have a /widgets landing page and a bunch of product nodes with urls like /product/product-name.

Is there a nice way to handle this? Or is it up to content creators to just know they need to update it?

You should use Pathauto if you aren't already.

This has a feature (tab) that lets you bulk update the content type urls to /widgets/[node:title].

You should also install the Redirect module, so that all your former /products/[node:title] automatically redirect to /widgets/[node:title]. This is for SEO purposes, you don't want your Google listing pointing to a broken link, non-existent page.


How to link the title in a teaser to the main content? I have created a view that provides teaser content for different nodes.

This teaser content carries a main title and some more fields. I want to make the title as a link, which when clicked, takes the user to a page that displays the full node.

I tried enabling the "Link this field to its entity" for the title field in its view, but clicking on that link takes me to a page like:

http://localhost:8082/node/<node id>

I want it to go to a prettier looking URL like:

http://localhost:8082/<pretty URL>

How can I achieve this?

If you are using a node title field, then the "Link this field to its entity" option should definitely work.

By default it will link to

localhost:8082/node/123

where 123 is the node ID of the node.

If you want a nicer URL, like

localhost:8082/title

where title is the title of the node (or something similar), try the pathauto module, which allows you to define settings that automatically create pretty urls for nodes (and users and taxonomy terms, etc.).
The pretty urls can use tokens, like [node:title], which will be replaced by the title of the node for example.


Feeding arguments into Views I'm not sure how to frame this question, so I'm sorry if the answer already exists.

Basically, I want to know how to modify the way arguments are fed into views. For example, say I'm presenting a income statement and balancesheet, it seems like its formatting the links as www.example.com/balancesheet/ibm and www.example.com/incomestatement/ibm

Is there a way to make it www.example.com/ibm/balancesheet or www.example.com/ibm/incomestatement, so I can create views and have them grouped this way?

My problem is instead of grouping content by views, I want to try to group views by content so if someone searches for IBM they basically get all the views that apply.  I'm open to any suggestions anyone has.

Each item between the slash after the domain name of the website is called an argument. Take, for example, example.com/one/two/three/four/five -- in this case one is the first argument, two is the second argument, ect.. Drupal has a function that separates these arguments named arg() which takes an argument as a number. arg(1) when called while loading this example URL will always return 'one' while arg(5) will always return 'five'. This way context can be passed into all the modules in a consistent way. I just want to make sure you see arguments for what they are.

Here is why. You are creating a two separate pages for items that should be on the same page. Instead of creating pages you might consider blocks in views and place the many blocks on the same page. This way you can, for example, use taxonomy terms to tag content as IBM, Intel or Apple. Create a balance sheet and tag it IBM. Create another tag it Apple. Create an income statement and tag it IBM. Create another and tag it Apple.

Then create a basic page with a brief description of the IBM corporation and a logo using the path alias module to change the name of the URL to example.com/ibm. Then add the two views as blocks to the page. Each view will be called when the user goes to example.com/ibm and arg(1) will be ibm. Then you can use the arguments (in View 3 contextual filters) to use this argument to define the Taxonomy term to filter the information in the database with. In this case IBM. Now you might have 12 reports for IBM for each category going back 4 years. Views will pull them all and you can use a field of title that links to the node to have a link going to each one. Then you can also use the date filter to make sure that the most recent one is on top. Once the View block is created, Views will just load the other view using once again arg(1) to define the taxonomy term to find all the other reports information in the database.

Now there are more advanced ways to trigger which Views get called with modules like Context or Panels which are super high powered tools that focus on just this simple purpose.  You might be interested in the videos on Panels at Node One or the Mustard Seed Media video on the Context module.

(edit) To create a similar tabbed look like companies on the WSJ you can use either Quick Tabs for an ajax tabbed effect or creating a Views page and assigning it a Menu Tab for the menu item so that several tabs are found on the same page.


Show image for only first view item I've created a view for a group of nodes, what I want to do is output the image just for the first result rather than all of them.

Currently I'm using CSS to hide all except the first but that isn't ideal.

Display Suite provides this functionality.  Just install DS, then, in your view, choose "Display Suite" under the option for "Show":

In the settings for that option you can choose a different view mode for the first item in your list:


How does `drush features-update` work? I have made changes to a Feature on a Drupal 7 site.  I want the same feature to be updated in another website. How to do it using the drush features-update command? When I run it, it asks to overwrite the previous Feature, but nothing new comes in the Feature.

Drush feature-update updates the feature code with overwritten settings. So the function is used to export changes to code.

If you want to take those changes to another site, you will have to copy the updated feature to the other site unless they share the same code (and then revert the feature and clear cache (not always needed)).

In code it could look like this

$ drush fu feature_module
$ cp -r feature_module ./DIR
$ cd DIR
$ drush fr feature_module


Views and theme functions for nodes Is there a way for a view to pull out x number of nodes of the same content type but use a different theme function for each one depending based on the value of one of its fields?

I need each node to be themed according to a field which will have the name of a theme function.

Display Suite Extras, shipped with Display Suite, lets you choose a different build mode for every row in the View. You might look its code to see how it's done and then hook into it to switch based on the value of a node field. Shouldn't be hard.


Fire Autocomplete after input reaches 4 characters I am searching for a way, to fire the autocomplete event after 4 characters are in the input-field. What I am doing now is:

if(strlen($string) > 3) {

in my "page callback", but this is not the way I want it to work. Because now, the event is fireing, but only returns matches after 4 characters.
Is there a way to start the autocomplete only after the input?

Check this answer : https://drupal.stackexchange.com/a/143720/30200

In short, you can defined a custom jquery event and associated it to your form_item. This event would fire only after a certain number of character


Context and Page Caching Just started a gigantic Drupal build and I'm trying to validate if the Context Module is the correct option for a segmented content delivery system. It appears to be and I am optimistic.

The project calls for about 100 custom "variables" that the site administrators can segment content with. As a test, I've created a custom context condition of time of day. If the condition is set for >= 2PM for example with a reaction of showing the Powered By Drupal block in the footer, everything works as expected - Before 2PM, no block and after 2PM, block. So the context condition is working as expected.

Now, I've enabled page caching with lifetime and expiration set to 1 day. If I clear the cache before 2PM and hit the page, the block does not show as expected. If I hit the page (which is previously cached) after 2PM, still no block.

I have used a "preboot" method to modify the cache key, but in my example above, the cache key would include the hour and the minute, effectively reducing the cached copy of a page to 1 minute. I might as well turn page caching off in that case!

Is it possible to run the context conditions on a cached page? Has anyone found a way to make this happen?

If you have access to your ssh console, you can use cron

crontab -e

Then you put inside, at the bottom:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
0 14 * * * cd /var/www/drupal && drush cc all

the above will clear the cache with drush everyday at 2pm.

A few notes:

replace cd /var/www/drupal with the actual path to your drupal.
I believe the default runs at UTC time.
You need to install drush if you haven't already.

An alternative to using Drush, you could create a PHP or Python or NodeJS etc.. file that uses mysql to delete the row that holds the page cache in your DB, and run the file with cron at 2pm.


How to format views table using open outreach theme The Views preview of my table looks like this.

Using Open Outreach it appears like this.

Neither are exactly what I'd like to see. How can I change the displayed table format (on my site) without fooling with php and CSS? I'm new to Drupal. I really don't want to get into CSS and php.

You could transform the tabular display by using the DataTables module, which uses the datatables plugin.
In doing so, you get all the typical dataTables widgets available, such as sorting for appropriate columns, but also a search box, pagination, etc.
Here is an excerpt from the module's project page:

... integrates the jQuery plugin DataTables into Drupal as a views style and a callable theme function. DataTables lets you add dynamic features to tables, including:

Variable length pagination
On-the-fly filtering
Sorting with data type detection
Smart handling of column widths
... (1)

(1) = there are more features (i.e. "Themeable by CSS"), but that requires "fooling with php and CSS" ...
PS: Works great for both D6 and D7 ...
Update (related to that issue you ran into as mentioned in your comment):
Consider reviewing/testing if that patch in comment nr 1 might work for you. The patch looks like so:
diff --git a/datatables.module b/datatables.module
index 193c892..3b66932 100644
--- a/datatables.module
+++ b/datatables.module
@@ -244,11 +244,8 @@ function theme_datatable($variables) {
 function template_preprocess_datatables_view(&$vars) {
   // Run views table preprocess function to handle putting rows in columns,
   // classes, etc.
-  template_preprocess_views_view_table($vars);
-
-  // No need to add anything if there are no rows.
-  if (!$vars['rows']) {
-    return;
+  if(!empty($vars['rows'])) {
+    template_preprocess_views_view_table($vars);
   }

   $view     = $vars['view'];

The most elegant / straight forward way to "apply" that patch is to use GIT. However, this seems like only a few lines in 1 module are changed by the fix. You could also "apply" that fix by simply editing that module to be patched, by reading what the patch content is, and then editing the module with your favorite editor, to achieve the same result. Here are the steps involved:

navigate to the folder in your site that contains file datatables.module.
make a backup copy, eg to something like datatables.module.backup.
open datatables.module in your favorite editor, and scroll to the line around line 244. If you can, turn line numbers on.
You should then see a few lines of code identical to the lines near the top of the patch (not preceeded by '-' or '+' signs.
around line 247, there should be a line like template_preprocess_views_view_table($vars);, but without that '-' sign as in the patch
DELETE that exact line, and then next 4 lines entirely (which is indicated in the patch with the '-' sign at the start of each line).
then INSERT those 2 lines preceeded by a "+" in the patch (but make sure to replace the "+" signs at the start of those 2 lines with a blank).
save your (module) file, and rerun your test to see what effect/result you now get.
after you finished testing it, decide what you want to do with this edited version of the module. Continue to use it? If not rename the edited file to something like datatables.module.edited, and then rename the datatables.module.backup file back to datatables.module. That will have restored the original version.


How do I style a block title for a single menu in a fusion theme? I have a custom menu placed in the sidebar1 region of a fusion-based sub theme. The menu is displayed with the Menu name as the block title.  When displayed, the title is styled with
.  If I set colors and backgrounds in css style sheet as h2.title.block-title {}, all block titles on the page for all regions are styled the same way, but I would like to limit the style to just one specific menu. When rendered, the menu block is embedded within a couple
 levels including one for the region
. Using h2.title.block-title.sidebar-first-inner {} does not work. How do I limit the style to just this one location of h2?

you could use

div.sidebar-first-inner h2.title {
   whatever css rules you need
}

which means set the css of an h2 with class title that is within a div with class sidebar-first-inner