How to ensure CiviCRM checksum / cid are valid in custom Drupal module

A little grepping around and I found this:

CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])

which takes a CiviCRM contact id ($cid) and compares it to the checksum in the URL and did the trick for me as follows:

  $cid = check_plain($_GET['cid']);
  if ($cid != "" && CRM_Contact_BAO_Contact_Utils::validChecksum($cid, $_GET["cs$c"])) {
        //Contact ID and Checksum match up, embed a view
        //with $cid as an argument (or other custom functionality)
  } else {
        //Not a match, decide what you want to do in this case
        //(e.g. check if user is logged in, or display error...)
  }

UPDATE:

It looks like the usage has changed slightly in core since I pulled the above out of there (although the above was still working for me). Try this (taken from here):

    //check if this is a checksum authentication
$userChecksum = CRM_Utils_Request::retrieve('cs', 'String', $this);
if ($userChecksum) {
  //check for anonymous user.
  $validUser = CRM_Contact_BAO_Contact_Utils::validChecksum($tempID, $userChecksum);
  if ($validUser) {
    return $tempID;
  }
}


Best method to clean up database table orphaned data in Drupal 7?

This is a script I use on my own Drupal sites, you can see if it works for yours, it deletes files and records in the file_managed table that have no references in the Drupal file_usage table, or things that are no longer being used by the Drupal installation.

$result = db_query('SELECT fm.fid, fm.uri FROM {file_managed} fm LEFT JOIN {file_usage} fu ON fm.fid = fu.fid WHERE fu.fid IS NULL ORDER BY fm.fid');
$num_files_deleted = 0;
$num_records_deleted = 0;
$time_before_start = time();

foreach ($result as $record) {
    $file = file_load($record -> fid);

    if ($file != FALSE) {
        if (file_delete($file)) {
            print(drupal_realpath($record -> uri) . " has been successfully deleted.\n");
            $num_files_deleted++;
        }
    }

    db_delete('file_managed') -> condition('fid', $record -> fid) -> execute();
    $num_records_deleted++;
}

$time_after_finish = time();
$total_time = ($time_after_finish - $time_before_start);
$total_time_h = $total_time / 3600 % 24;
$total_time_m = $total_time / 60 % 60;
$total_time_s = $total_time % 60;

if ($num_records_deleted || $num_files_deleted >= 1) {
    print("\n\n");
    print($num_files_deleted . " files purged and " . $num_records_deleted . " in " . $total_time_h . ":" . $total_time_m . ":" . $total_time_s . ".\n");
}
else {
    print("Nothing to purge.\n");
}

You can try running that on a dev to see if that's also something you would want.


How to create a custom design of an existing view block?

By modifying the view templates the views can be altered.
You can add custom html design and styles to modify design.

From Page: Theming information select the template. For eg:  views-view--sample--page.tpl.php, template for the view named Sample.


How to import date fields using CSV file?

This was an issue with the feeds importer. I deleted the existing importer and created a new importer with new mappings, then all the date fields started working as normal.

The date format I use in the csv file is: 23-Apr-12


This will disable the cache.

$build['#cache']['max-age'] = 0;

Block Cache API is removed; blocks now use standard caching patterns


Default value for the same field, different depending on content type

You can easily achieve you goal with the rules module, as @pico34 wrote in his answer, but use the trigger Before saving content instead of After saving new content.

Alternativey, if you need to do that programmatically, you can define your default values in just a few lines of code using hook_node_presave()

Example

/**
 * Implements hook_node_presave().
 */
function YOUR_MODULE_node_presave($node) {
  // set the value of field "field_somefield" in case of node type: a, b or c.
  if (in_array($node->type, array('a', 'b', 'c')) && empty($node->field_somefield[$node->language][0]['value'])) {
    switch ($node->type) {
      case 'a' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for A';
        break;
      case 'b' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for B';
        break;
      case 'c' :
        $node->field_somefield[$node->language][0]['value'] = 'Default value for C';
        break;
    }
  }
}


How do I debug a CKEditor installation on Drupal 7?

Here are, roughly in the order you should try them, some tips that may help you debugging a CKEditor configuration.

1. Clear the cache

Remember to clear the cache after you've changed any setting that has something to do with wysiwyg.  Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.

2. Check out that roles are configured correctly

Navigate to your text formats: Administration » Configuration » Content authoring  » Text formats and ensure the roles are configured correctly.

Add the roles you want to use wysiwyg to Filtered HTML and Full HTML.

3. Check out that profiles are set up right

Navigate to your ckeditor profiles: Home » Administration » Configuration » Content authoring » CKeditor

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

Under Basic Setup, check the text formats that apply
Under Editor Appearance, set default state to enabled, and show the toggle.

4. Check the paths

Navigate to Administration » Configuration » Content authoring  » CKeditor » Global settings. press Edit, and check that all the paths listed there actually exists.

5. Check the default text processing option

Make sure that you've selected "Filtered text" as your default text processing option.  To change this, navigate to Administration » Structure » Content types, select the content you experience problems with and click manage fields and edit  on the body field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. Filtered HTML).

To make sure that Filtered HTML is selectable, you need to make sure that the setting for "Text processing" is set to Filtered text (not Plain text):

Press Save settings after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. Filtered HTML) is selected.  The screen dump below shows how the pull-down menu immediately below the text field for content should look like:


How can I filter a View by the value (or data) of field?

I have worked out how to do this finally. You need to install the token filter module and then when entering a value for a filter inside Views, you can make the operator "equal to" a token. Meaning, you can filter by the value of a particular field or anything else exposed as a token.


Drush not working on Multisite with Shared User Table

The solution ended up being very simple.

I just had to change one line.

I changed this:

        'default'   => '[Multisite DB].',

to:

        'default'   => '',

This is how it looks all together.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => '[Multisite DB]',
  'username' => '[Database Username]',
  'password' => '[Database Password]',
  'host' => '[DB Server IP]',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
  'prefix' => array(
        'default'   => '',
        'users'     => '[Main Site DB].',
        'sessions'  => '[Main Site DB].',
        'role'      => '[Main Site DB].',
        'authmap'   => '[Main Site DB].',
        'users_roles'   => '[Main Site DB].',
        'field_data_field_first_name'   => '[Main Site DB].',
        'field_data_field_last_name'   => '[Main Site DB].',
        'field_data_field_title'   => '[Main Site DB].',
  ),
);

I know that a lot of people use Bakery or are already on Drupal 8, but I hope this helps anyone still on Drupal 7 looking to share a User table across multiple websites with different databases.


Multiple nodes from a single content type?

As fas as i understand the question your requirement is to display those content on different pages. So it is better to create a three different views displaying the required data.For example you can create first view name dog1 having field name , breed and history and a second view name dog2 having field age weight and height and so on. And also you add submenu of those two pages link.


Is there a way to get Drush to download all required dependancies for a specific module?

Drush 5 and up:

Newer versions of Drush (version 5 and higher) will ask you if you want to download the required dependencies when you enable (drush en) a module. It will also ask if you want to download the module itself if you didn't download it yet. Combined with the "-y" option (e.g. drush en views -y), everything will be downloaded and enabled automatically without asking further questions.

Note that the automatic downloading of dependencies may fail if the required module's name is not the same as its project name on drupal.org. For more info, see the my original answer for Drush 4 below.

Original answer (Drush 4):

No, there is no way to do that. The problem is that there is a difference between a module and a project. Often (but not always) the name of the project is identical to the module (or one of the modules) contained in the project. A single project (eg. Views) can contain multiple modules (views, views_ui, views_export). While drush dl downloads a project, drush en enables a module.

When a module declares dependencies, it declares dependencies on modules, not projects. When performing a drush en, Drush can check if the required module is available. However if it's not available, Drush has no way of knowing which project to download. For Drush to be able to automatically download required projects, work needs to be done in the underlying projects/modules infrastructure, so Drush can retrieve a mapping of projects and modules. See also Smarter handling of missing dependencies.


Drupal and reverse proxy: How to make Drupal aware that it's protocol is HTTPS?

It turns out the IP which should be in the reverse_proxy_addresses is neither the IP which you get when you ping the domain, nor the ID in the headers which you can inspect. Rather, you need to temporarily install devel_php on your site, and then go to /devel/php and enter dpm($_SERVER['REMOTE_ADDR']);. This will give you a result such as 172.18.0.5, which then goes in $settings['reverse_proxy_addresses'];
More info at https://blog.dcycle.com/blog/170a6078/letsencrypt-drupal-docker/


You can achieve this by overriding the service defined from Drupal core.
Altering existing services, providing dynamic services describes the code to use.

In your case, the code should be similar to the following one.

namespace Drupal\my_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the mail provider service.
 */
class MyModuleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('plugin.manager.mail');
    $definition->setClass('Drupal\MY_MODULE\MyMailProvider');
  }
}


Set the menu_name key of your menu-router item. From the docs:

  menu_name: Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

By default the primary links are set to the Main menu (machine name: main-menu). Therefore use something like this in your implementation of hook_menu:

function hook_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
  );
  return $items;
}


Why is the --uri option needed to return absolute URLs?

You can set the default uri by adding the following file. Then if you don't provide --uri it'll use the default.

sites/all/drush/drush.yml

options:
  uri: "https://your-site.domain"


The answer given on How do I remove the user registration/login form? is relevant for this question too.

While it's technically possible to remove the login functionality, you shouldn't, because then your administrator could never log onto the site.
In order to remove the register functionality, you simply need to browse to admin/user/settings (for Drupal 6) or admin/config/people/accounts (for Drupal 7 and 8) and select the the "Only site administrators can create new user accounts" option.


Views: How can I show a list of users who have a taxonomy term attached via a term reference field?

I ended up implementing this by overriding the taxonomy page with panels instead of views.  I then made the old view taxonomy term override into a content pane.  Then, to get the "User: has taxonomy term" effect, I made a view (content pane) for each vocabulary with a "Term ID" contextual filter (supplied as a panel argument) and a relationship of "Taxonomy term: User using MY TERM".  I then added these views as content panes to the taxonomy override in panels.

I had to do this for each vocabulary, but it works.


Views 2: Combine two multi-value fields per row

Ah.  I gotcha now.  Drupal has no internal automagic way of knowing any connection between your author name and photo fields.  But, for display purposes at least, you can show them together by hacking at the CCK field template.

If you go into CCK module's directory, you will find a content-field.tpl.php file.  Copy it into your theme's directory and then COPY it to content-field-field_author_photo.tpl.php, eg, based upon the field name of your author's photo field name.  It is imperative that you COPY it, not just rename it, CCK needs both the base template and the specific field one.

By default, this bad boy looks like this:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php print $item['view'] ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

and basically it wraps a CCK content field with lots of CSSable divs and so forth.  What you want to do is print out the author name under each photo, so you could do that by replacing the print $item['view'] (which is your photo) with something along the lines of this:

          <?php print $item['view']; ?>
          <?php if (!empty($node->field_author_name[$delta]['value']): ?>

               <?php print check_plain($node->field_author_name[$delta]['value']); ?>

          <?php endif; ?>

And now when CCK builds this field, it will also grab the author name and put it under the photo.  It will of course still build the author name field and display it, so if that's not what you want, you can go in the Display Fields section of the node type config and exclude it from the $content variable and then it will only show up here.

Clear caches/theme registry and style up the author-photo-caption class and you should be set.  And now wherever this field is displayed, it will grab its counterpart (assuming no typos above :)

(Other assumptions:  field_author_photo and field_author_name are the names of your fields on your system.)


How much time does it take to manage sites within a multisite architecture as compared to multiple single installs?

Short: It really depends.

Long: Each individual multisite installation adds complexity to the whole. If these 70 sites are more ore less the same in terms of individual content but (nearly) same codebase, modules and similar themes (imagine a large organization spread over the world with region specific characteristics), you'll most likely need less time to maintain.

If these are 70 profoundly individual sites, you'll probably end up checking dependencies over dependencies for modules and themes, debugging deadlocks and incompatabilities. Maintaining this can be a real challenge and 70 hours a month are gone faster than you have "drushed and rollbacked" everything to working.

Accurate documentation and a SLA designed fair for both parties should be the key to a successful maintenance.

(I maintain a multisite installation with around 30 instances for a large organization with all the pros described above.)


Try global $user; rather than global $account;.


Where in the table is it stored that /drupal/foo is actually /node/47 in order to mass query to remove /drupal and just leave the /foo part?

The table you want is {url_alias}.  The {url_alias.source}column is the internal path (eg node/123), the {url_alias.alias} is the alias itself.

Mucking with the database directly isn't recommended, though.  Your best bet is to use Pathauto and Globalredirect.  The first will allow you to set up patterns, the second will redirect nodes to the alias.

You then use the Delete Aliases (admin/config/search/path/delete_bulk) link and then Bulk Update (admin/config/search/path/update_bulk) to make the new ones.

If you must do this manually, I suggest looking into the what the Path include provides as an API, and using that.

Also be sure that you don't actually have a problem with a $base_url being set incorrectly in your settings.php


Drupal Forms API how to get degree sign onto submit button

Buttons in Drupal by default are being generated by the theme_button() theme function which uses drupal_attributes() to handle all of the button's attributes which always escapes an attribute's value using check_plain().

Visit api.drupal.org/api/drupal/includes%21form.inc/function/theme_button/7 for the theme_button() function and click under the Code section on a function name to see what it does.

I think there are two possibilities:

You write your own implementation of theme_button(): copy the original function, paste it into your template.php file and rename it to something like YOUR_THEME_button();
Or just use the bare unicode character as you did in your question. I read at stackoverflow.com/q/3627720/328272 that this does not work on Windows XP, but I successfully tested it on IE7 and IE8 on XP using browserstack.com.


You will likely want to define a custom page.tpl.php for use in the lightbox so it doesnt conflict with your normal site pages where you would like sidebar content etc.

Think of having 2 differently themed versions of the same page, your traditional page and a cut down version which is only the node content area.

To do this, add a theme_preprocess_page() so it creates a unique url argument to trigger the content only display via its own tpl.php:

function YOURTHEME_preprocess_page(&$vars) {
  // Get the path (eg node/#) and split it into an array ([node][#][video])
  $path = $_GET['q'];
  $path = drupal_get_path_alias($path, $path_language = '');
  $patharray = explode('/', $path);

  // If the last part of the path is "frame" use the page-content.tpl.php
  if ($patharray[2] == 'video') {
    $vars['template_files'][] = 'page--video';
  }
}

Then copy your exiting page.tpl.php into a page--video.tpl.php and trim out all the content you dont wish to see in your lightbox.

EDIT: (include details on using the video only page) In your iframe load your node page with "video" appended to the drupal url. For example "node/135/video" so it using the page--video.tpl.php

I have been using this solution to embed content from our nodes into another application and it works well. :)


Assuming that the Name field is text and the Year field is an integer, if you sort the Names ascending and the Years descending, the empty year of James should come last and before Jane (which should be what you are after). That's the default behavior of Views. If your views has contextual filters or relationships, you may be getting different results.

In any case, you can configure the Year field and under the "No Results Behavior" you can set a very low (or high depending on what you want) value for year and hide it. This way, you will guarantee that it will be sorted as expected.


Why don't you just use Views, and place that view towards the bottom of the article or that content type?

The views will be based on a user relationship with the node uid (the author's user id).

All those fields you require you can add to the user profile (admin/config/people/accounts/fields) - Company Name, Byline etc etc? And then display them via views.


Getting the user picture URL when Gravatar is installed

Obviously, handling directly in the Gravatar module would be best, but another option (though slightly hackish) would be to simply

$img = strip_tags(theme("user_picture", array('account' => $user_item)), "<img>");


Change AJAX processing icon and progress bar in Drupal7 using CSS

You can do it by overriding the CSS in your theme CSS file. Here is the rule that you've to override

.ajax-progress .throbber {
  background: transparent url(../../misc/throbber.gif) no-repeat 0px -18px;
  float: left; /* LTR */
  height: 15px;
  margin: 2px;
  width: 15px;
}

You can just change the background and you will be able to change the processing icon.

Here is the another one that you should override

html.js input.form-autocomplete {
  background-image: url(../../misc/throbber.gif);
  background-position: 100% 2px; /* LTR */
  background-repeat: no-repeat;
}


What is the best procedure to upload sites folder from Locahost to live server?

Instead of using FTP, consider using Git over SSH.  Drupal.org has documentation on using Git with Drupal 6, 7, and 8.  Note that for this, your webhost will need to support SSH, which some of the cheapest do not.

If you're using Drupal 8, consider using Git with Composer.

If you need some help figuring out how all this works, consider making a test site and a free account on one of the Drupal-dedicated hosts like Pantheon or Acquia. (Disclaimer: I have sites on Pantheon, but here I'm just recommending trying a free account to see how the Git flow works.)


Creating a View feed: Do not summarize, but show whole post

from the sounds of it your view will be set to display teasers.

on your view edit page, under format, you have show, if set to "content | teaser" it is only displaying the teaser to display the full node click on teaser and then set the view mode to full content.


Move block level configuration also in Features


How to import nodes that reference each other using Feeds?

Two importers can work on the same nodes without any problem, but that's not what you need.  Instead, You need to set the importer to update/overwrite existing nodes when they have the same GUID.  Then you run the importer twice on the same xml file.  The first time they won't be populated properly, but because they'll already exist the second time, the second run should fix it.


How can I add a CSS class to all the tables?

If your table is rendered using theme('table'), you can preprocess it from your theme function.

function my_theme_preprocess_table(&$variables) {
  $variables['attributes']['class'][] = 'table';
}


Create a secondary form to fill data into an entity

I don't know about the webform solution/Redhen

but programmatically/basic drupal speaking I would just use HOOK_form_FORM_ID_alter to restrict access to certain form elements based on role/permission.
Find the id of the form and have a look at the array via devel or something similar, every field normally has an '#acces' variable already included. Setting those to 0 for the fields does exactly what one expects it would do.

This way you can re-use the standard form for all purposes instead of adding a second one. So future edits to the entity fields will automatically be added to all forms and you don't have to fiddle around with all sorts of secondary processing in the submit handler.


This has not much to do with form API, only with the structure of the field.

You need to pass in the values that the field type expects, based on its propertyDefinitions() method for example. Looking at http://cgit.drupalcode.org/tablefield/tree/src/Plugin/Field/FieldType/TablefieldItem.php?h=8.x-2.x#n141, it does some special processing on it, so might have to account for that.

The easiest option for that kind of stuff is usually to just create a node in the UI, then load it and call $node->toArray(). The structure that you get back ther for your field is usually also what it expects to be set.


First of all if you have date module you do not need to add two fields "Post" and "Expire". You can add a date field with a start and an end date. Other than that the rest is simple. Go to your view and add two filters.

First filter will be your start date where the field is "less than or equal to" -> "now" (you can write that only if you select "enter a relative date" )

Second filter as you may have guessed will be your expire date field where the field is "is greater than or equal to" -> "now"

If "less than or equal to" and "greater than or equal to" don't appear as options, make sure you've enabled the Date Views module. (It is installed as part of the Date project.)


How do I only render the main content without wrapping it with the theme or side blocks and menus?

There are two similar questions.

Problems creating a custom blank page with my custom module

How to output from custom module without rest of theme

You can use a symfony response or replace the page template with a blank twig in hook_theme().


How do I control the number of cols in a textarea?

Thanks David Thomas - CSS did it!

Since your comment is rather terse, I take the liberty of answering my own question where I describe how to use CSS in more detail.

To attach a CSS file, add the following to the form:

$form['#attached']['css'] = array(
  drupal_get_path('module', 'mymodule') . '/mymodule.css',
);

Then look at the HTML generated to find the class of the textarea:

<textarea id="edit-mymodule-data" name="mymodule_data" cols="40" rows="2"
  class="form-textarea">
Please fill in some data.
</textarea>

(Just for the record, notice that the values for cols and rows are picked up from the $form array, but unfortunately the value set for cols have no effect.)

The class of textarea is form-textarea, so placing the following in mymodule.css makes the textarea 100 pixels wide:

textarea.form-textarea { width: 100px; }


The way I think about it is in terms of sku numbers (or manufacturing part number/catalog number.) If a single product is available in multiple sizes (1 mg, 50 mg, 1 gm), each one will have its own unique sku. Those sizes are the variation attributes. But then I may also want to add on a non-attribute field like an image or a packaging/shipping surcharge (for a larger size). That data is specific to the product variation but isn't related to the sku.

Using the t-shirt analogy, if both size and color are attributes, then you might have the following unique variations:

TS_SM_01: small, blue t-shirt
TS_MD_01: medium, blue t-shirt
TS_LG_01: large, blue t-shirt
TS_SM_02: small, red t-shirt
TS_LG_02: large, red t-shirt
TS_SM_03: small, green t-shirt
TS_MD_03: medium, green t-shirt
TS_LG_03: large, green t-shirt

If I add on a field for an image or a field for some sort of customization, those new "non-attribute" fields do not cause me to create a whole new set of product variation sku numbers.


How do I enable the "print PDF" link on only a specific page?

Check the Link options section at admin/config/user-interface/print/ui, making sure you don't have 'content corner' selected.


How to set a checkbox using POST request with Services Module?

This probably is the JSON you need for that field when POSTing:

field_foo: { und: [ { value: 1 } ] }

Remember, the Services module is dependent on which widget you have selected on the Manage Fields page for your entity/bundle.


Taxonomy Terms node count of different content type

You can achieve this with help of an additional relation. If you are following view creation from the post mentioned by you

After selecting ' Taxonomy term: Content with term ' add another relation and choose the node referenced field - reverse and choose Require this relationship. (in your case 2.Store-title---> This field is of content type Store and is added here as a node reference)

Now you will get your count of deals


How can we discover the machine name of $conf keys?

By literally looking at the DOM.

For a random example, take the aggregate CSS checkbox on the Performance page:

<div class="form-item form-type-checkbox form-item-preprocess-css">
 <input type="checkbox" id="edit-preprocess-css" name="preprocess_css" value="1" class="form-checkbox">
 <label class="option" for="edit-preprocess-css">Aggregate and compress CSS files. </label>
</div>

You'll find the machine name for the variable in the name attribute of the associated <input> element. In this case, preprocess_css.


Do I have to move contributed modules to "sites/all/modules" for upgrading?

You don't have to, but it is highly recommended. It greatly ease identification of the files to keep while upgrading (and following the upgrade documentation).


How do I cache my custom entities using entity api with entitycache?

You can achieve this quite easily with a few hooks and additions to your existing hooks.

Define the cache table in your hook_schema() implementation in your module's .install file:

// Optional cache table for entitycache support.
$schema['cache_entity_my_entity'] = drupal_get_schema_unprocessed('system', 'cache');
$schema['cache_entity_my_entity']['description'] = 'Cache table used to store my_entity entity records.';

This adds a db table that can be used to store your cached entities.

Add an update hook to create the table:

function my_entity_update_700X() {
  if (!db_table_exists('cache_entity_my_entity')) {
    $schema = drupal_get_schema_unprocessed('system', 'cache');
    $schema['description'] = 'Cache table used to store my_entity entity records.';
    db_create_table('cache_entity_my_entity', $schema);
  }
}

Enable entitycache in hook_entity_info(). Add this near the bottom before return $info;

if (module_exists('entitycache')) {
  $info['my_entity']['field cache'] = FALSE;
  $info['my_entity']['entity cache'] = TRUE;
}

Implement hook_flush_caches() in your .module file:

/**
 * Implements hook_flush_caches().
 */
function my_entity_flush_caches() {
  return array('cache_entity_my_entity');
}

And that's it! Entity API takes care of the interactions and things like load() and resetCache() (I found you have to implement those functions when adding entitycache functionality to non-entityapi entities)


How to set number of articles per page on the Blog module?

Looking at blog_page_last and node_page_default, I see that both use the persistent variable called "default_nodes_main" (which defaults to 10) for the number of nodes per page. That variable can be set on the form at /admin/content/node-settings, under "Number of posts on main page".

The above means that both the /node and /blog pages use the same value. If you want different values for both pages, you probably need to rebuild one (or both) of them as a view.

I hope that answers your question.


Custom module with custom theme/template

As Clive said, you can simply return HTML instead of the render array, e.g.

function myApp_theme() {
    $html = "Hello World;
    return $html;
}

A more general way is to modify the page.tpl.php in your theme and add a wrapper around the normal styling.  E.g.

<?php if ( $plain_page ) { ?>
  <?php print render($page['content']); ?>
<?php } else { ?>
Normal stuff
<?php } ?>

Then in your module, use the template_preprocess_page hook to set the $plain page variable.  E.g.

my_module_preprocess_page( &$vars ) {
  [ check if it's a page you want as plain ]
    $vars['plain'] = TRUE;

You will only need the content for the  tags as the html.tpl.php template handles that.


Here's a step-by-step:

Install the UI Patterns Views module
Insert the fields and map them to the UI Pattern fields

Note: You are mapping fields for the rows.

At this point, each piece of content should be rendered as a UI Pattern

Now, if you want to arrange the cards in a specific way (say, using Masonry), then you can do it in one of the following ways:

Add a class to the entire view, say, js-view-masonry – you can then use this class in JavaScript to detect this view and apply the JS plugin that organizes the cards like you want.
The other way will be to create a superpattern of the card pattern. Say, a card_collection pattern, with a field named items. Next, override the view's template, especially the part where the rows are rendered. Here, instead of displaying the rows, into the "card_collection" pattern.

Here's a working example of the second method using "card_collection". The blog list consists of 2 patterns. The "card" pattern and a pattern called "card collection" which wraps the cards.


How to set the default value of an exposed filter rather than -Any-?

You can use hook_form_alter() to alter the any drupal form.
example :

function yourmodule_name_form_alter(&$form,&$form_state,$form_id){
  if($form_id == 'views_exposed_form'){
  $form['field_width_value']['#default_value'] = 'whatever you want';
  unset($form['field_width_value']['#options']['All']);

 }
}


Problem with images not displaying because domain is incorrect

The first thing you need to do is stare at your Apache access logs for a while and see if you have inbound requests to the wrong URL.  You may need to configure per virtual host logfiles to see which vhost is handling which.

You may also want to disable Drupal caching (both page and block) to see if the problem persists.

My guess is that everything with your Drupal configuration is correct, but that you have inbound requests that Drupal is handling because it is the default site, and these are getting cached.

If the Apache logs indicate that Drupal is getting the wrong URL, then I would do the following:

Configure both virtual hosts to respond to the canonical URL, and the redirections.  Something like

ServerName www.example.com
ServerAlias example.com *.example.com

This will make sure the proper vhost is responding to the proper domain (which is guess is the root cause of your problem, ie you need a ServerAlias).

Configure httpd.conf or .htaccess to set up canonical URL redirection for both the Wordpress and Drupal sites.  Something like

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]

These help ensure that Drupal and Wordpress only ever see requests for a single hostname.

These two things make good sense on most live sites, too.

If you still have the wrong URLs and you are 100% positive about the traffic, then my next guess would be that you have a misconfigured settings.php somewhere in your organization, and you have two sites / servers running out of the same database (eg, DEV and LIVE are actually using the same database).  To fix this, you would need to find the offending site.


Trying to create a user with an entity reference taxonomy term using services

I was able to get it working with the following on checkboxes and select:

"field_likes": {
"und":{
"target_id": "1"
      }
}

This technically solves the problem, though I'm not sure how to send up multiple values this way.

EDIT:

Here is the actual solution, which not only allows you to put in entity reference taxonomy terms, but multiple as well:

"field_likes": {
                 "und":{
                         "target_id": "1",
                         "target_id_1": "2"
                        }
                }

This is with the select list widget, which I think is important for this particular example (based on other links I've been reading).


Field and storage settings on base fields

The base field definition implements the FieldDefinitionInterface and the FieldStorageDefinitionInterface, so it can act like a form API field, though it's not managed by the field module.

So the base field definition contains the settings of both, which you can see how the default values are set in BaseFieldDefinition::create():

  public static function create($type) {
    ...
    $default_settings = $field_type_manager->getDefaultStorageSettings($type) + $field_type_manager->getDefaultFieldSettings($type);
    $field_definition->itemDefinition->setSettings($default_settings);
    return $field_definition;
  }


How to configure CkEditor's styles dropdown?

1. Your Custome style should be present in your CSS file. 2. Your FILTER SETTING should be proper. To check, same way as yours, I just enabled style and and put h1.heading-a|Title(which I took from css/base/elements.css for example purpose) in style dropdown and and it did show up as shown in the second image.

Second Image

Hence, the issue is, to properly put the Class|Key in the Styles dropdown section and make sure that it is available in CSS.

Later to check custom one, I did put h2.myclass {color: red} in elements.css and saved and cleared cache. And as you can see it showed up in following image

UPDATE-1: FILTER SETTING

Now the reason why, Horizontal line and Underline iCon are not visible as you have stated in your comment. For that you need to check the FILTER SETTINGS. Have you played with Limit allow HTML tags and correct faulty HTML list which you can see at the bottom of the basic HTML setting page as shown in following image. If you delete
 from the list the icon will not shown up. Just I checked, if I remove
 form list the icon also gets disappeared.

And your Enable filter setting should be as shown in following image.


When and where does Panels get the title out of a View?

I was hoping that someone would answer this, so I wouldn't have to answer my own question when I found the solution.

Credit goes to a co-worker (who doesn't really post here) who reminded me that you also need to update the handler:

function foo_views_pre_view (&$view, &$display_id, &$args)
{
  $view->display[$view->current_display]->display_options["title"] =
  $view->display[$view->current_display]->handler->options["title"] = "Foo";
}

When you do this, the title does propagate properly to the pane title.


How can I add extra parameter to URL when click "apply" button of Views exposed filter?

You can use a hook_form_FORM_ID_alter() to add a hidden form element with the value that you want (1 in your example). You'll have to check the View name and display name to ensure you only affect the right exposed filter.


Does Drupal have any security like Dexterity in Plone?

Drupal has a powerful access control to allow users, site builders and developers grant or deny access to content created in it. The basic of access control is the triplet user-group-permission, where you have users associated to roles associated to permissions.

There's a lot of Drupal contributed modules to extend these features. Content Access is a cool module to restrict content to some roles based on it's own type. Domain Access is another control acccess module, a lil more complicated, which handle the access control to affiliate content to "subsites" (domains, subdomains or non-standard ports). So, if you make a little search in the Modules page of drupal.org for "ACL", "access control" or something like, you'll find a lot of resources to bootstrap your web software development.

Keep drupalizing!


Combine views sort criteria in exposed form

Use Better Exposed Filters module:

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.


I think you can find an answer in this similar question here: How do I enable comments for user profiles?

Apparently, Profile2 module allows that functionnality.


What is the difference between user_is_anonymous() and user_is_logged_in()?

The functions are essentially opposites.

The only real difference is the user_is_anonymous() function has an additional check for $GLOBALS['menu_admin'] to allow menu admins to be able to administer menu links that are visible to anonymous users only.

It's used by drupal_valid_path() as well as the menu_overview_form() function:

function drupal_valid_path($path, $dynamic_allowed = FALSE) {
  global $menu_admin;
  // We indicate that a menu administrator is running the menu access check.
  $menu_admin = TRUE;
  if ($path == '<front>' || url_is_external($path)) {
    $item = array('access' => TRUE);
  }
  elseif ($dynamic_allowed && preg_match('/\/\%/', $path)) {
    // Path is dynamic (ie 'user/%'), so check directly against menu_router table.
    if ($item = db_query("SELECT * FROM {menu_router} where path = :path", array(':path' => $path))->fetchAssoc()) {
      $item['link_path']  = $form_item['link_path'];
      $item['link_title'] = $form_item['link_title'];
      $item['external']   = FALSE;
      $item['options'] = '';
      _menu_link_translate($item);
    }
  }
  else {
    $item = menu_get_item($path);
  }
  $menu_admin = FALSE;
  return $item && $item['access'];
}


Yes it's safe to remove them. But I would recommend you not doing so. These modules are just tiny modules and it won't give more than 1 MB of space to your system.

However, if you are no longer using a module, make sure you have uninstalled that module. If you had search module enabled and if you are no longer using it, disabling it and uninstalling it will clear existing search index and now you could get a lot of database space saved.

If saving every bit of the space is worth, look at your third party libraries. They often come with folders such as docs and examples in it that actually do not help in terms of the site functionality.

Other places that you might want to check include, log folders (Apache logs), SSH command logs, old backups from Backup and Migrate module (or other backups), obsolete caches (Admin > Configuration > Development > Performance > Clear All Caches  -- this will clear all caches, including in-use ones), watchdog (Administer > Reports > DB Log > Clear), spam comments (Admin > Content > Comments > Unapproved).

Make sure you keep a backup of the system for your own safety!


Creating view using a field(checkbox) as Contextual Filter

If you want this filter you should add the field as a "standard filter" and not contextual filter. In Views UI look for the headline Filter criteria, add your field "featured" and choose what value that has to be set.

Here is a screenshot how the UI looks, it is under filter criteria where you should push add.


How do I enable and use the password module for Drupal 6?

No, this module works as any other module. See my screenshot as I can see it in my module listing -

Are you sure you have it in sites/all/modules/ ? Are the permissions correctly set?


Why can't I find the parent term of a tag when a node is being inserted?

Did you try taxonomy_get_parents_all()?

$parents = taxonomy_get_parents_all($tid);
  foreach ($parents as $term) {
    $pterms[] = $term->name;
  }


Get customer shipping information entered in checkout page, from shipping page

See the replacement patterns and give like as below, for example,
[commerce-order:commerce-customer-shipping:field-name-line]. Use "-", not "_".


Use a field's values in database to populate an exposed filter's options

This topic migth be useful for you.

You can also create taxonomy vocabulary years and than select filter will be able to use in views.


How to set a flag at node when user view node?

Using the Rules module seems like a no brainer to me to get this to work, with no custom module(s) needed ...

Here is how your custom rule should look like (a kind of getting started with Rules):

Rules Event: When viewing content.
Rules Condition: Check the content type that matches your needs.
Rules Action: Flag the node being viewed by the current user.

Ps: I'm assuming this is about D7.


Yes, hook_css_alter can be used with external CSS.


Using Git to keep Core and modules up to date

You can done it easily with Git with the submodules. Every subfolder from yours sites/all/modules (for example) can be a submodule that clone the repo from drupal.org.


You can add per user preference settings. Check this for a working example of how to add a preference setting in the user profile form and how to store and read it.


Is there a module that creates a taxonomy of the world's languages?

I searched for such a module fairly extensively but was unable to find anything.

In the end, I used the Taxonomy CSV Import/export module, which allows you to create a list based on a CSV (comma-separated value) file, which is very easy to prepare.  I then referenced one of the lists of languages on Wikipedia.  I would share my list with you except that mine is specific to my site; it doesn't list all human languages, but instead just the most popular ones in Asia.


How to sort on different columns in the same view?

In Drupal 8, if you want to alter an ORDER BY, in particular to use a formula, you have to add an expression and then order by it:

$query->addExpression('SUBSTRING(thread, 1, (LENGTH(thread) - 1))', 'order_field');
$query->orderBy('order_field', 'ASC');

There can be some confusion in Views, because their version of addExpression is Sql::addField. And in fact, Sql::addOrderBy let's you add a field and order by it in one call.

So, your code would look like:

$sql = <<<SQL
CASE
     WHEN node_field_data.last_name IS NULL THEN node_field_data.title
          ELSE node_field_data.last_name
END
SQL;

$query->addField(NULL, $sql, 'last_name_else_title');
$query->orderby[] = array(
  'field' => 'last_name_else_title',
  'direction' => 'ASC',
);

Or just...

$query->addOrderBy(NULL, $sql, 'ASC', 'last_name_else_title');

Thanks agileadam for pointing out the failure point (see also).


Can you post the callback function generating the page at 'ri_email/ajax'?

It should look something like this:

<?php
  function awesome_ahah_callback() {
    $thing_to_process = $_POST['thingfromform']
    /* do stuff, including generating some kind of $processed_data variable */

    drupal_json(array(
      'status' => TRUE,
      'data' => $processed_data,
    ));
    exit();
  }
?>

If you aren't generating the thing you want to send back through AHAH with drupal_json and then calling exit() then I don't think it will work.


How to use Rules send an email with a list of nodes that fill certain conditions?

When you want to run a rule periodically, use the event Cron maintenance tasks are performed.

This will trigger your rule whenever cron runs.

See the cron documentation on drupal.org for more information on cron and its configuration.

Because this action doesn't specifically involve nodes, the next problem is loading the nodes you want to act on.

How you do that depends on which nodes you want to load the nodes. Examples are (there are likely also other ways):

The Load a list of entity objects from a VBO View action that is provided by the Views Bulk Operations module. This was you can set up a view that lists the nodes you want to target and load the nodes from that list.
The Fetch entity by property action. This could be used to fetch all content of a given content type.

When you have a list of entities you can loop add a loop to your actions to loop through the list and perform actions on each entity.

If you need to check perform conditions as you are looping through (like checking the value of a field on the entities) you can use the Conditional Rules module to add if blocks.


Can a group of fields be added to $form in buildForm()?

It turns out fieldset is what I was looking for:

  Provides a render element for a group of form elements.


Send node as HTML formatted email to all users of a role

It may depend on your config. Here's a solution relying on Mime Mail and Mail System, as Mime Mail integrates smoothly with Rules.

Download and enable these 2 modules. Then you'll have a few steps configuring it :

Mail System: select MimeMailSystem in both "Site-wide default MailSystemInterface class" and "Mime Mail module class" drop-down list.
Mime Mail: change it from "Plain text" to "Filter HTML".

Now when you edit your rule, you'll see an action "Send HTML mail to all users of a role". Select editor role. You're done :)

Find even more details in this step by step tutorial: How to Send HTML Emails in D7 using Rules

EDIT : Alternative solution.

Download simplenews and enable both simplenews and simplenews rules. Set up the module.
Create a editors newsletter. Deactivate Subscription block
Enable "Use as simplenews newsletter" in the content type options you wish to send as HTML formatted email.
Create a rule : after editing a user account, condition user has role editor, subscribe user to newsletter editors  (and reverse rule to unsubscribe)
Create a rule : after saving a node, condition content-type is..., send newsletter :The newsletter node to be sent.: [node]


In case it helps someone - I solved the issue by creating a view block of Messages, then I:

Added a relationship with the Taxonomy term referenced from the event_type field.
Added a relationship with the User using the event_notification_preferences field.
Added a contextual filter for User: User ID and got the default
value from the currently logged in user.


Profile 2 Not showing fields on user edit page

Give the permission "[PROFILETYPE]Edit own profile" under "Profile2" section to the respective user roles.

And the fields will be appeared on edit user page.


How can I link a text field to a user profile such that I can display nodes on the user profile based on that text field

I can see how you'd want the Producer to be able to create an event and assign instructors to it before the instructor has an account. So in that case, have a node type which represents the instructor. This would be like a bio page or CV or some-such.

Then use nodereference and/or entityreference fields, Views, and viewreferences to connect the dots. The Event type would have Instructor fields which would refer to the bio pages for the instructors. As the instructors created accounts, a viewfield on the user profiles would show the bio page, keyed by an email acct field which you'd be sure and add.

Complex but not hard. :-)


Does 'managed file' type form api support the properties #prefix and #sufix?

Yea..all though drupal 7 form api for managed_file shows #prefix/#suffix is supported, it did not work for me either.
So I tried using #field_prefix and #field_suffix and it worked. :)
I know this is a old post but I am posting answer hoping it will help someone. :->


how to get nid of a node when user is not on a node page

You'll want to Query the database for the nodes you need and then use the results of that query to populate the #options property. Something like this:

<?php
    $result = db_select('node', 'n')
    ->fields('n')
    ->condition('type', 'node_type_name','=')
    ->condition('status', 0,'>')
    ->execute()
    ->fetchAssoc();
?>

You can then use the results of that query easily since it comes back as an associative array. You'll want to specify exactly which fields you want (in your case, probably just title and node. See http://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7 for how to do a proper select.


How to add permissions and configure links to a module in the /admin/modules page?

Configure is the configure key in yourmodule.info.yml, containing a route name, usually your primary settings form/page.

Permissions link automatically shows by having permissions defined in your module.


Version numbers of dependencies in testing

From the module.info file docs: ( quite long, but informative )
dependencies
An array of other modules that your module requires. If these modules are not present, your module cannot be enabled. If these modules are present but not enabled, the administrator will be prompted with a list of additional modules to enable and may choose to enable the required modules as well, or cancel at that point.
The string value of each dependency must be the module filename (excluding ".module") and should be written in lowercase like the examples below. Spaces are not allowed.
dependencies[] = taxonomy
dependencies[] = comment

In addition, test_dependencies[] can be used to indicate dependencies which are optional but recommended. At this writing they are supported only by Drupal.org's automated testing system. They cause the testbots to check out the projects suggested.
test_dependencies[] = autoload
If you need to specify that a certain module's version number is required Drupal 7 provides a way for this in the dependencies[] field. Version numbers are optional and only necessary if the module absolutely requires another module's specific version or branch.
The syntax for the dependencies[] field(s) is:
dependencies[] = modulename (major.minor)
Where major is the numeric major version number and minor is the numeric or alphanumeric minor version number. x can be used to denote any minor version. Some examples follow.
name = Really Neat Widget
description = An example module
dependencies[] = exampleapi (1.x)

test_dependencies[] = autoload (>7.x-1.5)
...

In the above .info code, the "Example" module requires an "Example API" module with the major version of 1 and any minor version.
dependencies[] = exampleapi (1.0)
This means that the module requires the 1.0 (and only the 1.0) version of the Example API module.
dependencies[] = exampleapi (1.x)
The above module requires any minor version of the module in the 1.x branch (1.0, 1.1, 1.2-beta4, etc.)
The dependencies[] property in the .info file can also optionally specify versions:
= or == equals (optional: equals is the default)
> greater than
< lesser than
>= greater than or equal to
<= lesser than or equal to
!= not equal to

dependencies[] = exampleapi (>1.0)
The above module requires any version greater than version 1.0.
You can optionally specify the core version number as well:
dependencies[] = exampleapi (>7.x-1.5)
The above module requires a 7.x version compatible version of the module and a version greater than 1.5.
Additionally, multiple version dependencies can be specified as comma-separated values within the parentheses:
dependencies[] = exampleapi (>1.0, <=3.2, !=3.0)
This facility can be used to specify a minimal core version by using system as the module name:
dependencies[] = system (>=7.53)
This makes the module require at least Drupal 7.53.
More info: http://drupal.org/node/542202#dependencies


I ended up having to hide the specific pager with css in the case I did what you are trying to do...


Actually, db_fetch_object() could also return NULL, contrary to what the documentation says. The documentation assumes you aren't passing to the function a value that for PHP is equivalent to FALSE, for example NULL, an empty array, or an uninitialized variable. If the function gets a value that for PHP is equivalent to FALSE, the function will not execute any instruction, and it will return NULL.
function db_fetch_object($result) {
  if ($result) {
    return mysql_fetch_object($result);
  }
}

The same is true for other database engines, for example PostgreSQL, which uses the following function.
function db_fetch_object($result) {
  if ($result) {
    return pg_fetch_object($result);
  }
}

This is usually not a problem, since the function should normally be called as in the following snippets.
 if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
    $block['subject'] = check_plain($category->title);
    $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
    $read_more = theme('more_link', url('aggregator/categories/' . $category->cid), t("View this category's recent news."));
  }

  while ($item = db_fetch_object($result)) {
    $items[] = theme('aggregator_block_item', $item);
  }

In both the cases, the control statements will not be executed, since for them NULL is equivalent to FALSE.


A file that comes in from a browser's Web API as a Blob is probably base64-encoded. PHP will not decode files in the POST or GET parameters. It is up to the PHP application to decode the file before saving.

if (!empty($payload['blobFile'])) {
  $name = str_replace(' ', '_', $payload['fileName']);
  $file = file_save_data(base64_decode($payload['blobFile']), 'public://' . $name, FILE_EXISTS_REPLACE);
  $content['field_media_file'] = ['target_id' => $file->id()];
}

It might also be useful to check if the binary is actually a PDF before saving, but that could be done in different ways based on opinion (loading via a PDF library, checking file headers, virus/malware scan).


See https://www.drupal.org/node/2116263.

You either need to run it inside the core folder, or (easier IMHO), you need to pass the -c core argument, so it finds the phpunit documentation.

Also note that only a part of Drupal's tests are phpunit, others are based on our own test framework and you need to run them with run-tests.sh or through the UI.

That said, you only need to run core tests if you work patches for Drupal core. Drupal's tests always path, nothing is added unless it is passing all tests.


How to share content title, image and body on Instagram?

If you want to show Instagram feeds in your website (as in revision 2 of your question ...), then there are typically 3 modules to pick from (quotes are from their project pages):

Instagram Block:

  ... integrates with Instagram and creates a block containing your most recent instagram posts.

Instagram Feeds:

  This is a Feature module. It allows you to create Instagram feeds for your site that will download images from Instagram using filtering by hashtags and / or usernames.

Drupagram:

  In this early implementation the module will interact with the Instagr.am API and be able to fetch media items. Advanced methods like relationships between Instagr.am users and such will be added later on.

Note: posting to Instagram doesn't seem to be available, since that isn't allowed through their API (by design).


It's in <drupal_root>/modules/update. If not, it means you damaged your core.

Try drush en update - it should re-enable it for you. After performing updates you are allowed to disable it again.


Can I filter the list of candidates used by the menu system to determine the menu trail?

Unfortunately menu_link_get_preferred does not sort it's results. If two items match the same paths, it will just return the first result returned by the database. There is an ongoing issue about this: drupal.org/node/1649062

You can workaround this by ensuring the menu you want was added first in the database, but that's not a sustainable way of addressing this. The order might change after you restore a backup, when you compact your database, or after the next Drupal update if they address the issue.

If you cannot work around the issue another way, I think patching core with the patch provided in the issue is safer. The patch sorts the preferred links by mlid, which means you need to create the preferred menu item last (but unlike the workaround before, this will still work even if your database gets re-written).


Working with operators when manually specifying options for a custom views exposed filter

This doesn't answer your question exactly but gives an alternative.

Views exposed filters have a grouping functionality that can be used to create predefined value/operator pairs, so you can configure it to give options like Japan & not Japan without actually giving the user the ability to select the operator.

Much nicer for the user.

See the attached screenshot as an example of a possible solution to your problem that requires no custom code (note I am guessing that JP is the correct value in this case).

There are a couple of things to be aware of:

There is a bug where if you use is empty or is not empty you still have to enter a value, even though it is never used. See https://drupal.org/node/1818176
You might get undesirable results if not all your content has country data. The reason is that if a field doesn't have data it is NULL and in views/sql you need 2 separate operators to match not a string vs not null. The grouping in views doesnt' let you select multiple operators so you cant have both "is not Japan" OR "is null". If your country data is a required field you have no problem here. - It's possible in this case you could alter the views query if "Not Japan" is selected and add in the "OR country IS NULL". You should be able to do that in hook_views_query_alter() and it still should be simpler than your current approach.

Note: I opened an issue for Add new filter operator "Is not equal to OR is empty"


How to get the data of field collections

These are the field data types and their column names:

Text - value
Entity Reference - target_id
Term Reference - tid

Combine that with field_get_items(), e.g.:

$items = field_get_items('node', $node, 'field_suppliers_value');

if ($items) {
  // Or $items[0]['target_id'], etc
  $fc = field_collection_item_load($items[0]['value']);
}

Hopefully that'll give you enough to go on.


Page template suggestions are not working

As reported in Drupal 7 Template Suggestions, the template suggestion used by default from Drupal 7 for pages is page--[front|internal/path].tpl.php.

For a page visible at http://www.example.com/node/1/edit, Drupal would look for the following template files:

page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php

To add extra suggestions, your theme should implement template_preprocess_page() and add new suggestions in $variables['theme_hook_suggestions'] ($variables is the variable passed by reference to the function).

If you did that, then the only reason the suggested template file is not being used is because the file is not correctly named: in the case the page shows a book page, for example, the template file should be page--book.tpl.php. You could change the code for your theme, and let it use the page--node-type.tpl.php template, if it doesn't find a template like page--book.tpl.php.

To notice also that, in theme_get_suggestions() (which is the function called by template_preprocess_page()) hyphens are replaced by _, and not vice versa.
The reason that is done is explained in a comment reported in the function code.

// When we discover templates in drupal_find_theme_templates(),
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);


Large Binlogs Generated When Reverting Features

DISCLAIMER : Not a Drupal Expert, Just a MySQL DBA

There are really two classes of answers for this question

STANDALONE DB SERVER
MASTER/SLAVE REPLICATION

STANDALONE DB SERVER

If you know you are going to perform a feature-revert, the simplest thing to do is this

StandAlone Method #1 : Disable Binary Logs

STEP 01) Run SET GLOBAL SQL_LOG_BIN = 0;
STEP 02) Run your feature-revert
STEP 03) Run SET GLOBAL SQL_LOG_BIN = 1;

This will disable binary logging during the feature revert and reenable afterwards

StandAlone Method #2 : Erase All Binary Logs Except the Last One

You could crontab a job that runs this:

PURGE BINARY LOGS BEFORE NOW();

StandAlone Method #3 : Erase All Binary Logs

You could crontab a job that runs this:

RESET MASTER;

MASTER/SLAVE REPLICATION

In standard MySQL Master/Slave Replication, a Master Has Binary Logging Active and the Slave Does Not. You cannot just disable binary logging like you would for a StandAlone DB Server because you need to replicate the DB Changes of the feature-revert.

Here is what to do stem the rise of binary logs and relay logs

Replication Master (Manage Binary Logs)

At the completion of a feature-revert, which binary logs are safe to remove so that MySQL Replication can still work and remain intact?

Here is what you do:

STEP 01) Run SHOW SLAVE STATUS\G On the Slave.

For example:

mysql> show slave status\G
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: 10.64.97.249
                Master_User: replicant
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000658
        Read_Master_Log_Pos: 799061333
             Relay_Log_File: relay-bin.003861
              Relay_Log_Pos: 47059
      Relay_Master_Log_File: mysql-bin.000658
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 799061333
            Relay_Log_Space: 47059
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0
1 row in set (0.00 sec)

STEP 02) Get binary log from Relay_Master_Log_File

Field #10 of SHOW SLAVE STATUS\G
That would be mysql-bin.000658

STEP 03) On the Master, Run PURGE BINARY LOGS TO 'mysql-bin.000658';

Replication Slave (Manage Relay Logs)

To force a Slave to Throttle the amount of Relay Logs to Just 2GB, add this to the Slave's my.cnf

[mysqld]
relay_log_space_limit=2G

and restart mysql on the Slave. When a Relay Log is fully processed it is automatically deleted and makes room for the next Relay Log.

EPILOGUE

You should make sure you have this set in /etc/my.cnf on the StandAlone DB Server or Master

[mysqld]
expire_logs_days = 3;

and restart mysql. This will make sure all binary logs older that 3 days are automatically deleted.

If you are curious and want to know what runs in a feature-revert You could

Look through source code of the feature-revert module
take the binary logs and dump the contents in plain text SQL

Run the following:

mysqlbinlog mysql-bin.000138 mysql-bin.000139 mysql-bin.000140 mysql-bin.000141 > Revert.sql
less Revert.sql

UPDATE 2012-08-09 12:40 EDT

If you are concerned with point-in-time recovery, you must decide how many days worth of binary logs you are willing to keep.

Here is a scenario: Say you want to be able to revert back up to 7 days ago. You would have to setup the following:

STEP 01) Have the Slave maintain its set of Binary Logs with an expiration of 7 days

Add this to /etc/my.cnf on the Slave

[mysqld]
log-bin=mysql-bin
expire_logs_days=7

STEP 02) service mysql restart

STEP 03) Perform a midnight Backups on the Slave as follows

STOP SLAVE;
FLUSH LOGS;
mysqldump on the Slave
START SLAVE;

STEP 04) Delete backups older than 14 days

Once you have Steps 3 and 4 automated, you must let mysql rotate the binary logs on the Slave. You should not manually delete the binary logs on the Slave. Keep in mind that point-in-time recovery is not automatic. It is rigorous manual process.

Would you like a description of a point-in-time recovery ??? Here we go...

Let's say you have the following

It's August 9, 2012 12:11 PM
run mysqldumps on the Slave every night at midnight
each backup is named by date Backup_99999999.sql in /backups
and you have the following list of binary logs on the Slave

_

-rw-rw---- 1 mysql mysql 1073742269 Aug  2 11:22 mysql-bin.001789
-rw-rw---- 1 mysql mysql 1073762807 Aug  2 16:22 mysql-bin.001790
-rw-rw---- 1 mysql mysql 1073742048 Aug  2 21:28 mysql-bin.001791
-rw-rw---- 1 mysql mysql 1073741969 Aug  3 06:34 mysql-bin.001792
-rw-rw---- 1 mysql mysql 1073741954 Aug  3 11:20 mysql-bin.001793
-rw-rw---- 1 mysql mysql 1073742182 Aug  3 16:19 mysql-bin.001794
-rw-rw---- 1 mysql mysql 1073742228 Aug  3 21:37 mysql-bin.001795
-rw-rw---- 1 mysql mysql 1073753003 Aug  4 06:32 mysql-bin.001796
-rw-rw---- 1 mysql mysql 1073742100 Aug  4 13:18 mysql-bin.001797
-rw-rw---- 1 mysql mysql 1073741891 Aug  4 18:56 mysql-bin.001798
-rw-rw---- 1 mysql mysql 1073742424 Aug  5 06:12 mysql-bin.001799
-rw-rw---- 1 mysql mysql 1073742017 Aug  5 18:35 mysql-bin.001800
-rw-rw---- 1 mysql mysql 1073741952 Aug  6 05:27 mysql-bin.001801
-rw-rw---- 1 mysql mysql 1073757571 Aug  6 13:00 mysql-bin.001802
-rw-rw---- 1 mysql mysql 1073742172 Aug  6 17:35 mysql-bin.001803
-rw-rw---- 1 mysql mysql 1073742067 Aug  7 00:35 mysql-bin.001804
-rw-rw---- 1 mysql mysql 1073777487 Aug  7 10:45 mysql-bin.001805
-rw-rw---- 1 mysql mysql 1073791986 Aug  7 15:51 mysql-bin.001806
-rw-rw---- 1 mysql mysql 1073742035 Aug  7 20:37 mysql-bin.001807
-rw-rw---- 1 mysql mysql 1073741978 Aug  8 05:28 mysql-bin.001808
-rw-rw---- 1 mysql mysql 1073742217 Aug  8 10:30 mysql-bin.001809
-rw-rw---- 1 mysql mysql 1073742422 Aug  8 14:41 mysql-bin.001810
-rw-rw---- 1 mysql mysql 1073743447 Aug  8 18:47 mysql-bin.001811
-rw-rw---- 1 mysql mysql 1073742241 Aug  9 00:36 mysql-bin.001812
-rw-rw---- 1 mysql mysql 1073741985 Aug  9 08:45 mysql-bin.001813
-rw-rw---- 1 mysql mysql  743967477 Aug  9 12:10 mysql-bin.001814

You want to reload the Master going back to August 5, 2012 02:30 PM

Here are you steps

STEP 01) Take all binary logs that encompass August 5, 2012 from 12:00AM to 2:30PM. This would be binlogs mysql-bin.001799 and mysql-bin.001800. These are used because

PRINCIPLE : the first write of a binlog is also the last write of the previous binlog

the last write to mysql-bin.001798 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the first write to mysql-bin.001799 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
the last write to mysql-bin.001799 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the first write to mysql-bin.001800 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
the last write to mysql-bin.001800 is Aug 5 18:35 (6:35PM) 2012-08-05 18:35:00

The range 2012-08-04 18:56:00 to 2012-08-05 18:35:00 is the narrowest range that surround 2012-08-05 00:00:00 to 2012-08-05 14:30:00. This is why binlogs mysql-bin.001799 and mysql-bin.001800 are the correct choices

STEP 02) Generate all the SQL that ran August 5, 2012 from 12:00AM to 2:30PM

mysqlbinlog --start-datetime="2012-08-05 00:00:00" --stop-datetime="2012-08-05 14:30:00" mysql-bin.001799 mysql-bin.001800 > ForwardChanges.sql

STEP 03) Make a copy of the August 5, 2012 midnight backup to PITR.sql

cp /backups/Backup_20120805.sql PITR.sql

STEP 04) Append ForwardChanges.sql to PITR.sql

cat ForwardChanges.sql >> PITR.sql

STEP 05) Load PITR.sql into the Master

mysql -h IPAddressOfMaster -u ... -p... < PITR.sql

When the script is done, the database will be in the state it was as of August 5, 2012 2:30PM

Pretty easy, huh ???


Embedding a view for search and redirection

Following this reply on drupal.org and this answer on SO, I added a hook:

function my_module_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'my_view_id') {
    $view->override_url = Url::fromRoute('<current>');
  }
}

Some of the assumptions in Drupal and the workarounds are so annoying. Days wasted. :(


This answer to a stackoverflow question does a great job at explaining the attack that can get around mysqli_real_escape_string() using multi-byte character sets.

I've concluded that when running Drupal 6, we do not have to set the charset at the server level in order to be safe from the attack.

Drupal always sets the client to UTF8 (and not the GBK or BIG-5 charsets that are required for the exploit). Newer versions MySQL (> 5.1) are also not vulnerable.

HOWEVER, although Drupal is safe from this exploit, we should still follow the installation documentation which states, "The database should be created with UTF-8 (Unicode) encoding, for example utf8_general_ci.".

One helpful comment on the installation docs outlines how to create your database with UTF8 encoding, and how to ensure that UTF8 is used when performing a backup/restore:

  To achieve this by the mysql command line interface use the following commands:
  $ mysql -u root -p # Login
  mysql> CREATE DATABASE databasename CHARACTER SET utf8; # Create with utf-8

  When using mysqldump/mysql for backup/restore also force both server and client to utf8 by inserting into /etc/mysql/my.cnf:
  default-character-set = utf8 # Server
  skip-character-set-client-handshake # Force client


Here's a SQL-centric explainer: each field in Drupal 7 has two storage tables associated with it:

field_data_{name-of-field}
field_revision_{name-of-field}

In both cases, the field contents will be in a column like {name-of-field}_value. You can run a MYSQL UPDATE with a REPLACE function to bulk update URLs in these tables.
So if you find that the text you need to update is in the 'field_body' table:
UPDATE field_data_field_body SET field_body_value = REPLACE(field_body_value, 'oldurl.com', 'newurl.com');
UPDATE field_revision_field_body SET field_body_value = REPLACE(field_body_value, 'oldurl.com', 'newurl.com');

Immediately after running these queries, you must clear the Drupal cache. This is best done from the "Performance" admin page in the Drupal UI. If you insist on SQL-only remedies, you can clear the particular relevant cache with this:
TRUNCATE TABLE cache_field;

The regular caveats apply:

Have a backup of your database ready, and verify that the backup you have restores correctly!
Be judicious about your REPLACE functions, that you don't accidentally replace more than what you thought you were targeting.
Yes, you should perform the REPLACE against both the data and the revision tables.


change views global text field conditionally

Ok so credit goes to https://www.webfoobar.com/index.php/node/65 which basically gave me the answer.  The working code is as follows:

function MODULE_NAME_views_pre_render(&$view)
{
    if ($view->name == 'user_dashboards' && $view->current_display == 'my_tutorials')
    {
        foreach ($view->result as $index => $value)
        {
            $tutorialtime = strtotime($value->field_field_tr_tutorial_start[$index]['raw']['value']);
            if($tutorialtime < strtotime('now'))
            {
                $oldtutorials[] = $index;
            }
        }
        $view->style_plugin->render_fields($view->result);
        foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result)
        {
            if(in_array($index, $oldtutorials))
            {
                $rendered_result['nothing'] = '';
            }
        }
    }
}


How to make a panel page the default local task

I was eventually able to get this to work. The page needed to be a "default menu tab" with the path entity/%/view or similar. With that, entity/% loads the path entity/%/view and all of the tabs show up as expected. This turned out to be more a problem with my understanding of default local tasks than anything else.


This particular solution was a custom form, where I had fine control over the CSS classes applied to the different elements, but it might also work for node-edit et al.

You would use hook_form_alter() to target whichever form you want.  Then, you would add a custom CSS class and an '#attached' property to that form element, containing a 'js' element which would point to a custom javascript file within your module.  The code in this file would watch elements of that CSS class for when a user hit 'tab', and then automatically click the 'Add More' button for you.  JS added below for reference:

(function ($) {
  Drupal.behaviors.formAutoTab = {
    attach: function (context, settings) {
      $('.othercustomclass').focus();
      $('.customclass').keydown(function (event) {
        if (event.keyCode == '9') {
          $('input[type=submit][id^=addbuttonidgoeshere]').mousedown();
          event.preventDefault();
        }
      });
    }
  }

})(jQuery);

The trick is .othercustomclass which you will need to refocus on the new element after it's added.  I think core Drupal does apply some sort of 'ajax-processed' class or something else to the fields added by the 'Add More' button, which you might be able to use as the jquery selector.


You need to find the user your server is running with (or the owner of files and folders). If your drupal is working correct besides this error then go to your website root and type ls -l in terminal. It will show you something like this:

-rw-rw-rw-  1 www-data charlie 6604 aug  8 04:04 authorize.php
drwxrwxrwx  3 www-data charlie 4096 nov 12 13:02 cgi-bin
etc.

Here you see the owner (www-data) and the group (charlie). This can be different on your system, but remember which you have for the chown-command below.

Give your /tmp folder the same owner. Go to /admin/config/media/file-system on your site and see the path to your tmp folder. If it starts with a '/' then it's located in the root of your system. If it doesn't start with a '/' then its relative to your website-folder, tmp for example is then really /var/www/httpdocs/tmp.

Then use chown -R www-data:charlie /path/to/tmp and you should be good to go. When you use your systems tempfolder at /tmp you really should create and set a subfolder inside /tmp.


Form is not submitting after ajax callback

I think the problem is that you only return the another-field in the ajax callback.

You probably have to make a wrapper for the submit and the another-field.

So you willl have:

$form['ajax_wrapper'] = array(
  'submit' => array(
    // Submit button...
  ),
  'another-field' => array(
    // Another field...
  ),
);

And then return $form['ajax_wrapper'] in your ajax callback.
Make sure to use $form_state['rebuild'] = TRUE;


So it turned out to be a two-fold issue. Thank you to Geoff and Clive who provided the larger part of the solution!

Step 1 - By default, the Date module renders a date field as a fieldset which is why the field name is differently styled and separated from the element a bit. The quick solution is to add a very short function to your template.php which tells the system to format a date field in the same way you'd format any other element. Like so:

function MYTHEME_date_combo($variables) {
  return theme('form_element', $variables);
}

I pulled that code from how to avoid fieldset in drupal date field

Step 2 - Edit the Content Type, Edit the date Field, expend "More settings and values", then expand "Advanced Settings", and change the Label position from "Above" to "None." That will get rid of the internal label.


How to compare a field value with each title values?

Finally, I found a solution with the module Field Validation and a PHP Code validation rule associated to my field Synonyms:

$args=array(':type'=>'specimen');
$titles=db_query('SELECT title FROM {node} WHERE type = :type',$args)->fetchCol();
foreach ($titles AS $title){
if ($this->value==$title){$this->set_error();}
}

It works like a charm.


Output an empty alt tag for an image in with views?

If you have disallowed the "alt" text in your field configuration, the system will output and empty value as you want. But if the field has a value in the attribute, you could modify it with hook_preprocces_field().


Setting up Multisite on windows server with IIS7

After much digging, found out the combo of msSQL and PHP 5.3 caused the site to break. Reinstalled with PHP 5.4 and mySQL and it's running swimmingly!


Converting a left join query with empty right side to Views

You can use this function

function MY_MODULE_views_query_alter(&$view, &$query) {
    if($view->name == 'view_name'){
       }
}

https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7


Changing value of min / max resolution for an image field dynamically based on a previous select list

I came up with a good solution using #ajax property from the Form API :

I declare hook_form_alter and add the #ajax on my push type select field.

/**
 * hook_form_alter
 */
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'push_node_form') {
    // Add id to field image for ajax reload
    $form['field_push_image']['#prefix'] = '
';
    $form['field_push_image']['#suffix'] = '
';
    // Create ajax reload function
    $form['field_push_type'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => 'reload_image_field_resolution',
      'wrapper' => 'image-field-to-reload',
      'method' => 'replace',
      'effect' => 'fade',
    );
  }
}

Then in the field settings I put a resolution as a key from the select list like this :

200x200|Square

200x400|Portrait

400x200|Landscape

And then I reload the image field with the proper resolution base on the select value key.

/**
 * Ajax callback to reload the image field
 */
function reload_image_field_resolution($form, $form_state) {
  // Get the value of the push type
  $type_value = $form['field_push_type'][LANGUAGE_NONE]['#value'];
  // Explode the value to make sure that it's a good safe key value representing
  // a resolution like this : 100x100
  $resolution = explode('x', $type_value);

  if (count($resolution) == 2 && is_numeric($resolution[0]) && is_numeric($resolution[1])) {
    // If the value is good, build a new array containing the new resolution
    $min_max_resolution = array(
      $type_value,
      $type_value
    );
    // Reset the max and min with of the image field
    $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']['file_validate_image_resolution'] = $min_max_resolution;
    // Set the variable to pass to the theme function with empty description otherwise
    // the old string (with the basic resolution) will be concatenated to the new string.
    $variables = array(
      'description' => '',
      'upload_validators' => $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']
    );
    // Return the approriate altered string using theme_file_upload_help()
    $form['field_push_image'][LANGUAGE_NONE][0]['#description'] = theme_file_upload_help($variables);
  }

  // Return the image field with its new resolution
  return $form['field_push_image'];
}


You could just write the code yourself in a custom module. What you want is pretty simple.

/**
 * Implements hook_user_login().
 */
function HOOK_user_login(&$edit, $account) {
  setcookie('user-is-logged-in', '1', 0, '/');
}

/**
 * Implements hook_user_logout().
 */
function HOOK_user_logout($account) {
  // Set cookie in the past and then remove it.
  setcookie('user-is-logged-in', '', REQUEST_TIME - 3600, '/');
  unset($_COOKIE['user-is-logged-in']);
}


Drush suddenly stopped working can't use PM command

So simple, why nobody saw this including me!.....seems like I can't run Drush from modules directory, only from root, never noticed before, haven't used Drush for a while ...

Not working

C:\aquiasites\fixing\sites\all\modules drush en color_field -y

Working

C:\aquiasites\fixing drush en color_field -y

[solved]


How to hide username displayed in code with Omega 3 theme

The theme function your trying to us is theme_preprocess_node, and you'r correct in replacing the Omega with [yourtheme].

The reason the function isn't getting called though is MYTHEME_alpha_preprocess_node should just be MYTHEME_preprocess_node. Alpha is part of the theme name, so if you remove it, the function should start working for you once you clear your cache.

EDIT ---------------------------------

Because drupal's template functions are still hooks, you can't just override the preprocess_node function, as omega's preprocess function is still going to run. However, what you can do is edit the $vars variable. Make sure you have the & in the param ( ie function (&$vars) ) so the vars is a reference.

From there, you should be able to modify the $vars['attributes_array']['class'] array and remove the unwanted class.

So if you put something like this in your code, that should get you close to where you might need to be.

function mytheme_preprocess_node (&$vars){
    $count = 0;
      foreach($vars['attributes_array']['class'] as $class){
        if(substr( $class, 0, 7 ) === "author-"){
          unset($vars['attributes_array']['class'][$count]);
        }
        $count += 1;
      }
}

EDIT 2 ============================

When I say remove the class from the var, I mean you should just be able to unset the variable (I updated my code snippet to show it inside the preprocess function).

You don't need to copy the whole of the omega_alpha_preprocess_node. What you actually are doing when you define your own theme_preprocess_node function is your telling drupal you would like to modify the variables for the node before it processes it. Because your working from a subtheme, the parent theme is still going to run it's own preprocess functions. So that class will always be added via omega. However, because your subtheme's preprocess function is downstream, it will get the &$vars reference with that class already added to it. So instead of rewriting the function, all that is needed is to simply remove the class from the $vars variable that you received in your params.


All you need to do is search your page.tpl.php for parts like:

print render($page['region_name']);

and then wrap them in appropriate if construct, not rendering them at all on pages you don't want to see them rendered.

Alternatively, you can create files named page--user.tpl.php, page--user--login.tpl.php and so on. See this answer for details. Simply copy default page.tpl.php and remove unneeded regions from a copy.


What is the correct syntax to embed JS from Jquery UI website in Drupal 7?

What should I put in JS file to make this work with Drupal 7?

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

    //code starts
    $( document ).click(function() {
      $( "#toggle" ).toggle( "slide" );
    });
    //code ends

  }
};
})(jQuery);

See Working with JavaScript and jQuery for in-depth info.


Date popup field won't display in tableselect element

I still can't get the date_popup element to work in a tableselect element, so I ended up going with text field and the jQuery_ui datepicker (included in core).

  $form['dates'] = [
    '#type' => 'fieldset',
    '#title' => t('Set Dates'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE
  ];

  $form['dates']['start_date_popup'] = [
    '#type' => 'date_popup',
    '#title' => t('Start Date'),
    '#date_format' => 'Y-m-d',
    '#date_year_range' => '0:+20',
    '#maxlength' => 10,
    '#date_label_position' => 'none',
    '#id' => 'apply-start-date'
  ];

  $form['dates']['end_date_popup'] = [
    '#type' => 'date_popup',
    '#title' => t('End Date'),
    '#date_format' => 'Y-m-d',
    '#date_year_range' => '0:+20',
    '#date_label_position' => 'none',
    '#id' => 'apply-end-date'
  ];

  $form['dates']['apply_dates_button'] = [
    '#type' => 'button',
    '#value'=> t('Apply Dates'),
    '#attributes' => array('id' => array('apply-dates')),
  ];

...

 'start_date' => array(
   'data'=> array(
     '#type'=>'textfield',
     '#value'=> $new_start_date,
     '#title' => 'Start Date',
     '#title_display'=>'invisible',
     '#name'=> 'start_date[' . $locale . ']',
     '#id'=>  'start-date[' . $locale . ']',
     '#attributes' => array('class' => array('datepicker')),
     '#size' => 10,
     '#maxlength' => 10
   ),
 ),
 'end_date' => array(
   'data'=> array(
     '#type'=>'textfield',
     '#value'=> $new_end_date,
     '#title' => 'End Date',
     '#title_display'=>'invisible',
     '#name'=> 'end_date[' . $locale . ']',
     '#id'=> 'end-date[' . $locale . ']',
     '#attributes' => array('class' => array('datepicker')),
     '#size' => 10,
     '#maxlength' => 10
   ),
 ),

and this JS behavior:

(function ($) {
  Drupal.behaviors.dashboardDatepicker = {
    attach: function (context, settings) {
      // Attach the datepicker to the selected fields.
      $( ".datepicker" ).datepicker({
        dateFormat: "yy-mm-dd",
        changeYear: true,
        yearRange: '-30:+30',
        minDate: '-0',
        showButtonPanel: true
      });

      // Add click handler for apply button.
      $("#apply-dates", context).click(function(event) {
        // Keep the form from being submitted.
        event.preventDefault();
        // Get the dates from the fieldset
        var startDate = $("input[id*='apply-start-date']").val();
        var endDate = $("input[id*='apply-end-date']").val();
        // Get the set of selected checkboxes.
        if(startDate) {
          $("table#locale-table").find("tr.selected").find("input[id*='start-date']").val(startDate);
        }
        if (endDate) {
          $("table#locale-table").find("tr.selected").find("input[id*='end-date']").val(endDate);
        }
      })
    }
  };
}(jQuery));


how to create a view of entities and nodes

Node are entities. Likely a Node View has access to node-specific properties while an Entity View only has access to fields and generic properties (or properties exposed through the Entity API).

If you can link your entities to nodes using a relation that is exposed as a relationship in a Node/Entity View, you should be able to have view results consisting of data from both a entities and nodes.


You can create a custom drush command to call the cache_clear_all function or just use:

drush ev "cache_clear_all('my_module', 'cache', TRUE);"

You can read more about cache_clear_all in A Beginner's Guide to Caching Data in Drupal 7


How to test if user is denied access when her role has no "access content"

I recommend saving out your permissions using Features and then loading your custom feature in your test. By doing that, you can test out your configuration settings.

If you really just want to turn programmatically create a user that does not have the 'access content' permission, try this before you create your $web_user:

user_role_revoke_permissions(1, array('access content'));

This will revoke the 'access content' permission for anonymous users (role 1). See http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_role_revoke_permissions/7 for more help.


What is the reason behind the current menu structuring

You can create as many menu items as you want and have them point wherever you want. You can do this in code and in the UI.

Drupal menus have plenty of flexibility, especially with contrib.

More:

You can set up many different menus (and not just one overall hierarchy) because that way you can have more than one menu. You can put them wherever you want on the page. You can have a sidebar menu and a top-strip menu and whatever else.

Internally, the menu system is really a routing system. Drupal uses the same set of code for routing requests as it does for presenting menus in web pages. Each route/item can have its own permissions, so the list of items the user sees is determined by their role, automatically.

In short, to recap: The reasoning behind Drupal menu structuring is that it's flexible.


How to display a table with results when a batch is finished

You need to store your results somewhere to be able to display them. If they are only required temporarily, the Drupal cache may be an appropriate place to use.

You'll need a key to identify the cache item and make it unique to the batch. As batch callbacks are not passed the internal batch ID, which would be the ideal choice, you'll need to generate one, for which you can use the uniqid() function.

So your batch finished callback will be something like:

function mymodule_batch_finished($success, $results, $operations) {
   if ($success) {
     $key = uniqid();
     cache_set('mymodule_batch_results:' . $key, $results, 'cache',time() + 86400); // keep for 1 day
     drupal_goto('mymodule/batch-results/' + $key);
   }
   ...
}

In the callback function for the redirected page you can extract the key from the path and read the data from the cache.

function mymodule_menu() {
  $items['mymodule/batch-results/%'] = [
     ...
     'page callback' => 'mymodule_display_results',
     'page arguments => [2,],
     ...
  ];
}

function mymodule_display_results($key) {
   $data = cache_get('mymodule_batch_results:' . $key);
   if ($data) {
     ...
   }
}


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

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

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


How do you apply timezone formatting to a date?

The arguments you pass to the function are wrong; in particular, what you pass as last argument should be the one before it.
The arguments the function accepts are format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL), but your fourth argument is an empty string, and then you pass the timezone identifier as last argument, which should be the language identifier.
You are also using '$date' as first argument.

Try with the following call:

format_date($date, 'custom', 'D d/m/Y - g:ia', date_default_timezone_get()).


try

hook_module_implements_alter()

to alter the hooks order


How can I filter for the UID of the node on a view?

Hope this will help you, To display all content created by author who created the current node loaded, No need to make any relationship, Just add a Configure contextual filter: Content: Author uid check the bellow options,


Yes, it's variable and it's in the Strongarm box. His name is ctools_content_all_views. It can be not set by default - then just submit your form and check again.


MRSS is just an XML.

There are many Views plugins to export data as XML. Specifically for MRSS, there is Views RSS. Or you can simply use template files to output data with proper tags.

It should be possible to use Feeds XPath Parser module to import MRSS, too.

The Views RSS module is only for Drupal 7 and 8.


How to use the Features API to enable a feature?

in order to enable a feature, they use this code

That's not accurate. The hook function is actually:

  Invoked on a Feature module before that module is enabled.

It's not involved with the action of enabling the feature, it's just a listener to enable it to run some code just before something else enables it.

Features are just modules, and to enable one you use the same method as if you were just enabling a module:

module_enable(['foo']);


What is cache_menu in Drupal 7 DB? Safe to empty?

What exactly is doing this cache_menu table in MySQL Database of my Drupal 7?

Not to sound too glib, but it does exactly what it says - it stores cache for the menu system.

  Is it necessaru so huge?!

It's as big as it needs to be - if you have a lot of menu structure, it will be large. But 300mb isn't exactly a lot of data in this day and age.

  If it is just a Cache - would it be safe to empty / disable somehow?

Depends how you define "safe". Yes, your site will still work, but rebuilding the menus from scratch on every page load is likely to make your page requests take quite a bit longer.

You can safely truncate that cache bin and let it rebuild; maybe there is stale data in there that won't be re-added when the menus are built up again.


How to display user form and hide some fields?

You should alter the form before rendering it.

$form = drupal_get_form('user_profile_form', $user);

// Uncomment this line to inspect the structure of the form array (needs devel module)
//dpm($form '$form');

// hide field.
unset($form['field_name']);

return drupal_render($form);


As a matter of debugging, if you have the Devel module installed, try executing the query at devel/php with hard-coded data. That will help understanding if there is an issue with the  db_update(). Also, when you run the query and an error occurs, the error log at admin/reports/dblog on your site should show you any error message about that query.

In case you need to update or insert values on a table, db_merge() should be used instead of db_update(). db_update() doesn't insert new rows, but updates the existing ones; db_merge() updates the existing ones, or creates new rows.

Once you are ready with a working query, debug the $form_state values; there might a mismatch between database table column type and the data you are trying to put there.


PHPUnit Testing when a custom class contains drupal calls and references other classes

If you are doing Unit tests (and not functional tests), you will need to mock the objects you want to use, in the setup of the test. You can read more here: https://www.drupal.org/docs/8/phpunit/mocking-entities-and-services-with-phpunit-and-mocks

If you are using Drupal functions, you should first try to find out if there is an OOP method that can be used to do the same thing - later versions of Drupal have tried to deprecate such functions, and provide OOP alternatives instead. An example is the Time (datetime.time) service, that replaces things like REQUEST_TIME.

If there is no OOP alternative, you can do the following. Imagine you are using db_query() (which, you shouldn't). Instead of using that function direct in your code, you can create a protected function as follows:

protected function dbQuery($query, array $args = [], array $options = []) {
  return db_query($query, $array, $options);
}

Next, for your text, you will create a class that extends the original class. In this test class, you override dbQuery() above:

protected function dbQuery($query, array $args = [], array $options = []) {
  return ['row1' => ['col1' => 'val1'], 'row2' => ['col2' => 'val2']];
}

This mocks a call to db_query by returning an array of values. The last step is to use this new class in your Unit tests, so that when dbQuery() is called, it uses your extended version that returns the array, instead of calling db_query() which is not available to the Unit test.