Why would some features still show Overridden after a revert all --force?

A feature or features may not revert for the following reasons as cited by some developers in the issue queue #744450:

If your feature includes a view views cache could cause it to remain changed; especially, the migrate module (#1)
Other features can cause your feature to be overridden (#10)
Adding a line in your info file (#24)
There are hooks overriding or altering your view (#36)
A view won't revert. So revert the view using the UI (#62)
When Views UI is disabled, it may cause your view to be overriden (#64)
A feature is missing an include file (#82)


vbo action without selecting row (in other mean all rows)

The closest thing to this is Enable "Select all items on all pages" in Bulk operations settings.

It presents itself as a button to select all items in the view which you select the "select all" checkbox on the current page.

It's not exactly what you describe, but you're not going to get that without custom code to modify VBO.


How to change Drupal's default language programmatically?

Here is a corrected and tested version of the code posted by @Clive in a comment to the OP:

$langs = language_list(); // Note: No argument
// debug($langs, '$langs');
$langcode = 'en';
variable_set('language_default', $langs[$langcode]);

The code snippet above assumes that the two-character code that you assign to $langcode is enabled.  Uncomment the call to debug to see the languages that are enabled on your site and what array indices they use.

Note that the setting will not take effect until the next page load.


Drush sql-sync not placing file in specified dump-dir

I actually posted the same question in the Drush GitHub and they did in fact tell me that sql-sync was rewritten (removed in e89c7c4) and it no longer includes the option for a dump-dir.

As per GH #2125, they've said:

  It gzips and transfers the full dump every time. It uses a temp file in your specified temp dir for the transfer. Files are deleted right after rsync.

So I guess all documentation that is out there is old.


When you are doing node_save() inside hook_node_presave, it will trigger hook_node_presave where you have node_save()...

You could move the node_save else where. Perhaps if your using form in creating the original node just add submit handler in case the node type matches? Or some other way to by pass the infinite loop.


How to delete all revisions of given content type except the current revision?

The time out page is happening cause the modules is not using Drupal batch operation.

Did you try to use drush command that comes with the same module? you need to install Drush Help module to do so. If it didn't work, please post it here so I can provide you with a batch code.


Before upgrading, do I need to upgrade the Views module to 6.3.x?

It's not necessary. I have migrated one large site from Drupal6+Views2 to Drupal7+Views3 in just one step.

You have to take in account that views3 (views_ui submodule) depends on ctools. If you follow this path you have to disable views_ui before the upgrade and activate views_ui (and ctools) once the upgrade has finished.


How to display "NEW" label in comments list

There is a database table called history that records a users history to check against. There is an option in Views to add a 'new' marker to content that has not been viewed by the user and had been created within a certain time frame. If you are further interested in how the 'new' marker works, you can find the query that Views uses in views/modules/comment/views_handler_field_node_new_comments.inc to add the 'new' tag to a list of fields.

(edited for clarity)


Put menus into separate file for better handling caching with expires

There are several ways to achieve this - maybe more.

Ajax call and include the menu via jquery / javascript from drupal at runtime
Ajax call and iclude the menu via jquery / javascript from a static generated file by cron
SSI or ESI include at proxy level of a static file generated by cron

At the moment my favorite is 2. Option as the First option has a major performance drawback because the menu has to be generated for each page visit

Number 2. and 3. inlcude the menu within under 10 milliseconds
but 3. would be perfect as it makes the least problems with SEO.
As I do not yet have nginx as reverse proxy available in production I stick at 2. as I could not get to work SSI and PHP with apache and php virtual() is not cached by the drupal page cache (in fact it breaks it)

There is a module which helps with SSI and ESI called https://www.drupal.org/project/esi


How built in functions like theme_field() are called in drupal?

Consult hook_theme($existing, $type, $theme, $path).

It is called via theme() which can be called directly or indirectly on a render array

Each module that introduces a theme element will define a base implementation (what you are looking at in your question) for theme and other modules can override it if they wish.

Look at field.default.inc in Field module, line 212:

$info = array(
          '#theme' => 'field',
          '#weight' => $display['weight'],
          '#title' => $instance['label'],
          '#access' => field_access('view', $field, $entity_type, $entity),
          '#label_display' => $display['label'],
          '#view_mode' => $view_mode,
          '#language' => $langcode,
          '#field_name' => $field['field_name'],
          '#field_type' => $field['type'],
          '#field_translatable' => $field['translatable'],
          '#entity_type' => $entity_type,
          '#bundle' => $bundle,
          '#object' => $entity,
          '#items' => $items,
          '#formatter' => $display['type']
        );

Theme will then go through this process below to determine whether to render via template file or theme function (screenshot from page 82 of Drupal 7 Module Development).


Export data to CSV programmatically in drupal 7

@potney i have updated your code.Please check

drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->mail . "\n";
}
ob_clean();
print $output;
exit;
}

I have used this code it works for me

            $filename='filename.csv';
            ob_clean();
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');

        $contents="Date  \n ";
$contents.='11/05/2014';

echo $contents;

Please check this.Hope this will work


You shouldn't be accessing the data directly. You should use field_get_items() instead. I also use a foreach below, as that makes your code more generally applicable. Limiting to a single image should happen at the field layer, not theme. If you really want to, you could $image = reset($images).

$images = field_get_items('node', $node, 'field_image');
foreach ($images as $image) {
  $image_render = theme('image_style', array(
    'style_name' => 'teaser',
    'path' => $image['uri'],
    'alt' => $image['alt'],
    'title' => $image['title'],
    'attributes' => array(),
    'getsize' => false)
  );

  $link = l($image_render, $node_url, array('title' => $image['title'], 'html' => TRUE));
  print '
' . $link . '
';
}


Deleting the "Page title" module in an existing site that needs some module-removal (Will damage SEO?)

Page Title stores its titles in a DB table, which will be deleted (along with all its data) if you uninstall the module. It uses an HTML preprocess hook to load that data from the DB on a page-by-page basis, and replaces whatever would normally be the title for that page right at the last minute.

So...

  I wonder if deleting it will destroy the page titles that have already been added to the site's nodes

Is entirely accurate. If you remove the module, you'll also remove the page titles that were added using it, and Drupal will use whatever default title was applicable for the entity before you installed it in the first place (e.g. for nodes that'll be whatever is in the title property).


How to prevent node creation if blacklisted words detected in the body?

I can't give you working code, but the basic approach I have used is:

Make a new Vocabulary.  Call it Naughty Words.  Populate it with all of your naughty words.
hook_form_alter() your submission form, and push on a new $form['#validate'] functions.
In your validation function, read in all of the naughty word terms into an array.  Then check the submitted element(s) against the naughty words.  form_set_error() if there is a match.

There are several ways to do the matching.  One is a simple loop with a strpos against each term; another is to explode the submission and then do an array intersection.  Play around with it in something standalone.


Responsive Image Module not reducing the file size when resizing the browser (Drupal 8)

I guess the 685kB is your original, uploaded file and the 1MB file is generated on the webserver by GD or ImageMagick.

When your original file is heavily compressed and at the same time your JPG quality setting is very high, the generated (pixel-smaller) files can be (byte-wise) larger than your original. There is not much you can do against this except reducing JPG quality settings in Configuration > Media > Image Toolkit

Another option would be using a modified JPG library like MozJpeg, but this is beyond the scope of Drupal.


Custom Field Not Being Saved programattically through node_save()

My suggestion would be to inspect an existing node that already has a value for field_data_qid. Is qid a field created through the Fields GUI? $node->qid is not where I'd expect to see a custom field like this.. $node->field_qid['und'][0]['value'] is a more likely candidate. You'd end up with:

function my_module_test_page() {
  $node = node_load(151);
  dpm($node, 'Pre-modified node');
  $node->field_qid['und'][0]['value'] = 222;
  dpm($node, 'Pre-saved modified node');
  node_save($node);
  // Passing TRUE for $reset to bump the cache
  $test = node_load(151, NULL, TRUE);
  dpm($test, 'Reloaded node');
  return 'Test page';
}

Also: node_load takes a nid integer as a parameter, not a string: http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_load/7

See also: https://stackoverflow.com/questions/7876458/drupal-6-drupal-7-migration-field-unds and Best practice for language key for "und" in hook_form_alter


How to show a different product variation other than the default one on page load ( ajax trigger )

Please see Implement unique URLs for particular products on product displays.
It is an open feature request for Commerce, and it also links to a working sandbox with the implementation: http://drupal.org/sandbox/maciej.zgadzaj/1845182


Can cookies safely be stored in the public filesystem (sites/default/files)?

The risk depends on the nature of the cookie. If these cookies contain session data, they could be used to take over you session, which is considered to be high risk.

Your public files folder (sites/default/files) has public read access, meaning that everybody can obtain a file (once they know its name) by going to example.com/sites/default/files/[FILENAME]. This is not safe and perhaps not the best solution for the type of cookies described above.

Instead, you can save it to the private filesystem. Instructions for Drupal 7 and 8 differ, so best to look up the instructions you need. The ultimate safe solution would be to move your private filesystem outside of your webroot (some tutorials create it as subfolder of sites/default/files). Safer would be to place it in a folder next to your public_html/www folder or anywhere else on the filesystem, where it is not accessible from the internet.

If you configure it properly on SITE/admin/config/media/file-system, you can then use the streamwrapper private:// to read and write the files.

If these cookies do not contain any data that could be considered to be sensitive, sites/default/files (or public://) should be good enough.


I figured it out. After you extend your query:

$result = $query->extend('PagerDefault')->limit(21)->execute();

You'll need to also include the pager

// Attach the pager theme
$element['pager_pager'] = array('#theme' => 'pager',);


$check=db_select('users','u')
    ->fields('u',array('uid'))
    ->condition('mail','user email comes here','=')
    ->execute()
    ->fetchField();

if($check!='')
{
    form_set_error('mail','Email Already Exists');
}

You can use this.


Drush stoped working and drush status -v shows Executing: vagrant

I just realize that I in the ~/.drush/ folder there is a drush-vagrant folder, after deleting it everything started working again.
The folder is from the drush-vagrant module that I installed by mistake.
See drush folder download answer: How to download directly to ~/.drush folder?


Difference between hide() and ['#access'] = FALSE

Hiding the element is done during the rendering process.  If you look at the code, it just marks the element as already being rendered.

The #access key on the element is used during the form build process (can't find my chart, so I can't tell you exactly which part).  It says that this element is part of the form, but a particular user may or may not have access to be able to use it.

Unsetting the element, just throws the element away and says it is not part of the form anymore.

Of the three options, using #access is preferred: it's the API so you should use it.  When you just hide the element, a user can still submit that element git GET/POST as the Form API thinks it is still valid.  For non-submit elements, I believe the #default_value will also appear in $form_state['values'] when you validate/submit (however I don't recall the last time I tested this).


You should change "echo 555;" to "return 555;"


Gather all broken links (Link-checker) in view

Normally this would involve either a custom module, or a patch to the link-checker module, with an implementation of hook_views_data. This requires some coding skills and understanding of databases.

One option is to try the Data module, which supposedly is capable of automatically deriving the required information by looking at the table structure. I've never tried it though, so whether or not it works, or how well it works, I cannot say. From looking at the modules schema, it looks like the interesting tables are:

D7 "linkchecker_block_custom", "linkchecker_comment", "linkchecker_node", "linkchecker_link"

D6 "linkchecker_boxes", "linkchecker_comments", "linkchecker_nodes", "linkchecker_links"


Creating a one-time password, and send the email

Login One Time comes closest to your requirements. From its project page:

Login one time provides the ability to email one-time login links to users.
Features
Rules:

[user:login-one-time] token on user events.

[comment:login-one-time] token for node author on comment event.

User profile - "Send login one time link" button.

VBO - Create a view and send login links to the view. Checkout View
Reference for ideas on how to embed views.

Block - Select a user and send the link. You can use this block in
nodes as a CCK field using Block Reference.

PHP - Print a button in a template or directly send the emails using
the functions described in the README.


How to geocode a form field on submission?

Personally, rather than form_alter upon submission, I would wire up an AJAX function to fire on the address/location textfield's onchange event, which would use the Google Maps Javascript API's Geocoder function.  This would then populate a hidden text field (or two) with the lat/lng pair for form submission.

If you want to use the Geocoder module, it should probably go in the validate function so you can double check that you actually have a valid address.

Ideally, you would do both.  Doing it client side is faster, and doing it server side supports users w/o Javascript.


In submit you have two choices.

Rebuild

public function submitForm(array &$form, FormStateInterface $form_state) {

  $form_state->setRebuild();
}

The form and the twig template the form is wrapped in will be rebuilt and you can display the result.

This is a great question from @AdrianCidAlmaguer to demonstrate how this works with a basic example how to display the sum of two numbers: How to show a string once you submit a form in a page reloading the page?

Redirect

public function submitForm(array &$form, FormStateInterface $form_state) {

  $form_state->setRedirect($route_name, $route_parameters, $options);
}

You redirect to a new page and can display the result there.


I find two solution links, please check them:

Sol-1: https://www.drupal.org/node/1430034 (Most relevant solution)

Sol-2: How to theme a webform - D7 (It another solution to theme webform with another tpl name: webform-form.tpl.php. Here is the link which provide tpl code.)

I guess you need to use node--webform.tpl.php and also add preprocessor in template.php.

function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

And when you create tpl file you can check preview variable to check and theme accordingly.

If this doesn't help try second solution.


Add allowed file extensions in Views Send file field

Turns out the file behavior you're looking for is not defined for file elements, but for managed_files. It's as easy as:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_form_send_page_alter(&$form, &$form_state) {
  if ($form_state['step'] == 'views_send_config_form') {
    $form['mail']['views_send_attachments']['#type'] = 'managed_file';
    $form['mail']['views_send_attachments']['#upload_validators']['file_validate_extensions'][] = 'docx';
  }
}

But views_send will have to be patched to support managed_files. This still needs work in the issue queue.

Yet, as I mention in the issue, you can hack it directly in the module. It's not recommended, but we don't have a hook here and the issue above might take a while to be solved. So just change the line

$file = file_save_upload('views_send_attachments', array(), $dir);

to

$file = file_save_upload('views_send_attachments', array('file_validate_extensions' => array('docx')), $dir);


Custom plugin modified results in WSOD PluginNotFoundException

Plugin definition its a tandem between the plugin manager wich defines how your plugin type should be discovered and instantiated; and the plugin definition method itself that could be either using YAML files or annotations. Depending of which you used to define you new plugin type is how you must proceed in order Drupal find your plugin implementation. Said that if your plugin is used in a configuration entity you can find it querying your configuration table as follows:

SELECT * FROM config WHERE name LIKE '%group_user%' OR data LIKE '%group_user%';

In the other hand if your plugin is invoked directly in code by calling the plugin manager method createInstance you can then find where it is being used with a simple search in your custom code using your favorite editor or IDE. I emphasize on custom code as is a custom plugin type cannot be (yet) in contrib code.


drupal_goto not working in hook user login

Instead of using drupal_goto(), try passing the path in $edit['redirect'] in hook_user_login as below:

<?php
/**
 * Implements hook_user_login().
 */
function hook_user_login(&$edit, $account) {
  // To check if the form is not the user reset form.
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    $GLOBALS['destination'] = 'PATH_YOU_WANT_TO_REDIRECT';
  }
}
?>


The "migration" entity type does not exist." error after switching site file structure

The proof is in your last error message, it was expecting an Entity but it is now getting a Plugin. Migrate changed from using Config Entities to Plugins in Drupal 8.1.x so I'm presuming you've somehow triggered an upgrade.

See the change record: https://www.drupal.org/node/2668742


The Features module allows you to export all the configurations in code (instead of DB). It is very usefull when you have 2 separated versions of database, in example one for your localhost or test installation, and one for your live/production website.

However, if you want to deploy the local database to the live server too, it is not necessary to export everything with Features.


Unable to change the background image in theme

I think Your have 2 configuration problem.

File Permission (in Filesystem)
ErrorDocument Attribute (in Apache
Webserver)

First, You can solve permission error using 'chmod' command to the sites folder of drupal.

Try this:

  chmod -R 777 directory (777 means allow permission for all)

Second, ErrorDocument handle error can occured from invaild ErrorDocument attribute setting in .htacess or httpd.conf(or apache2.conf) file.

Try this:

check your .htacess file in 'install/' directory. If you can not
check this file, you can try 'ls -al' command in terminal. you have
to find 'ErrorDocument' attribute, and remove or correct it.
check your apache webserver configuration file (httpd.conf or
apache2.conf). If you can check 'ErrorDocument' attribute, you can
try remove this attribute in file. It is temporary, so you must
backup it before try suggested cases.
If you can not solve by case 1 and 2, you can try disable
'AllowOverride' attribute. Try find 'AllowOverride x' attribute and
replace to 'AllowOverride None'. Because, this problem can have
possiblity from .htacess file in parent directories. AllowOverride
attribute can control allow or deny additional configuration in
.htacess file.
You must restart apache service after try this cases. you can try
'service httpd restart' or 'service apache2 restart' command.

Hope this helps you...


One way to use two formatter for single field in view is

Add same field two times in view.
Set different field formatter.
Exclude from display.
Add " Global: Custom text ".
Go to Rewrite results of " Global: Custom text ".
Use Replacement patterns to show that two fields.

How to add Global: Custom text?

For count the click you need to some js coding.


Overriding region theme file for user profile pages

I found solution on this blog http://eureka.ykyuen.info/2012/05/10/drupal-7-customize-region-template-file-for-specific-content-type/
and here is my code to suggest a user profile region.

    function YOURTHEME_alpha_preprocess_region(&$vars) {
      $menu_object = menu_get_object();
      if (isset($menu_object->type) && $vars['region'] == 'content') {
        $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
        $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
      }
//theme suggestion for user profile
      elseif ($vars['region'] == 'content' && $vars['elements']["system_main"] && $vars['elements']["system_main"]["#entity_type"] == 'user') {
        $vars['theme_hook_suggestions'][] = 'region__content__userprofile';
        $vars['attributes_array']['class'][] = 'region-content-userprofile';
      }
    }


Show different fields on node edit and node view depending on the sub-type of the node

Take a look at the Conditional Fields module. You could make some fields dependent on one checkbox selection and other fields dependent on a second checkbox selection.

  Define dependencies between fields based on their states and values.

  Conditional Fields for Drupal 7 is an user interface to the new
  States API, plus the ability to modify fields appearance and
  behavior on certain conditions when viewing content.

  Description

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API.

  A simple use case would be defining a custom “Article teaser" field
  that is shown only if a "Has teaser" checkbox is checked, but much
  more complex options are available.


\Drupal::service('entity_type.manager')->getStorage('commerce_order')->resetCache([ORDER_ID]);

This service which used in OrderReassignTest.php will help you to Reload the order based on Order ID.


How to update field after ubercart checkout completion?

you can use the Rules module for the after checkout event then use some custom php code to update your field.

you might need to add Commerce Rules Extra module to get the checkout event in rules.


how drupal decide execution order of same hook in different modules?

Hooks are called in order of

Weight, which is defined per module in the database as {system.weight}.  Lower weights come earlier in the calling process.
Alphabetical, by module name.

By default, modules get assigned a weight of 0, so nearly all hooks in the system run in alphabetical order.  Some modules will adjust this in their install hooks so they run earlier or later in the module_invoke_all function.

See also: Adjusting module weight: what are the risks and things to look out for?


How to get details like duration, type, etc from uploaded videos and store them in fields?

Presumably we are talking mp4/webm video here? Start with checking out getID3. Then it is pretty simple to do:

$id3 = new getID3;
$file = $id3->analyze($filename);

Must always have "new getID3".


When is node_search() in the node module called?

node_search() is the node module's implementation of hook_search(), which:

  allows a module to perform searches on content it defines (custom node types, users, or comments, for example) when a site search is performed.

That hook is invoked from a number of different places.

At a guess I would say if someone was going to make changes to node_search() it would probably be for the 'search' operation (i.e. altering the results of the standard node search). That particular operation is invoked from search_data().

It might be worth having a look a regular copy of node_search() alongside your hacked copy to see if you can understand what the differences are, and whether you can revert the changes without breaking things (if that's what you need to do).


Show different fields when adding a content depends on the language

If you have some specific fields which only should be viewed based on language , the best way to do that is by using page manager and panels .

Download and enable this modules
go to Structure -> pages
enable node_view
add a variant and select Selection Rules
now add a rule based on user->language and node->type
and now you can make a custom view based on language


How to build a url to an (AJAX driven) exposed filter?

If I understood well, once I face the same situation than you, the module Views Filter Harmonizer help me to solve my issue.

From the module's page:

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering.

  Normally, when a Views field has been assigned both an exposed filter
  and a contextual filter, then both filters get applied to the View's
  results set -- always. This is not configurable behaviour. It's
  hard-coded.


Getting error "Table 'drupal.watchdog' doesn't exist" during install

This is weird, since exactly in 8.0.5 is fixed that kind of error:

#2646410 by claudiu.cristea, dawehner: Container cannot be saved to cache

Can you try Drupal 8.0.6 maybe? Your MariaDB as well as PHP seem to be compatible with D8 requirements (your MariaDB is based on 5.5 plus Mysql 5.6 stuff).


Ckeditor Wordcount plugin - How to target specific textareas

I figured it out, hope this helps anyone else out there.

I added the following to my Adminimal Sub theme to add a class to the summary textarea:

function adminimal_sub_form_alter(&$form, &$form_state, $form_id) {
 if (isset($form['#node']) && $form['#node']->type == 'article') {
 // Add class to body textarea for various content types. This is used for the Ckeditor wordcount plugin to target summary textarea.
   $form['body']['und']['0']['summary']['#attributes']['class']['0'] = 'article-summary';
 }
}

Then downloaded the Ckeditor 4 Wordcount plugin and saved it in the plugins directory (sites/all/libraries/ckeditor/plugins).

In the Drupal UI I went to configuration > CKEditor Filtered HTML (edit) and in the Custom Javascript configuration under Advanced options I added a path to my ckeditor.config.js (config.customConfig = '/sites/all/themes/global/js/ckeditor.config.js';).

This is my ckeditor.config.js:

CKEDITOR.editorConfig = function(config) {

 if (this.element.hasClass('article-summary')) {
 config.wordcount = {
    showCharCount: true,
    maxCharCount: 170
    }
}
// Make CKEditor's edit area as high as the textarea would be.
 if (this.element.$.rows > 0) {
    config.height = this.element.$.rows * 20 + 'px';
 }
}

Here I can set the maxwordcount and loads more besides, but for this project only needed the maxwordcount. This way if the Drupal Ckeditor module gets updated this file will not be affected.


How to decide between 'Hook_preprocessor' or using twig template?

It's not really an either/or thing. They are used together - preprocess functions are run before a template is used. Templates should only have very simple logic, if/else, and loops for the most part. Any logic more complex than this should go into a preprocess function. If you want to do things like adding classes to the attributes of a variable, this should generally be done in the preprocess function, though if you have a class that will only go in a single template, then it can be done in the template itself.


Normally a content entity has a template, like node.html.twig for node, so for custom blocks there should be block-content.html.twig. To avoid overhead it was decided to remove this template. This means you can't add template suggestions to the entity template, instead you have to add them to the block template. In this case you get the variables from the plugin when adding suggestions and you don't find the view mode or other details in a consistent way like for entities.

Additionally you use two different plugins to place the block:

Original block plugin for Custom Blocks (core)

http://cgit.drupalcode.org/drupal/tree/core/modules/block_content/src/Plugin/Block/BlockContentBlock.php?h=8.4.x
Block plugin from Entity Block (contrib)

http://cgit.drupalcode.org/entity_block/tree/src/Plugin/Block/EntityBlock.php?h=8.x-1.x

The second method, this is using custom blocks outside of the core block content plugin is not officially supported, because the pair of both are optimized to work together.

For the second method a custom entity might be a better choice (then of course one which has a template, which is standard for entities built by Drupal Console ).

  I have noticed a discrepancy between Custom Block and Entity Block
  where one form gives you the view mode to show the block in, and the
  other does not (Custom Block).

Checking the linked code from the Custom Block plugin. It should show the view mode, if there is more than one to choose from:

$form['view_mode'] = [
  '#type' => 'select',
  '#options' => $options,
  '#title' => $this->t('View mode'),
  '#description' => $this->t('Output the block in this view mode.'),
  '#default_value' => $this->configuration['view_mode'],
  '#access' => (count($options) > 1),
];


Does hook menu accept a wildcard as argument 0?

Wildcards may not be used as the first component of a route path in hook_menu. https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

what can you do if you want this feature, the solution is kind of tricky solution like

function MYMODULE_menu() {
  $items = [];
 $myItems =  // load what do you have
foreach($myItems as $myItem){
  $items[$myItem.'/review'] = [
    'page callback' => 'review',
    'page arguments' => [0],
    'access arguments' => ['access content'],
    'type' => MENU_CALLBACK,
  ];
}

  return $items;
}


How to debug queries and exports sent to Salesforce?

If you're using Ubercart / Salesforce Integration, you can use the following patch:

Drupal 6

--- a/uc_salesforce/uc_sf_order/uc_sf_order.module
+++ b/uc_salesforce/uc_sf_order/uc_sf_order.module
@@ -635,6 +635,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
     // Export the object to Salesforce.
     try {
       $response = $sf->client->create(array($object), $map->salesforce);
+      drupal_alter('uc_sf_order', $response, $sf);
     }
     catch (Exception $e) {
       drupal_set_message(t('Error exporting order to Salesforce.'), 'error');
@@ -681,6 +682,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
         }
         try {
           $product_responses = $sf->client->create($product_objects, $uc_order_products_fieldmap->salesforce);
+          drupal_alter('uc_sf_order', $product_responses, $sf);
         }
         catch (Exception $e) {
           sf_dpm($e->faultstring, 'Ubercart order line item exception');
@@ -718,6 +720,7 @@ function uc_sf_order_export($order, $name, $sfid = NULL, $manual = FALSE) {
       else {
         $user_object_export = salesforce_api_fieldmap_export_create($user_map_id, $account);
         $user_response = $sf->client->create(array($user_object_export), $user_map->salesforce);
+        drupal_alter('uc_sf_order', $user_response, $sf);
         $account_sfid = $user_response->id;
       }
     }

and then you can define the following function:

<?php
/**
 * Define debug constant
 * To activate, run: drush -y vset foo_debug 1
 */
define('FOO_DEBUG', variable_get('foo_debug', FALSE));

/**
 * Implements hook_TYPE_alter().
 */
function foo_uc_sf_order_alter($response, $sf) {
  $xml_request = $sf->client->getLastRequest();
  $xml_response = $sf->client->getLastResponse();
  FOO_DEBUG ? watchdog('foo', "UC Salesforce XML request/response:\n
Request:\n@req\n
Response:\n@res", array('@req' => $xml_request, '@res' => $xml_response), WATCHDOG_NOTICE) : NULL;
}
?>

To activate debug messages, run the following drush command:

drush -y vset foo_debug 1

And run watchdog messages in foreground before your test:

drush watchdog-show --tail --full

Read more:

Add hook_alter for catching and debugging the requests and responses.


Running triggered rules actions in the background?

Turns out you can use Rules Scheduler for this. Here's the recipe:

Create an action set with the actions to run in the background
Add the action "Schedule component evaluation" to your trigger, choosing the action set you created above
Set the "Scheduled evaluation date" to now

When your trigger fires, its actions will be called at the next cron run. That was simple!


The string (first parameter) always needs to be in English, from the Drupal 7 API:

  $string A string containing the
  English string to translate.

The langcode just means that the string will always be translated to Danish, no matter what the active language is. So if you'd be surfing the French site, you'd see the Danish string.

I'm afraid you'll have to translate your Danish strings back to English strings.


Save user selection after search in views

Go to your views >> Exposed filter settings and check Remember the last selection checkbox

If you want to go further then try the Views Saved Searches module

This module allows you to save your current configuration of exposed filters for later use. This can be especially useful for Views with a lot of exposed filters.
Whenever a View is changed, all saved searches for that View are deleted, to prevent corruption. If the user has JavaScript enabled, the saving and deleting process happens through AHAH, and the new section is displayed below the exposed filters section. When JavaScript is disabled, the new section is displayed above the exposed filters section.


How to get rid of large classes with numbers from views?

They are used to uniquely target views elements with javascript for AJAX purposes. If you have enabled the use of AJAX on your views display for pagination, filtering etc without page reloads, then removing or changing those might break it. If you are not using AJAX at all, you should be fine, although this comment is not a promise or guarantee!


How to allow users to 'add' values to a multi-value field but not edit any previously add values?

You can programmatically disable them in module like this:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'eck__entity__form_edit_ENTITY_NAME_BUNDLE_NAME') {
     $lang = $form['field_name']['#language'];
     foreach ($form['field_name'][$lang] as $key => $value) {
       if (is_numeric($key) && !empty($value['value']['#default_value'])) {
         $form['field_name'][$lang][$key]['value']['#disabled'] = TRUE;
       }
     }
   }
}

Result


Change field type from "text field" to "integer"

One option could be to create another field, of integer format.

Then using PHPMyAdmin (or similar) copy the contents of the  field_data_field_FIELDNAME_TEXT_FIELD into your newly created field_data_field_FIELDNAME_INTEGER_FIELD.

If that works you can then delete the original text field.


How to let users allow other users to view specific node content?

You can do it using a small custom module.

Make a allowed users/node list (database table oe entity)
Implement hook_entity_access()
return AccessResult::allowed() or AccessResult::forbidden() according to your user/node table


Add foreign key to schema using hook_update_N

You can add keys to tables using native SQL. It's not supported by drupal 7 core api. I answered this previously elsewhere:
Is there a way to add a foreign key to a table?

I doubt that simply adding a key will expose the relationship for you in Views though.

In order for Views to see this information you likely need to supply the info via hook_views_data() about your custom tables and relationships. A recent blog post I found about this today actually was:
https://chacadwa.com/blog/2014/08/12/adding-full-views-support-custom-entities

From this blog post you can see that for a table that needs a join to add extra fields (and to do so by default in Views) they add the following array to their hook_views_data() function.

// Define a default relationship to the staffdir extra data table.

$data['hank_hrper']['table']['default_relationship'] = array(
  'hank_hrper_extra_data' => array(
    'table' => 'hank_hrper_extra_data',
    'field' => 'hrper_id',
  ),
);

// Now define the staffdir extra data table, so views can use it.

$data['hank_hrper_extra_data'] = array(
  'table' => array(
    'group' => t('Staff directory'),
    'entity type' => 'staffdir',
    'join' => array(
      'hank_hrper' => array(
        'left_field' => 'hrper_id',
        'field' => 'hrper_id',
      ),
    ),
    'default_relationship' => array(
      'hank_hrper' => array(
        'table' => 'hank_hrper',
        'field' => 'hrper_id',
      ),
    ),
  ),
);

// Now we can define fields from the staffdir extra data table for use in the relationship.

$data['hank_hrper_extra_data']['opt_out'] = array(
  'title' => t('Opt out'),
  'help' => t('Allows for users to be excluded from the directory.'),
  'field' => array(
    'handler' => 'views_handler_field_boolean',
    'click sortable' => FALSE, // could be TRUE, but why?
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_boolean_operator',
     'accept null' => TRUE,
    'help' => t('Filter results to a particular result set'),
  ),
);


Load an iFrame to Drupal with JavaScript

Your code is missing some important stuff. The original code from the Google page you linked yourself:

_gaq.push(function() {
  var pageTracker = _gat._getTrackerByName();
  var iframe = document.getElementById('myIFrame');
  iframe.src = pageTracker._getLinkerUrl('http://www.my-example-iframecontent.com/');
});

So you would end up with something like the following.

<script type="text/javascript">_gaq.push(function () {
  document.getElementById('myIFrame').src = _gat._getTrackerByName()._getLinkerUrl('http://www.my-example-iframecontent.com/');
});</script>
<iframe id="myIFrame" height="500px" width="350"></iframe>


Custom submit handler for theme settings form

From Drupal 8: Use Custom Submit Handler for Theme Settings Form:

Use this method to add custom submit handler for theme settings form in drupal 8.

/**
 * Implements hook_form_system_theme_settings_alter().
 */
function MY_THEME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $theme_file = drupal_get_path('theme', 'MY_THEME') . '/MY_THEME.theme';
  $build_info = $form_state->getBuildInfo();
  if (!in_array($theme_file, $build_info['files'])) {
    $build_info['files'][] = $theme_file;
  }
  $form_state->setBuildInfo($build_info);

  $form['#submit'][] = 'MY_THEME_form_system_theme_settings_submit';
}

function MY_THEME_form_system_theme_settings_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // TODO: Extra submssio logic.
  // This submit handler will be called before default submit handler for this form.
}


Need to alter "No Paragraph added yet. Select a Paragraph type and press the button below to add one." message - Paragraph Module

You need to patch the contrib module.
Patch here works for me.


How to programmatically translate/localize taxonomy terms?

I was able to do it using the following code:

<?php
    $enabled_languages = array_shift(language_list('enabled'));
    foreach ($enabled_languages as $language => $object) {
        if ($language != 'en') {
            //Translate description
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'description'), // Path where to store source and translation.
                autotranslate_translate($term->description, 'en', substr($language, 0, 2)),
                $language
            );
            //Translate name
            i18n_string_translation_update(
                array('taxonomy', 'term', 12, 'name'), // Path where to store source and translation.
                autotranslate_translate($term->name, 'en', substr($language, 0, 2)),
                $language
            );
        }
    }

?>


I have figured this out myself.  Please refer to Comment #5 in Issue 2094541 for the answer, located at the following link:
https://drupal.org/node/2094541#comment-7955705
Here is what it says:

Finally, figured this out! The problem is, we're not supplying the required parameters to the Rules component. If you have given it only 'node' as the parameter, then, when you add the action to 'Unflag a Node', you must give the 'User on whose behalf to flag' a data selector such as 'node:author'. You can't do something like 'site:current-user' because that parameter is not available to the component when run through Cron.
Once you give it the required parameters, it should unflag the node through Cron.


Easier way to get a field's value when given a node object from node_load

You can use field_get_items() like this:

field_get_items('node', $node, $field_name);

Also see What's best practice when working with the language['und']?.


Theme specific Drupal modules? Possible?

Themes are enabled/disabled in Drupal by altering the flag in the database table system. And these settings are common for all the users irrespective of which device/ how they are accessing your page.

So in your case it is about making sure that only the files from necessary modules are loaded based on the current theme.

You can use $theme global variable to find out the current theme, and then based on that you can fetch the files from the necessary modules only. You can check the code from js module how the second part can be implemented. You need to have patience though ;)


In a manually created menu, when a taxonomy term is a parent with children, the children never display. Bug?

Have you tried editing the parent menu item and enabling the 'Expanded' checkbox? This module may also come in handy: http://drupal.org/project/menu_expanded

Keep in mind that in many themes, the stock menu for primary links / secondary links is not a multi-level menu and so even if expanded renders the child items in HTML, they may not render properly in the actual menu. If this is the case, you may wish to look at implementing a menu block with one of the menu modules such as: http://drupal.org/project/superfish


Listing all terms of a taxonomy in twig template

Build a view for the list of taxonomy terms and use the module Twig tweak:

<dd>{{ drupal_view('view_name', 'page_1') }}</dd>


Object of type stdClass cannot be printed when received JSON response

Short answer: because that is how the API was written.

Long answer is that they do not know how the object should be printed.

To cast an object to a string, you need the object to have a __toString method, which the object in question does not contain.

If you want to print the stringified version of the object then don't transform to an object using json_decode.


How to programmatically set node field values.

You can create a custom module and add use hook_form_alter to change the default_value of your field and change them to #disabled => true. Here is an example. Don't forget to chage modulename to the name of your module and form-id to the id of your form :-).

function modulename_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form['#id'] == 'form-id') {
        $form['field_name'] = array(
            '#disabled' => TRUE,
            '#default_value' => $user->name
        );
    }
}


I can't filter list term under admin/content

admin/content page doesn't list taxonomy terms, it shows content nodes. Those options in the select list are actually Content Types you can filter by.

To view taxonomy terms, the link is admin/structure/taxonomy.

Anyway, in the remote case you do want to have better filtering options for nodes, I recommend the module Admin Views.

After enabling Admin Views module, you can go to /admin/structure/views/view/admin_views_node/edit to edit the view that's responsible for displaying the admin node list. Here you can add as many exposed filters you need, in your case, the term reference field.

Admin Views also requires Views Bulk Operations module which allows you to execute operations on multiple nodes at once.

Edit: Your taxonomy vocabulary filter needs to be exposed to appear in the form (click on the filter, then click on 'Expose this filter to visitors, to allow them to change it'). Then all vocabularies should appear in the filter form.


how to get form element value before submit in drupal

Once an user has logged in, the GLOBALS $user with the information related to this user is ready to use. It isn't neccesary to add an argument to the URL in your redirection.

If it isn't loaded the information you want, you could store that variable in the $user object.

function doner_user_login(&$edit, $account) {
  drupal_get_form('doner_step_3');
  $GLOBALS['user']->doner_variables = $form_state['values']['about_fname'];
}


How to change the link text in Drupal 8 Views?

Here's how I do this (just tested it, working):

Make sure you have a relationship to Entity B added to the view.
Potential gotcha: Make sure your Title field for Entity A is NOT a link already; you won't be able to use it as a title in a link rewrite if it is already a link.  (If you want to rewrite a title that is already a link, you can add a second title, make the second one not a link, and then use that in your rewrite.)
Add a Path field that uses the Entity B relationship.  Rewrite it like {{ entityA_title }}


How to handle GET parameters in the proper Drupal way

When faced with this url structure,  you can use $_GET in the usual PHP way. Drupal urls are usually generated with parameters separated by /, and as you probably know,  arg() is the right tool when this is the case.

As for the email validation, there are native functions that validate, but the validation is quite basic:

//check if this is a valid Drupal username
user_validate_name('USERNAME');

//check if this is a valid email address
user_validate_mail('test@test.com');

If you had to do this in a form, one can add validation functions where needed with hook_form_alter:

/**
 * Implementation of hook_form_alter().
 */function my_module_form_alter(&$form, $form_state, $form_id)  {
 if ($form_id == 'user_profile_form') {
  array_unshift($form['#validate'], 'email_check_validate');
 }
}

/**
 * Validate profile form
 * Force form error if new email address matches current email address
 *
 */
function email_check_validate ($form, $form_state)  {
  global $user;
  $old_email = $user->mail;
  $new_email = $form_state['values']['mail'];

  if ($old_email ==  $new_email) {
    form_set_error('mail', t('Your email could not be changed'));
  }
}

But this does not apply in your case, it was just an example for when you need to do validation through a form.

Hope this helps, cheers!


On logout as admin, PHP code from node pages is executed.

If the page you are referring is a node page, then the node could be using the PHP input format, and in that case the node body would be passed to eval() through drupal_eval().
If the page is a view page, the Views module allows the administrator users to enter PHP code that is executed, through drupal_eval(), in specific circumstances.

In both the cases, a block visible in the page could be using PHP code to set it block visibility.

There could be other modules that call drupal_eval(). Those modules pass to drupal_eval() code that users with the right permission enter in the module's settings; if you have one of those modules, you should remember ending PHP code in a text area.


Updating Entity Properties with hook_update_N()

I've had this problem myself in the past and almost pulled all my hair out! :)

It turned out that I had forgotten to update my hook_schema declaration within the .install file of my module, and include the definition of the new database field for my entity table.

Adding in the definition should make the new field available to you.


Drupal 7: facebook comment for article only

In Drupal 7 you can use

Facebook Comments Box : This module gives your site the ability of using Facebook's Comments Box social plugin. It will create a block just configure only for article. You can check this video
Facebook Comments Social Plugin : Implement Facebook commenting with settings on the level of both content type and node.
Using Facebook plugin code

NOTE :

YOUR_URL : Updated current URL based on each article.


How to create a new field collection+fields in a programmatically added content type

I googled _create field_collection programmatically_ and this example was from my first search result.

  Thought I would post my solution for programmatically creating a field collection, along with an attached field, during a module install. The example is specific to my use, but easily modified to add the field types you need. Of course, if there is an easier way please feel free to add your thoughts. This works with the current 7.x-1.x-dev branch.

/**
 * Create a Field Collection field and attach collection node reference
 */
function _create_field_collection() {
  $t = get_t();

  $fields_array = array(
    array(
      'field' => array(
        'field_name' => 'bir_collection',
        'label' => $t('BIR Collection Nodes'),
        'cardinality' => -1,
        'type' => 'field_collection',
      ),
      'instance' => array(
        'field_name' => 'bir_collection',
        'entity_type' => 'node',
        'bundle' => 'article',
        'label' => $t('BIR Collection Nodes'),
        'description' => '',
        'widget' => array('type' => 'field_collection_embed'),
        'required' => 1,
      ),
    ),
    array(
      'field' => array(
        'field_name' => 'bir_collection_node',
        'type' => 'node_reference',
        'label' => '',
        'cardinality' => 1,
        'settings' => array(
          'referenceable_types' => array(
            'bir_specimen' => 'bir_specimen',
            'bir_image' => 'bir_image',
            'bir_locality' => 'bir_locality',
            'bir_view' => 'bir_view',
          ),
        ),
      ),
      'instance' => array(
        'field_name' => 'bir_collection_node',
        'entity_type' => 'field_collection_item',
        'bundle' => 'bir_collection',
        'label' => '',
        'cardinality' => 1,
        'description' => '',
        'widget' => array('type' => 'node_reference_autocomplete'),
        'display' => array('default' => array('type' => 'node_reference_default')),
      )
    ),
  );

  // Loop through fields array and create field and instance
  foreach ($fields_array as $field) {
    // Check if field already exists
    if (!field_info_field($field['field']['field_name'])) {
      field_create_field($field['field']);
    }

    // Check if instance exists
    if (!field_info_instance($field['instance']['entity_type'], $field['instance']['field_name'], $field['instance']['bundle'])) {
      field_create_instance($field['instance']);
    }
  }
}

First field in the $fields_array array is the field_collection type field that you add to your node entity. (field_name: bir_collection)

The second field in the array is the field which is added to your field_collection_item entity (Notice the bundle in the instance is same as your field_name on node: bir_collection. This is how the connection is made). In this particular example, it's a node_reference type field, but this can be any other field type that's available to your Drupal instance.

The order has to be in this sequence, since you need to add the field_collection type field to your node to create the field_collection_item entity, then you add the fields to your field_collection_item entity.


Module for recommendations based on Solr

Actually, if you go to Apache Solr's 'Pages/blocks' configuration page at admin/config/search/apachesolr/search-pages, you should see whether your "More like this" (which is like a "Related content") block is enabled.

If it's not, just click on the "Add search block "More Like This" as shown below:

That will take you to a page where you can configure your 'More Like This' block.

you can title it and call it something like "Similar Products",
you can define which content types it recommends (if you only want articles, or regular pages or just products to appear in this block) --> set that in the 'Filters' section which is collapsed by default
you can configure settings about the word matching it uses to pull up relevant content (how frequently words must appear or excluding words that are too short or too long from being matched on, etc)

Would this default block that comes with Sorl meet your needs?


Upgrading and creating entity references

If you attempting a Drupal 6 to Drupal 7 update without migration, you want to keep the structures as simple as possible since minimizing rough edges. Therefore, I would wait until after the update.

Once the site is upgraded, I would update the content types involved, and then write a simple custom module that creates a batch job for the conversion.


Why Recent log message is showing anonymous user?

Running cron happens automatically when someone visits your site by default. Drupal does that automatically once every few hours to run certain cleanup/background tasks.

Additionally, cron jobs always run as anonymous user, that's why it is logged as that, even if you trigger it manually as admin.


Best way to test if a commerce price field has a value

Adding isset() to that last if statement is a bit more explicit.

if (isset($discount_wrapper->field_discount_price->value()))


I'm on drush version 6 & can't do a drush status on my drupal8 site, whats the story?

This is a known bug in Drush 6.0.0 that was caused when Drupal 8 changed the way that the Drupal VERSION constant was defined.  This has been fixed in the master branch on GitHub; currently, the only way to use Drush with Drupal 8 is to clone the master branch directly.  There should be a 6.1.0 release out shortly to address this.

For more information, see:

https://github.com/drush-ops/drush/issues/63

UPDATE:  I mis-spoke above.  Drush 6.x supported Drupal 8 until the recent release of Drush 6.0.0.  Now, only the master branch (Drush 7) supports Drupal 8. So, there is no way to get Drush 6 to work with Drupal 8; you must use the master branch.  When 6.1.0 comes out, Drush will correctly tell you that Drush 6.1.0 does not support Drupal 8.


Create Latest Comments View Per Group OG 7.2

OG membership: OG membership from Node for the relationship and OG membership: OG membership from Node as the contextual filter not forgetting to sort the validation criteria


Trying to replicate a view with no success

When you say, "autoselects/autodefaults the dropdown menu item based on the show name," what are you trying to do, exactly? What show name you are trying to auto-select? Is this view capable of showing shows with other show names? If so, and say you have ten shows in that list, which one do you want to be the default?

Are you trying to have links to that same view from different places in the site and you want a link on the Tech Guy page to automatically filter the Tech Guy shows, and a link on the Fictional Mister Podcast page to automatically filter to the Fictional Mister Podcast shows?


How do I change the created date when I create a node?

I solved this problem via hook_node_presave();

function hook_node_presave($node) {
  $node->created = "you_timestamp";
}


Menu items, content nodes, taxonomy terms, etc. are not handled through the Configuration API. Configuration API is meant to handle... well, configuration.

A fast Google search returned Config menu link.
I have not tested that module, but if it works, it should do what you need there.


In your content type, you can create a "list" field called, say, Category, with the categories News, Gaming and Other. You can then categorize the content that should appear in your View using that field.

In your View, under Format, choose "Settings." There should be an option to choose a Grouping Field. Select the "Content: Category" field. Your view should now show up grouped according to News, Gaming and Other.

Was that what you had in mind?

UPDATE
The above wasn't quite what you were looking for. No problem.

You say you have articles like Article 1 (Gaming), Article 2 (Local News), Article 3 (World News), Article 4 (World News) etc. Is it right that the word in parentheses is a taxonomy term? If not, the below won't be relevant, but I'll assume for now it is.

If so and you want to 'chunk' these terms into three categories, you could certainly modify the Views query or write your own.

Alternately (which is probably easier) you could change your existing vocabulary into a hierarchical taxonomy with News as the super-category and Local News and World News as the subcategories.

So now your vocabulary looks like:

News

Local News
World News

Gaming

Other

If your content was already tagged with the existing categories, you shouldn't have to change anything.

You could then create a View that displays the fields you want. Add a filter "Term Name," and enter "News." Then, add an attachment display, and attach it to your current View, overriding the filter and setting it to "Gaming." Finally, add a second attachment and override the Filter, changing it to "Other." This should give you the result you want.


Get a node using the same category (taxonomy term) the current node is using

Add CONTEXTUAL FILTER (Earlier arguments) on CONTEXTUAL FILTERS section on views click add, select "Content: Has taxonomy term ID" and in "WHEN THE FILTER VALUE IS NOT IN THE URL" choose Provide default value. Choose "Taxonomy ID from URL" check "Load default filter from node page, that's good for related taxonomy blocks". It will create a related taxonomy.


How to fix google page speed insights issue?

With AdvAgg enabled go to the status report page admin/reports/status. It should offer advice on how to fix gzip and browser caching for css/js aggregates. Also see the readme, under troubleshooting there are some tips for getting apache to do what you need it to.

If advagg doesn't report any issues then check and see what kinds of resources google is complaining about in terms of browser caching (.jpg) and compression (fonts). Also remember that if these are coming from an external domain (google analytics) there isn't a lot you can do as you don't control that server.

Edit: Guide here - https://groups.drupal.org/node/517292. It's the AdvAgg Readme file as well.


You could use the name of the current route:

$current_route_name = \Drupal::service('current_route_match')->getRouteName();

The route names from views are built like this view.[view_name].[display_id].

You can list the existing routes with Drupal Console:

drupal router:debug


How to make a form required with states?

You will need to validate this yourself in a custom validate function.

Everything configured by #states happens 100% in the browser, everything that it does is not visible for Drupal when the form is submitted (for example, all invisible form field are submitted and validated in the same way if there were no #states).


Creating a menu while categorizing my products

You can use Superfish to replace the default main menu that comes with commerce kickstart, however you use it at a cost since this jquery drop down menus are usually not optimized for mobile, although superfish provides some optimizations (most in a beta state right now).

Anyway if you need a big dropdown menu your alternatives are short, and Superfish provides minimal mobile browser support if used with a responsive theme (auto-resize and support for touch devices).


A distribution is a collection of Drupal modules configured to perform a certain function.  An installation profile is a script that will configure Drupal at install time.  A distribution always has an installation profile in it, but not every installation profile will be a distribution.  An installation profile can be distributed without the modules it uses; in that instance, you can use drush make to download them, as installation profiles include a make file.

Drush dl will download distributions as well as Drupal core and contrib modules (e.g. drush dl commerce_kickstart).  Distributions are updated whenever the developer chooses to update them; of course, you can always run drush pm-update on your copy of your distribution, but there are testing concerns -- occasionally, updates will break things.  This is no different with distributions than your own Drupal install, but in the case of a distribution, presumably the dev will test and fix problems before rolling out an updated release.


Change aspect of node add form (not only via css)

Ok I think that I have found the solution:

Theming Node Forms in Drupal 7 --  http://drupal.org/node/1092122

M.


How to customize the email subject for a webform?

So, I think you're using the UI wrong. Each of those email templates you have should be to a different user and it doesn't look like you've added an email to anyone.

Below where you have your Value of "Event Type" line there's the option to send an email to a specific email address (I.E the admin) or to add an email to the value of the Email token, you need to add and save an email to a specific person there and add a subject using your token substitution there. Or at least that's what it looks like from what you posted.


Conditional display of views based on comparing node taxonomy and user taxonomy

First, your view needs to be set up with a display of type "Content Pane". For this to be possible you need to enable the Views Content Panes module which is part of Ctools.

Next, you need to add a contextual filter (also called an argument) for your taxonomy field. The option to do this is under Advanced on the Views UI for the view. The process is similar to adding other parameters to a view, so I'll not cover it in detail.

Once the contextual filter has been added you need to ensure it can be supplied by the panel you are going to add it to. To do that, click on the Edit link next to "Argument input" under Pane settings. Set the source of the argument to be "from context" and the required context to be "term ID of first term".

On the panel editor, you need to add a context for the logged in user. On the contexts tab for the panel, select "user" for the type of context to be added, then press the add context button. Choose suitable identifiers for the user context and select the "logged in user" option, then hit Finish.

Now from the same tab, under Relationships, you should be able to find an option to add a taxonomy context via the user context. It'll be labelled something like "Taxonomy term from User (on User: fieldname [field_fieldname])". Add it and assign it a meaningful identifier.

Now finally you should be able to add your view display pane to the panel. On the content tab, you'll find it under "View Panes" on the add content dialogue. After you click on it you should see the settings for it, which should consist of a selector linking the contextual filter from the view to the context from the panel. If there is only one taxonomy term context available, the correct value will probably be already correctly set. Save everything and test.

Good luck!


How can I programmatically add data to an address field?

If you have a field with multiple properties then use an extra array:
$values = [
  'name' => $user["name"],
  'pass' => '',
  'status' => $user["status"],
  'mail' => $user["e_mail"],

  'field_address' => [
    'first_name' => $user["first_name"],
    'last_name' => $user["last_name"],
    'city' => $city,
  ],
];


How do I create an entity using the properties of another entity?

Does this sound like a reasonable approach?

You've put some thought into this, it doesn't sound unreasonable -- nor does it sound simple.

  Is there a better way to think about this/do this?

If your reading Questions are simply textareas great, if they're radio boxes and select widgets look into leveraging an existing "quiz" or form builder like: webform, webform_entity or the quiz module.

  If it is reasonable, is there a way to pass a reading entity to the Assignment Entity so that I can properly construct an assignment from the reading data?

I have cloned nodes before in Drupal 6/7, which isn't too hard. I think you need to really iron out a workflow for "if I make a reading -- I can create Assignment(s) and/or AssignmentQA entities". You could try creating this workflow logic for instructors using workflow, maestro or using a set of Rules.

If you try and just "I made a reading entity". You could always make a view that allows you to create a hook_menu() link to a new node edit form using a Reading Node as a menu argument -- then you could see the original node's fields easily for cloning.

  And, how do I go about cloning the pdf file field, such that the pdf file can't be deleted from the server if it is updated, but the old version has already been assigned to someone? (e.g.- I'd like to use the updated PDF for any new assignments created, but keep the old one around for old assignments).

In D7 the file_managed FAPI element allows you to set an "owner" module for the FID, I believe only that module may deem the file as 'deleted'. So using a custom FAPI override you could specify a module you control as the enforcer for this ruling. The D7 file_entity module is seeking to add views to track individual file usage of FIDs i'm not sure if it's ready for prime time usage.


How to add taxonomy term reference field in a custom form

Well, I have found the way in the change records. take a look at: https://www.drupal.org/node/2418529

Here is the example options for taxonomy fields:

'#type' => 'entity_autocomplete',
'#target_type' => 'taxonomy_term',
'#selection_settings' => [
  'target_bundles' => array($vid1, $vid2),
],


Look at the documentation for hook_node_access, here:

https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7

The key is where it says:

Also note that this function isn't called for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.)

You probably want to check the link following that comment, i.e. the node access rights description, which got more complicated in D7 from D6.

Another thing to pay attention to is: if you're logged in as user id 1, then you won't be affected by those node access grants.


If you don't want coding, this is one possibility:

If you only have one form, but hundreds of nodes, another way I would suggest to do it is to use Webform Template for the School content type. You can create one webform template and then reuse it for every school node, but the address field in the webform should have a default value that is a token of the node's address field. All you would need to do is set up your webform template's address field to have a default value of something like [node-field-school-address] and every instance of the webform will have the address of the node it belongs to.

In order to use tokens in a webform, you will need this module: Webform Patched . This is a module that contains the Webform module itself along with token support an therefore the original Webform module should be disabled. I implemented this myself for my site and it worked without any problems.

I never worked with addressfield, but I found this module in case you need it: Addressfield tokens


How to implement just a 'Purchase Order' solution (without Drupal Commerce)?

Below are 2 possible alternatives (options) for setting up a simple shopping cart without using Drupal Commerce (as in your question) (or Ubercart) modules.
Option 1: A lightweight e-shop
If you're only looking for a simple and lightweight e-commerce solution, then have a look at the Light Shop module. Here is a quote from its project page:

Session-stored basket.
Adding to basket and its subsequent editing/checkout process is done using AJAX. Also it works fine when JavaScript is turned off.
Node based shopping. As the product can be assigned to any node type. One or more. With full support Field API features (regarding nodes).
Orders history. For each order will be created a separate node.
There is no dependence on other modules.
Full support for working with anonymous users
Integration with Views.

Option 2: A simple shopping cart
If you're only looking for a shopping cart, then have a looking at the Basic Cart module. Here is a quote from its project page:

Basic cart is a very simple shopping cart / checkout process for Drupal, that just sends 2 emails after each order. Along with the shopping cart, this module also provides a block where you can view your cart's content. It's ideal for small websites with only a few products or other content types being sold, for example touristic offers.
Main difference from Ubercart and Commerce:
The main difference from Ubercart and Commerce is the possibility of choosing the content types that can be added to the cart. It also doesn't bother you with the Product SKU, that can be a pain when you have just a few products.
Features:

The possibility of choosing the content types that can be added to the cart.
The possibility of sending, or not, an email to the customer once an order is placed.
Custom email messages for both the site administrator and the customer, along with the order details.
Order registration and listing in the administration area using Views module.
Integration with Rules module.
A block with the contents of your shopping cart.

Here is a screenshot of it (note the Checkout button also ...):


How to conditionally load - and allow a user to populate - a taxonomy image field in node create/edit form?

Might I suggest that you avoid taxonomy all together?

I am not a fan of taxonomy namely because it isn't a reliable way to tag your content.  The most obvious is that any variation in the tags creates a whole new tag.  For example, if you are doing a web site and you want to use the taxonomy of the different fruit:

apple != Apple

If you now go and create view to show all related content for "Apple", you won't get anything related to "apple."  Technically speaking, you can have 256 (2^8 = 256) permutations of your taxonomy term; not very useful, if you ask me.

So, the question is, what to use then?

Use your own Content Types.

For example, I created a content type called "Section" and the only field I have in the content type is "Title" which I renamed to "Section Name".  (You can ignore the "URL path settings field."  This is because I had pathauto installed.)

Next...create some Section Names by adding content.  Here I have added two content types:  Big and Little.

And if you "Edit" or "View" that piece of content you will see that there is nothing but the one field that you created earlier.

Next, is to create an entity reference to that content field  This is where the magic happens.  In another content type like "Article" (or whatever you like), create an entity reference field that links back to the "Section" content type.

Here, I have a content type called "Static Content" with just "Title" and  "Body". I added an entity reference field called "Section", gave it machine name of "field_er_section" for readability, and made it a checkbox/options type of selector.

When you create/edit the field, you must make sure you reference back the content type you first created, in this case "Section".

How does this all come together?  Let's take a look at a new piece of content that we create....

As you can see, we now have "terms" that the user can select rather than type out.

Where does this come in handy?  How about Views?
You can now add some filters based on your new "Section"

Execute your view and you have all content related to your new term.

Now, if we were to do this with "contextual filters" (found under Advanced in the Views page) you could base your view on the values in the URI.  For example, using the section names in my pics above:

www.example.com/little/

That would display all content related to "Little." You could also create a block view that would display all the titles of related content based on the term in the URI.

Now, as for your specific question, how do you add an image to your taxonomy term?

This is a content type, after all.  Just add an image field and that image will follow throughout your site.

I hope that gives you a direction to go in and a nice alternative to taxonomy.


Is there a way to serve a specific node for certain paths?

Core has URL aliasing built in, and having multiple aliases for a single path is supported.

You can manage these at /admin/config/search/path (assuming you have the core Path module enabled).


Create Bundle Product link - Not found, missing

They are missing because of how Kickstart manages it's menus.

The easiest way to fix this is to just disable the Commerce Kickstart Menus (commerce_kickstart_menus) module. You may need to clear all of your caches, but you should see the other items start to show up again.


change node field value without node->save or without causing hook_entity_presave infinite loop

I think I have found a simple solution

add revision message with UNIQUE string before saving the node

    //...
    $node->setNewRevision(TRUE);
    $node->revision_log->value = "AUTOMATED-UPDATE ". $field." incremented to ".$old_value ;
    $node->save();

check on the hook_entity_presave that the revision was not AUTOMATED by checking in the log for our UNIQUE string

    if ($entity->getEntityType()->id() == 'node') {
        $log = $entity->revision_log->value;
        if( substr( $log, 0, 16 ) === "AUTOMATED-UPDATE" )
            return;
        ...


Redirect on node form submit with custom module - hook_form_alter

use hook_nodeapi with op insert or add another submit function in hook_form_alter.


This module will help you views_rules

From module page:

  View loop

  A view loop is similar to a regular Rules loop, but allows looping
  over rows of view results.

  Collect view result rows (action):

  This action collects each variable in all view result rows into list
  variables for use in Rules.


Why is my update query OK for the database but the page shows the wrong value?

I replaced

foreach ($results as $key=>$result) {
  $numberofrowsaffected = $database->update('person')
    ->fields(['iscontact' => 0,])
    ->condition('id', $result->id)
    ->execute();
}

by

  $storage = \Drupal::entityTypeManager()->getStorage('person');
  foreach ($results as $key=>$result) {
    $person = $storage->load($result->id);
    $person->iscontact = 0;
    $person->save();

And it works!


How come images with image styles are blurry?

I've delt with this issues on many sites. The cached version from the image style always renders poorly. I'd recommend removing it and using CSS to adjust the sizing.

In some cases, removing existing upload size limits on the image field has helped resolve this.


create link for URL-based text field in content type

Click on edit in front of your link field in your content type's manage field tab.

You need to change Text processing option to filtered Text.

Then while adding this content type just type the URL with HTML tag.

I hope this solves your problem without installing a module.


How to create html page via module drupal 7

Use Drupal's Form API. Basically your code will look like this:

<?php
    $menu_items['user/campaigns/new_campaign'] = array(
      'title' => 'Campaigns',
      'type'=> MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('create_campaign_form2');
      'access arguments' => array('access content'),
      'file' => 'campaigns.create_campaign2.inc',
      'weight' => 1,
    );
?>

<?php
   $form = array();
   $form['selected'] = array(
     '#type' => 'select',
     '#title' => t('Selected'),
     '#options' => array(
        0 => t('No'),
        1 => t('Yes'),
     ),
     '#default_value' => 'Maybe',
     '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );
   return $form;
?>

Notice the use of drupal_get_form() in the menu hook. This function takes the return value of create_campaign_form2, which it expects to be a PHP array, as an argument and uses that data to build the markup of the form.

This particular example will generate a form with only a select drop down. But check out the complete Form API reference for all (and there are A LOT) of the options and settings you have available to build your form. It might be intimidating at first, but the idea is quite simple: you create a PHP array that represents your form and then drupal_get_form() turns that array into a secure and well structured form. ALWAYS use the Form API to build forms in Drupal.


Webform: How to prevent rendering of private fields

I've found that best solution is to use hook_form_alter to remove element from rendering. It can be achieved by this workaround: $form['submitted']['my_field']['#access'] = FALSE;


How to obtain the machine name and field type of the fields of a content type filtered by those created by the user?

If you mean the fields configurable in UI, then you can get them through EntityFieldManager::getFieldDefinitions:

$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'article'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

$result = [];
foreach ($fields as $key => $definition) {
  $result[$key] = [
    'type' => $definition->getType(),
  ];
  // if the field is a reference field get also the target entity type
  if (in_array($result[$key]['type'], ['entity_reference', 'entity_reference_revisions'])) {
    $result[$key]['target_type'] = $definition->getSettings()['target_type'];
  }
}

Entities have base fields defined in code and bundle fields defined in configuration. Drupal doesn't keep track whether a bundle field is configured by you or is from another source. A field can be pre-installed by a module, then deleted and added in UI again and Drupal wouldn't be able to tell the difference.


How to connect to MySQL with SSL connection

Finally got it figured out. It's "driver options", not "PDO attributes".

  $databases = array (
    'default' =>
     array (
       'default' =>
        array (
          'database' => 'drupaldb',
          'username' => 'drupaluser',
          'password' => 'password',
          'host' => '192.168.10.100',
          'port' => '3306',
          'driver' => 'mysql',
          'prefix' => '',
          'driver options' => array(
              PDO::MYSQL_ATTR_SSL_KEY => '/path/client-key.pem',
              PDO::MYSQL_ATTR_SSL_CERT => '/path/client-cert.pem',
              PDO::MYSQL_ATTR_SSL_CA => '/path/ca-cert.pem',
           ),
       ),
    ),
  );


Adding wysiwyg (ckeditor) to textarea on node edit form

I usually do this by installing better formats module.   This give you the option to set the default format for a cck field when you create it.


Ckeditor - Not displaying text on edit node option

You have to give the Authenticated user role the rights to use the input format CKEditor used to save the page. Look on the access rights page, URL depending on  Drupal version.


You can create custom layouts in your theme for panels, there's a fairly good how to guide here: https://drupal.org/node/495654

If you wanted to use different layouts for different nodes, you can add a variant to your panel pages, and under "selection rules, select "node:type" and select the content type you want. Then you can assign different panels layouts to each respective variant under the layout tab.


Turns out nid in Drupal 8 is now listed as ID - and it is listed liked this:
Title - ID and Category - content.  It appears on the view as Content: ID. I put this in Fields and made it hidden.  I added a relationship to my other content type.  Then for contextual filter I used the Content:ID with the relationship. Under When filter is not available, I picked Provide default value: Content ID from URL. And then the view worked.


Alter element_info and troubleshoot changed elements

The underlying problem was caching. I thought I had cleared cache, but apparently not.

Here are answers to my questions:

As suggested above, use watchdog() to see the value of the $type array. Here is a (probably dangerous) snippet:

watchdog('customcode', 'uc_price after mod: <pre>'.
print_r($type['uc_price'], TRUE) . '</pre>');

hook_element_info_alter is how I want to modify the element, and the function should replace hook with the name of the custom module.

It looks as if all hook_element_info_alter hooks are called after all type elements are defined somehow, but I am still fuzzy on this.

I am not certain when hook_element_info_alter is called, but it appears to be called early (there is no need to visit the form in question) and it appears to be cached for a long time.

My strategy of setting #allow_negative to TRUE was in fact the right approach, because the validation function uc_store_validate_number takes this into account. Otherwise I would have had to unset the validation function and replace it with a custom one.


Behat, Selenium and Chromedriver CI errors

Apparently Codeship, the CI provider that I am using, had a different version of chromedriver that conflicted with my setup.
Running chromedriver 2.35 fixed the problem.

Many thanks Aswini K for the effort provided though!


Have you just now updated your PHP than you may need to restart the apache and check if it works, and still if you get the above error than check Installing and Troubleshooting Drush.

One dirty hack of installing the drush is mentioned here: https://drupal.org/files/drush-document_env_var-1841324-25.patch. But I won't recommend you to use this as you are already having the PHP 5.4 and that hack for PHP version < 5.3.3


views slideshow force al link to basic page instead of the slideshow's custom made url

Add a field to the content type which you are using in your slideshow. Use this field to hold the URL it should point to. Then, add the field in your slideshow view and make it hidden. Now you can use that hidden field to rewrite the URL of the image in the view.


How can I filter child terms in an exposed filter by parent term from contextual filter?

I've done this recently in a project of mine using MYMODULE_form_views_exposed_form_alter. The code assumes you've a view with the term ID on first position as contextual filter, e.g. domain.com/myview/123

<?php
function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $view = $form_state->getStorage('view');
  $display_id = $view['view']->current_display;

  if ($form_id == 'views_exposed_form' && $view['view']->id() == 'MY_VIEW' && $display_id == 'MY_VIEWDISPLAY') {
    if (!empty($view['view']->args) && $view['view']->args[0]) {
      //get the term ID from the contextual filter
      $contextTermId = $view['view']->args[0];
      $entriesToRemove = [];

      $currentFilterValue = $form_state->getUserInput()['FIELD_FILTER_TAXONOMY'];
      foreach ($form['FIELD_FILTER_TAXONOMY']['#options'] as $idx => $entry) {
        if ($idx === 'All') {
          //remove the old root '- Any -' option
          $entriesToRemove[] = $idx;
        }
        //the next line is a bit shaky might need rework:
        //sometimes filter entries are a stdClass,
        //but I've also seen entries as array in other exposed forms (grouped filters?)
        elseif ($entry instanceof stdClass && is_array($entry->option)) {
          $termId = key($entry->option);
          $termName = current($entry->option);
          //the context filter term is our new root, so we change its label to '- Any -'
          if ($termId == $contextTermId) {
            $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => t('- Any -')];
            if (empty($currentFilterValue) || $currentFilterValue == 'All') {
              //we've removed the default empty/All entry, reset it to our newly created, faked '- Any -' category
              $form_state->setUserInput(['FIELD_FILTER_TAXONOMY' => $contextTermId]);
            }
          }
          else {
            //this is the core part: for each filter option load the term
            //and check if it is a child of the contextual filter term
            $parents = \Drupal::entityTypeManager()
              ->getStorage('taxonomy_term')
              ->loadParents($termId);
            if (!in_array($contextTermId, array_keys($parents))) {
              $entriesToRemove[] = $idx;
            }
            else {
              //optional: we are in a sub-filter now,so we no longer need the leading '-' to indicate hierarchy
              $form['FIELD_FILTER_TAXONOMY']['#options'][$idx]->option = [$termId => trim(preg_replace('/^-/', '', $termName))];
            }
          }
        }
      }
      foreach ($entriesToRemove as $idx) {
        unset($form['FIELD_FILTER_TAXONOMY']['#options'][$idx]);
      }
      //optional: if there is only 1 entry left, hide the filter
      if (count($form['FIELD_FILTER_TAXONOMY']['#options']) == 1) {
        $form['FIELD_FILTER_TAXONOMY'] = [
          '#type' => 'hidden',
          'value' => $contextTermId
        ];
      }
    }
  }
}

A word of caution: Don't to this on huge taxonomies, my code loads every taxonomy term to decide if it needs to be removed.


Drupal 7 same token showing twice in token available admin page

This is normal behavior and nothing wrong.

The token with '_' gets generated by 'token' module, and
the second with '-' gets generated by 'Entity API' module (entity tokens).

Any one can be used.


Leaflet maps multiple icon types in views

Here is what I did. You should be able to tweak it to fit your needs:

I created terms and uploaded images for them.
I created nodes and associated terms with them.
I went ahead and created my leaflet view, using the appropriate
token in Point Icon in leaflet settings.

I hope that helps.


Uncomment your selectors, and your item_selector should be:

nlm/ and not just nlm.

I had this same issue when I was setting up a JSON migration and that was the first thing I ran into.


If the "signature" doesn't contain any special programmatical behavior and its basically textual (whether styled with CSS and/or images or not)

Than I have the ultimate simple solution for you:

Create a block with the desired content, and place it under your "Content" block on your main content region by going to Structure > Block layout.

The signature-block will now appear under every page/node (you could filter where it would appear by means of content type or NID -> Node ID number).


How to change the check box to radio buttons Yes/No in tableselect form api?

You need to set '#multiple' => FALSE on the tableselect where you declare it. This will set the tableselect to use radios rather than checkboxes.


How do I find out what controls access to a page?

For Drupal 6 and 7, the basic access check details are stored in the table menu_router.

To find out the relevant details, try a query like

SELECT path, access_callback, page_callback FROM menu_router WHERE path LIKE '%user%';

Lets look at three examples returned by that query on a local site of mine:

| path                | access_callback  | access_arguments   | page_callback
| user                | 1                | a:0:{}             | user_page
| user/%/edit/account | user_edit_access | a:1:{i:0;i:1;}     | drupal_get_form
| user/%/display      | user_access      | "administer users" | ds_contextual_page_tab

The data above has been manipulated slight for brevity.

First: user. userhas an access callback of  1, which means it will always pass. This is not, as one might think, to allow everyone access, but usually rather because the access decisions for this particular path are complicated enough to require more than a regular permission. Because of that, we need to look at the next column, which is page_callback. This tells us which function is called to actually handle the page, and page_arguments, in this case empty, could contain any arguments passed to the same function. In this case, there are no arguments, so we can't learn any more here. One needs to start reading the code of user_page() to figure out more.

Second: user/%/edit/account. This path has a standard access_callback, which means that user_edit_access is called, and if it returns TRUE, we'll be given access. One needs to read that function to find more details.

Third:  user/%/display. This one is the easiest. user_access simply checks if the user has been assigned the permission that is passed in from access_arguments, so in this case administer users. If that permission has been checked for the users role, access will be granted. User 1 automatically gets to bypass such checks.


If you have created that custom block using a view , yo can easily add link to the respective node.You can add content: link in the FIELDS section


Select query for get title and url of node

You don't need to make any tricks like that to compare a timestamp to the current year.

You can obtain the year of the timestamp by using the PHP date function:

date('Y', 1394010573)

will return

2014

You can obtain the current year by using the same function but without mentionning any timestamp (it will take the current date by default):

date('Y');

Knowing this, you can easily limit your query.


In views pagerer you can limit "Items to display " section and give the option as 1 to limit ome image to display from that filter


How can I display the Google rich snippets when a view is on "Show: fields" and the panel enabled?

I see that you are using views fields mode for populating the values. That might be the issue.

In your overall HTML check that an entry for itemtype="http://schema.org/Recipe"> is present. In your current html I feel you wouldn't have this. If that is the case then change the mode in your views to node from fields.

Then recheck your HTML and you should find the entry. If you do find the entry then the reason is that your fields(in old view mode) are not enclosed within a recipe tag.

In the above case you can install schema tokens module and then in your fields view, hide all the fields and then add a Global text field within which you can use these tokens to get the desired output.


It's trivial, but—did you try changing the row plugin to Fields instead of User?
With fields, you have granular control over the display of the user profile, so this might in effect be what you're looking for.


Can view file list in IMCE but can't load files

I know your question is 6 months old and you have probably solved it or found a workaround... but I had exactly the same problem and wanted to share what has worked for me, in case it could help others.

At the beginning I had a default single site and IMCE worked perfectly, a few months later I set up another site in multisite configuration, and IMCE didn't work on the second site : no upload, insert, suppress buttons in the top bar, and no possibility to view images or insert them.

In fact it was not a multisite problem, it was due to a jQuery incompatibility.

Both sites use the jQuery Update module :

for the default site, the default version is jQuery 1.7
for the second one, the default is jQuery 1.9 for the front theme (and 1.7
for the admin theme, but IMCE uses the default version).

If I tried to use 1.7 version for the second site, IMCE get to work.

So, in order to still use jQuery 1.9 or newer (needed by the front theme) and have IMCE working, you can use jQuery Migrate Plugin to resolve incompatibilities.

There is a patch for jQuery Update here, I applied it, get to jQuery Update config page, selected "Enable jQuery Migrate Plugin" (with or without the CDN), and it worked perfectly !


Problem dynamically populating a select field based on the selection of another select field

You're wrapping your model select options array in t()

i.e: '#options' => t($models) vs '#options' => $models

Try this instead, it might work:

  $form['model'] = array(
    '#type' => 'select',
    '#options' => $models,
    '#prefix' => '
',
    '#suffix' => '
',
  );


What is wrong in my code for replacing the text of 'add to cart' button?

try this

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}


Perhaps something like this:

function mymodule_page_callback($parent_nid){

  global $user;
  try{
    // Create new node, assumes default LANGUAGE_NONE
    $node = new stdClass();
    $node->title = 'Title';
    $node->type = 'my_type';
    $node->language = LANGUAGE_NONE;
    $node->uid = $user->uid;
    $node->status = 1;
    node_object_prepare($node); // Sets some defaults.
    $node = node_submit($node); // Prepare node for saving
    node_save($node); // Returns $node by reference with nid

    // Set entity reference on parent node
    $parent = node_load($parent_nid);
    $parent->field_entity_reference[LANGUAGE_NONE][] = array(
      'target_id' => $node->nid
    );
    // Save parent
    node_save($parent);
    // Go to edit form for new child node
    drupal_set_message("Node created");
    drupal_goto('node/'.$node->nid.'/edit');
  }catch(Exception $e){
    watchdog_exception('my_module', $e);
    drupal_set_message("A problem occured creating the node", 'error');
    drupal_goto(); // front page
  }

}


Notice: Trying to get property of non-object in function MY_MODULE_form_comment_form_alter()

You have the wrong function signature. It is supposed to be:

hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

In your function, $comment_count is set as the form_id, and $comment will always be null.

Set it to the signature above, then use $form['nid'] and $form['cid']. To get the comment count on the node, inspect at $form['#node']->comment_count

Here is a replacement code for what you are trying to do:

function MY_MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->comment_count){
    // node has comments
    $form['#attached']['css'] = array(
        drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.', 'file');
  }
  else {
    // no comments on the node
    $form['#attached']['css'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE2.css.', 'file');
    $form['#attributes']['class'][] = 'new-comment-form';
  }
}


Problem in displaying with Embedded Google Docs Viewer module

Open the PPTX file and Save As a PPT file.  This worked for me to prevent the unexpected symbols in the google docs viewer when trying to embed a PPTX file.


How to move drupal 7 site in a different path from Home directory

Depending on your server setup, it should not be hard. My only recommendation will be to disable the clean urls and the 444 permission of the settings.php file before moving the site over. After the move is done check if the .htaccess file is there, clean the cache, re-enable the clean urls and restore the permissions to the settings.php file to 444.


How to sort only own webform submissions in a view?

The solution was to specify as Filter criteria "webform submission:user " and in fields I added the same criteria. Then I customized it by creating a label name.

The video tutorial Drupal Views Module: Creating lists of content on your Drupal site really helped me discovering Views and find an answer to my question (I recommend it for every beginners like me).


You can do it using the hook_webform_submission_presave() exposed by the Webform api in a custom module.

Another alternative is to make use of this sandbox project

  This module provides a way to calculate values for Webform components
  and/or to add custom validation code without the need for creating
  custom modules that implement hooks. It offers a PHP-like macro
  scripting language to use instead.

  Differs from Webform PHP in that there is no eval() evil and macro
  code has no direct access to Drupal environment or functions, i.e.
  macro code is contextually jailed.

  Differs also from Webform Calculator in that it permits logic-driven
  calculations and also integrates with the Webform Validation module.


How to remove the title from a youtube video when using D7 + media module?

It looks like that's the field label, which can changed on the manage display page (Structure > Content Types > Manage Display)