Private file system, The upload directory private://webform/XXXX/_sid_ for the file field could not be created or is not accessible

Your path must exist outside of your webroot directory and be an absolute path, for example: /var/www/private )

Also check PHP configuration

file_uploads = On must be set to "On"
upload_max_filesize = 24M can't be larger than post_max_size
max_input_time = 300 small values may cause timeouts for large file
uploads
memory_limit = 64M small values may cause out of memory errors for
large file uploads
max_execution_time = 180 small values may cause timeouts for large
file uploads
post_max_size = 24M limits the size of input submitted to the website
(including attached files)

Information is taken from here.


In display suite manage display, put 1 (the number of image to display) instead of #1


What is the best approach to write hooks?

I think your question is more of in-general type . Please specify for what all purpose you need to use hooks .
I think this might be helpful for you : http://www.stephanemartinw.com/articles/25-theme-drupal-hooks-templates-functions

Thanks


Sorting logic with anonymous function does not work

PROBLEM SOLVED. As J. Reynolds pointed out there were missing nid values in $view->result before the sorting was made.

There was also an issue with the nids because I had forgotten to set the field mapping (migrate d2d) to "do not create automatic URLs" for pathauto during a an earlier migration from D6 to D7 of the group nodes that contained the items in question. So the item nids were fetched from the wrong group entity. My mistake :-(.

But everything is sorted out now. Thanks for your input!


Get values from views exposed filter in hook_views_pre_view

I've found it, there is a views method:

$input = $view->get_exposed_input();


How would i redirect a user after registration to his subdomain site

Use Rules again to do the redirect.

On Event Drupal is initializing or User has logged in add a condition if you need that (eg check that user role is not anoymous) and then add an Action of Redirect. In there use some php for the redirect path using the global variable $user (you may need some formation also if the username has spaces).

Notice that you must run this Rule after the rule that creates the subdomain. Or you can simply add the redirect action on the same domain_rules rule after the component that creates the subdomain.

You must also have a common user database along sites (domain and subdomain). The Bakery module is a good option here.


hook_block_view() is only invoked for the module that defines the block via hook_block_info().

To alter the content of a block provided by another module, use hook_block_view_alter() instead.


It was not resolving the host names. Added an entry to /etc/hosts and it worked fine.


What is the name of the module that gives a detailed report of modules and themes installed?

It sounds like you are talking about the Module summary module for D7. The Used modules for D6 is no longer supported.


You might be able to get this to work by using the Rules module.
Depending on how the format of your URLs look like, you may want to also use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface. Using those you might be able to build an appropriate rule to issue a redirect (+ display a message if needed) based on some Rules Conditions that implement your access restrictions.

For more details, refer to my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?".


about constructing a database for student multi-step form

The "users" table is for containing information about what the Drupal site sees as authenticated users, which means the users with a login in a Drupal site.

If you are adding information about users that don't need to login on the site, e.g. people working for an organization for which you keep information, then you should not use the "users" table. You should create your own table that contains the necessary dat; possibly, you should create a custom module that creates that database table when installed.

If you are adding users as authenticated users, and you need to store extra information about those users you can:

In Drupal 7, you can add extra fields to the user's account.
In Drupal 6, you can enabled the Profile module, which allows you to add extra fields for the user profiles.
In Drupal 6, and Drupal 7, you can create a module that handles that information.

Of the two solutions, on Drupal 7 it is better to use the fields provided by the field API; if you need to handle the fields in a specific way, you can implement a new type of field in a module.

If you need something more customized, such as a multi-step form to fill the information, then you could write your own custom module that creates its own database table, and uses the user ID as primary key. In this case, you would need to write more code, such as the one that deletes rows from the database table when a user has been deleted from the "users" table. In Drupal 6, that could would be in a hook_user('delete') implementation, while in Drupal 7, it would be in a hook_user_delete() implementation.


Dymanimcally add links in main menu (e.g. last 4 nodes)

Make the URLs static; have the content of those URLs change

You were on the right track with views. But don't use it to create a block with the links, use it to create a page that displays the full rendered entity of the last node of your content type. You can give it a URL like /latest-article.

You could get fancy and use contextual arguments to display the 2nd, 3rd, ... offsets (e.g. /latest-article/%) or you could just add four more displays to the view, each with the offset bumped up by one.


Drupal 7 CKEditor-CKFinder remove "Browse Server"

Well I have found that patch solution. So just answering my own question.
In sites/all/modules/ckeditor/includes/ckeditor.lib.inc file,

There is a section as

if (user_access('allow CKFinder file uploads')) {
                $ckfinder_full_path = $host . ckfinder_path();
                //$settings['filebrowserBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?id=' . $profile_name;
                //$settings['filebrowserImageBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Images&id=' . $profile_name;
                //$settings['filebrowserFlashBrowseUrl'] = $ckfinder_full_path . '/ckfinder.html?Type=Flash&id=' . $profile_name;
                $settings['filebrowserBrowseUrl'] = '';
                $settings['filebrowserImageBrowseUrl'] = '';
                $settings['filebrowserFlashBrowseUrl'] = '';
                $settings['filebrowserUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Files&id=' . $profile_name;
                $settings['filebrowserImageUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Images&id=' . $profile_name;
                $settings['filebrowserFlashUploadUrl'] = $ckfinder_full_path . '/core/connector/php/connector.php?command=QuickUpload&type=Flash&id=' . $profile_name;
            }

So I commented the actual filebrowserBrowseUrl, filebrowserImageBrowseUrl & filebrowserFlashBrowseUrl settings and made those as blank. That did the trick.


How to display a comma-separated list of multiple field values?

While it's possible to use CSS for this I think it's better to avoid it. I've simplified the field twig file to illustrate, but it would look something like this:

{% for item in items %}
  {% if loop.last %}
    {% set separator = '' %}
  {% else %}
    {% set separator = '/' %}
  {% endif %}
  {{ item.content }}{{ separator }}
{% endfor %}


How to hide a field when its value is set to zero

I'm not sure why you are using presave operation.

If you want to hide a field on node view you should use view operation.

So your code should be as the following code:

function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type=='salary_info' && $op=='view') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value'];

    if ($public_holiday == 0) {
      // you don't need to load node again.
      unset($node->field_pd_public_holiday);
    } else {
      drupal_set_message("HOLIDAY");
    }
  }
}

Edit:

If you want to hide field on another content type or node using presave operation, then you need to load node and unset field value then save node again using node_save function

So your code should look as the following:

function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  if ($node->type=='salary_info' && $op=='presave') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value']; // here I get the value that I set to 0(No) or 1(YES) using a select list.

    if ($public_holiday == 0) {
      $node = node_load(207919); // load node by nid
      unset($node->field_pd_public_holiday[0]); // unset field from node object
      node_save($node); // save node after unsetting the unwanted field value.
    }
    else {
      drupal_set_message("HOLIDAY");
    }
  }
}


allow users to continue the survey (webform) if closed by accident

It's simple. Go to your webform and add page break type wherever you want to split the form.

Then go to Form Settings and check Automatically save as draft between pages and when there are validation errors. or Show "Save draft" button.

If you want to go further, meaning if you want to save a draft when user closes the browser. check Use AJAX to auto save a draft


What might be stopping this Contextualised Filter work in Block (please)?

Found the answer - a logical issue rather than a question of using the controls.

The key was to reverse the order of bringing in content.  Set the main content-type as galleries, then use an entity relationship (set that up first) on Relationship to bring in fields from images and sort on them.

With this procedure, Views can use a Contextual filter for the Galleries. I will wirtie it out more fully on my blog.


Hide some part of node when the field_countdown timer is zero

You might use twig without method. It will print all configured content to be rendered without the selected fields/properties.

{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    {# Show #}
    {{ content }}
{% else %}
    {# Hide - print the content without the field_timer #}
    {{ content|without('field_timer') }}
{% endif %}

For some cacheability issues it is recommended to always print content.


I'd check out Login Toboggan.  There's an example on the project homepage that nearly matches your use case.


Drupal 7 url with hex code for special characters?

You can use the following snippet.

$decoded_url = rawurldecode(rawurldecode($url));

For example, for the second URL, the code returns http://example.com/drupal7/?q=node/1#overlay=?q=admin/config/content/formats.

That URL anyway is not usable as it is, as it would be wrongly parsed. For example, if on my browser I enter http://tero.local/dr72/?q=node/1#overlay=?q=admin/config/content/formats (tero.local is the local name used from my computer), what I get is the following page.

As you see, the overlay is not shown.
Differently, when I enter http://tero.local/dr72/?q=node/1#overlay=%3Fq%3Dadmin%252Fconfig%252Fcontent%252Fformats, I get the following.

In this case, the overlay is rendered.


Why is my twig variable not working inside my block twig?

Because the field is being rendered, which is different than evaluating its value. content.field_content_side is a render array which holds a lot more than just 'value'.

Try:

{% if node.field_content_side.value == 'left' %}

To get this in a block, you would add this to mytheme.theme:

/**
 * Implements hook_preprocess_block().
 * @param $variables
 */
function mytheme_preprocess_block(&$variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['block_content'] = $variables['elements']['content']['#block_content'];
  }
}

Then:

{% if block_content.field_content_side.value == 'left' %}


A custom Views template for the exposed form might do it.

wrap it in a div, and use either a custom jQuery or third party pop-up script within the tpl.


Module not appearing in list after pushing to Acquia Cloud

Unless it's automated, you'll also need to pull to code from the remote repository onto your web server.


Custom PHP code in Rules differs from Devel's one

I have finally suceeded by deleting and creating a new rule with the same PHP code ; I guess there must be a bug in there !


You need to load a taxonomy term using taxonomy_term_load

This should get you on the right track.


Interchange below lines that should work !!

$max_length = 10; //variable_get('title_max_length');
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));

to

$max_length = 10; //variable_get('title_max_length');
drupal_add_js(array('common' => array('max' => $max_length)), array('type' => 'setting'));
drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js');


Why don't you duplicate the view that works and just reconfigure the filter criteria to met your requirements?


A commerce product is an entity like any other, so...

$cp->field_my_field[LANGUAGE_NONE][0]['value'] = '22';


How create a new variable according field value

Your code is already there, i think you didn't extract the value of the field_display_reviews correctly, try the following:

 /**
 * Implements hook_preprocess_HOOK().
 */
function mytemplate_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $node = $variables['node'];
    if ($node->type == 'config') {
      if (
        isset($node->field_display_reviews[LANGUAGE_NONE][0]['value'])
        && $node->field_display_reviews[LANGUAGE_NONE][0]['value'] == 'yes'
      ) {
        $variables['display_reviews'] = 'this variable need be created';
      }
    }
  }
}

NOTE: if your display_reviews field of type Boolean the value it will be 1 instead of yes, print the value of $node->field_display_reviews[LANGUAGE_NONE][0]['value'] before if to see.


As @Clive and @prkos mentioned in comments above, Drupal has different stream wrappers for public and private file systems:
https://www.drupal.org/node/15368
I know you are using Drupal 7, but the Drupal 8 docs on the topic mention:

In Drupal 8, you can no longer set private file system via UI. You set it in your settings.php file.

So you might find it convenient that you can configure this in the Drupal 7 admin UI ( "Private file system path" under admin/config/media/file-system) without any edits to your site's codebase.
If you have configured the private stream wrapper correctly, you can prevent anonymous users from downloading those files and instead respond to their attempts with an HTTP error 403.
The remaining desired functionality is provided by the community-contributed module that @Clive mentioned:
https://www.drupal.org/project/r4032login
The module is available for Drupal 7, 8, and 9. Its project page will explain its usage, but basically it redirects users to the login page when they ask to access a restricted resource, and redirects them to their intended destination once they log in successfully.


It is possible.

Apache solr search module introduced tpl files for each search page.

If your custom search page's machine name is simple search, the search results tpl for that page will be named as

    search-results--apachesolr-search--simple-search.tpl.php

Replace simple-search with the machine name of your search page, with underscores converted to hyphens.


How to change the behaviour or display of the language switcher?

Add next into template.php file of your theme:

<?php
  function YOURTHEMENAME_links__locale_block($variables) {
    foreach($variables['links'] as $key => $lang) {
      if (isset($lang['attributes']['class']) && in_array('locale-untranslated', $lang['attributes']['class'])) {
        // Set here any page link.
        $variables['links'][$key]['href'] = '<front>';
      }
    }
    return theme_links($variables);
  }


Validation is pretty much depends on what kind of fields are they! Still I can show validation for the common fields as on user registration process.

You must be hooking into the user registration form somewhere, unless form is custom form.Assuming you are implementing hook_form_alter() to hook into user registration form.

> Step 1: Add validation handler to the user registration form.

    // Implementing hook_form_alter() to add validation handler to user registration form.
    function mymodulename_form_alter($form,$form_state,$form_id) {

    // Not sure you have to check form id of the user registration form.
      if($form_id == "user_registration") {
        $form['#validate'] = array(
          '#validate' => array('_mymodulename_registration_validate'),
        );
      }
    }

    // Write validation callback.
    function _mymodulename_registration_validate(&$form,&$form_state) {
       // Validate last name.
      if (trim($form_state['values']['last_name']) == '') {
        form_set_error('last_name', 'Last Name field is required field');
      }

      // Validate company name.
      if (trim($form_state['values']['company_name']) == '') {
        form_set_error('company_name', 'Company Name field is required field');
      }

      // Validate the e-mail address.
      if (!valid_email_address(trim($form_state['values']['email']))) {
        form_set_error('email', 'Please enter valid email address');
      }
      if (_mymodulename_registration_user_validate_mail(trim($form_state['values']['email'])) == 1) {
        form_set_error('email', 'Email address already registered');
      }
        // Validate password.
      if (trim($form_state['values']['password']) == '') {
        form_set_error('password', 'Password field is required');
      }
      if (trim($form_state['values']['password_confirm']) == '') {
        form_set_error('password_confirm', 'Repeat password field is required');
      }
      if (trim($form_state['values']['password_confirm']) != trim($form_state['values']['password'])) {
        form_set_error('password_confirm', 'Passwords do not match');
      }
    }

/**
 * Helper function to validate email adress already exists or not.
 *
 */
function _mymodulename_registration_user_validate_mail($email) {

  // used db_query_range() to check if email exists or not.
  if ((bool) db_query_range("SELECT mail FROM {users} WHERE mail = :name", 0, 1, array(':name' => $email))->fetchField()) {
    return 1;
  } return 2;
}


How to set #value to the form item from HTML data-*?

I solved this task with Drupal.behaviors in js-file

like that:

Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
        var paint_id = new Number($('.paint-order').data('pid'));
        $(context).find("[name='mymodule_product_id']").val(paint_id);

    }
}


Try to change the name of the (taxonomy) vocabulary that holds the names of the forums and groups.


Drupal 8: The proper alternative to exit(); for terminating a request

You would have been looking for drupal_exit() in the past, but this was removed in D8. It is now advised to use the appropriate HTTP Exception. See the example on the change notice:

https://www.drupal.org/node/2017339


How to create a view to display a block of referenced nodes?

When configuring the argument for the block, set it to "Provide a default argument", and configure that to use the nid of the node being viewed.


Use a the preprocess function, template_preprocess_search_result() to add a custom authored on date variable to your search-result.tpl.php template.

function MYTHEME_preprocess_search_result(&$variables) {
  //$variables['result']['node'] is the node object returned in the search results
  //the $variables['result']['node']->created property contains the authored on date
  if(isset($variables['result']['node'])) {
    $variables['created_date'] = format_date($variables['result']['node']->created, 'short');
  }
  //$created_date will be available in your search-result.tpl.php for printing
}

It's probably worth mentioning that the base template is printing out the $info variable which is the concatenation of a few vars in $info_split. Changing $info_split won't change the printed date without changing search-result.tpl.php.


How to change field attributes of Content Entity?

You don't need to uninstall the module, you can write some update hooks instead.

Since it's not possible to update the field type, you have to manually move the field values to a new field.

First create a new field for the cloned values:

$fields['formheader_clone'] = BaseFieldDefinition::create('string_long')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 1024,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Then add this update hook:

function mymodule_update_8000() {
  $entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');

  // Migrate the fields and create the new field.
  $field_definition = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Header'))
    ->setSettings([
      'max_length' => 1024,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => $weight,
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => $weight,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
  $entity_definition_update_manager->installFieldStorageDefinition('formheader_clone', 'my_entity', 'my_module', $field_definition);

  drupal_flush_all_caches();

  $entities = \Drupal::entityTypeManager()->getStorage('my_entity')->loadMultiple();
  foreach ($entities as $entity) {
    $entity->formheader_clone->value = $entity->formheader->value;
    $entity->save();
  }

  // Delete the storage definition if it was defined before.
  $storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('formheader', 'my_entity');
  if ($storage_definition) {
    $entity_definition_update_manager->uninstallFieldStorageDefinition($storage_definition);
  }
}

Now run drush updb

Now you have to update the formheader field in your custom entity, this is what it must look like:

$fields['formheader'] = BaseFieldDefinition::create('string_long')
  ->setLabel(t('Header'))
  ->setSettings([
    'max_length' => 1024,
    'text_processing' => 0,
  ])
  ->setDefaultValue('')
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'string',
    'weight' => $weight,
  ])
  ->setDisplayOptions('form', [
    'type' => 'string_textfield',
    'weight' => $weight,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Now add this update hook:

function mymodule_update_8001() {
  $entity_definition_update_manager = \Drupal::service('entity.definition_update_manager');

  $field_definition = BaseFieldDefinition::create('string_long')
    ->setLabel(t('Header'))
    ->setSettings([
      'max_length' => 1024,
      'text_processing' => 0,
    ])
    ->setDefaultValue('')
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => $weight,
    ])
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => $weight,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);
  $entity_definition_update_manager->installFieldStorageDefinition('formheader', 'my_entity', 'my_module', $field_definition);

  drupal_flush_all_caches();

  $entities = \Drupal::entityTypeManager()->getStorage('my_entity')->loadMultiple();
  foreach ($entities as $entity) {
    $entity->formheader->value = $entity->formheader_clone->value;
    $entity->save();
  }

  // Delete the storage definition if it was defined before.
  $storage_definition = $entity_definition_update_manager->getFieldStorageDefinition('formheader_clone', 'my_entity');
  if ($storage_definition) {
    $entity_definition_update_manager->uninstallFieldStorageDefinition($storage_definition);
  }
}

Now run drush updb again

It's important to do it in the correct order


Conditional field in node type depending on user profile

If you want to hide a field from particular role via a contrib module, you can try

http://drupal.org/project/field_permissions

or if you're comfortable in code, see

hook_field_access

e.g:

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    // TODO: some special access check for TRUE or FALSE in $access
    return $access;
  }
  return FALSE; // default deny
}


Why is Drupal displying missing core tables for an external DB?

If I had to guess you called db_set_active() in some code and forgot to switch back to your master drupal database, so "drupal" execution continued after you intended it to with the current database set as your alternate.

The lager_db probably has no semaphore table, but drupal's trying to call it anyways. You should switch back to drupal at the end of your custom code (or as necessary) with db_set_active(); it passes the 'default' parameter if none is given.


I'd write the db queries yourself (don't use views) so that you have full control over the output. Use a custom module to do the queries and write the html. You don't need a whole new theme, because the CSS needs to be inline for email clients to work properly.


Where is the target ISBN in feeds module?

The ISBN Field module doesn't support Feeds yet. Every module that provides a field should write their own mapper to support Feeds, as Feeds isn't able to dynamically know how to populate a field.

In the ISBN Field issue queue there is a patch available which might solve your problem: https://www.drupal.org/node/1930538


Even if you don't change anything, it's enough to click the 'Save' button on the views configuration page to make it override the code. You can simply revert the view if you are sure that you didn't change anything.


Try the module field_collection.

Add a field of type field_collection to your content type and allow multiple values. Then go to structure => Field collections and choose your field to add your date and text field.

Update: field_collection is on its way to be deprecated

Use paragraphs module instead.

Notice these meta data issues for paragraphs.


How to take care of .htaccess of all sites in multi-site setup on Linux?

You cannot have separate .htaccess files in Drupal's root directory.

You can have different rewrite condition inside your Drupal's root .htaccess file .

You can have separate .htaccess inside your sites/%mysite%/ directory which will control all the files, modules, themes, etc related to that specific site.


Well it depends on what you want to allow in your filenames.  There is a similar question here where you will find how to sanitize filenames in PHP.

From the above link, I had used following function to sanitize filenames in my one of the modules:

function mymodule_sanitize_string($string) {
    $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $string);
    $string = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
    $string = preg_replace(array('~[^0-9a-z_-]~i', '~[ ]+~'), ' ', $string);

    return trim($string, ' -');
}

If you want to sanitize user input then Drupal has many input filtering functions  e.g. check_plain(), filter_xss(), check_url() etc. There is a good tutorial on Drupal security essentials here.


Add a CSS basing on the author of the comment

If (what I'm not sure) understand your question correctly, you want to add an extra class if the comment was posted by the node author.

As explained in Bartik documentation:

 /*   - $classes: String of classes that can be used to style contextually through
  *   CSS. It can be manipulated through the variable $classes_array from
  *   preprocess functions. The default values can be one or more of the following:
  *   - comment: The current template type, i.e., "theming hook".
  *   - comment-by-anonymous: Comment by an unregistered user.
  *   - comment-by-node-author: Comment by the author of the parent node.
  */

There are already specific classes for comments posted :

by node author : .comment-by-node-author
by anonymous : .comment-by-anonymous

And you can see that in your node markup :

/* ... */


How to make an "Add more logins" similar to Stackoverflow?

So the default assumption most Drupal modules make with authentication is that they will replace the current login setup with their own.

This approach is described well in http://drupal.org/node/114774#dist-auth and can be seen in how the current openid module provided in Drupal core works.

If I understand your question correctly you want to provide a way for people to authenticate from multiple different sources and have those enabled sources show up under their user profile. I don't think there is a module that does this yet, as most of the auth modules operate in their own little bubble as described above.

After a quick look at OpenID Selector you aren't going to get a lot of mileage from there, its mainly implementing and configuring the jquery library. You are going to need to write this from scratch.

The main pieces of your module will be:

A database table that maintains the logins associated to a given
user.
Some kind of form_alter scheme for the login page to show
all of the available login options the site owner has specified
(this will replace what the individual modules currently do)
An admin page for the site owner to select from available options.

Each one of those login options will probably be provided by a separate contrib module, so you might have to alter your logic for the specifics you find in the implementation from those modules.

To me its an ambitious undertaking for a configurable module that you plan to release, but if you go the quick and dirty highly customized / hard coded route for a single site it shouldn't take you too long.

Other places to look for inspiration on how auth modules operate in Drupal and possible sources you might want to include are FBOauth and Twitter.


How to count the number of nodes with a certain taxonomy term, based on a list of nids?

Mmm i dont think drupal 7 views is up to this perhaps this work around may help
create a custom module and put

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = [];
  $blocks['my_block'] = [
    'info' => t('My Medals'),
  ];
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_block' :
      $block['content'] = my_block_view();
      break;
  }
  return $block;
}

function my_block_view() {
  global $user;
  $uid = $user->uid;

  $result = db_query('SELECT * FROM {node} WHERE uid = :uid AND type = :type', [
   ':uid' => $uid,
   ':type' => 'post'
  ]);
  $node_ids = [];
  foreach ($result as $row) {
    $node_ids[] = $row->nid;
  }
  $output = '';
  $gold = [];
  $silver = [];
  $bron = [];
  if (count($node_ids) != 0) {
    foreach ($node_ids as $nid) {
      $node = node_load($nid);
      $tid = $node->field_term['und'][0]['tid'];
      switch($tid) {
        case 1;
          $gold[] = $nid;
        break;
        case 2;
          $silver[] = $nid;
        break;
        case 3;
          $bron[] = $nid;
        break;
        default;
        break;
      }
    }
  }
// bad practice but quick win.
  $output = 'GOLD ' . count($gold) . ' Silver ' . count($silver) . ' Bronze ' . count($bron);
  $block = [
    '#type' => 'markup',
    '#markup' => $output,
  ];
  return $block;
}

The above will create a custom block then you have to place the block on the user and change the   "global $user; $uid"  to fit your need.


$params = Url::fromUri("internal:" . $source_uri)->getRouteParameters();
$entity_type = key($params);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);


Token replacement by its value before indexing in apachesolr

you can use hook_apachesolr_index_document_build() function to override node data index in apache solr


DrupalGap is typically used to consume Views as JSON results. It can then use the JSON to decide how to display the HTML inside the app.

Check out this example for creating a page in your App that will fetch and display Views content:

http://www.drupalgap.org/node/219

Out of the box, it easily lets you create lists and tables of your Views data.


Sublimetext 2 does not recognize .module file as php file

When you have the .module file open, go to:

View -> Syntax -> Open all with current extension as

and select PHP. This will then default all .module files to use PHP syntax.


How to add a path filter to views 3 in Drupal 7?

Try the Views URL alias module.

The 'Views URL alias' module allows Views to be filtered by path aliases.
This module is useful if your website uses heirachical paths. It allows you to filter and sort a view by URL aliases. When combined with the Views bulk operation (VBO) module you can apply operations to a specific section of your website based on a URL alias.

Note that Currently, only node aliases are supported.


You might be interested in the drushify project, which will create a Drush commandfile for you, from a template.  You can give it the name of a module, and run it from a Drupal site to make a Drush command for a module, or just give it an arbitrary name and run it from outside any Drupal site, and it will create a global Drush command.

From there, you only need to go through and fill in the parts of the template that it made for you.  You may delete any of the optional hooks that you don't need -- which is usually most of them.


Show default image when no uploaded image

This can be done when you edit the content type > your image field > fieldsettings. There you can upload a default image. This image should show up in views.


Can I use the Search API module and its facets without a server running Java?

Try to use search_api_db it support facets and some other features.


Modifying Drupal core (search module, image module)

I'm not sure how the second one is Image module-specific, but you would override that maxlength like so:

function hook_form_[content-type]_node_form_alter(&$form, &$form_state, $form_id) {
    $form['title']['#maxlength'] = 500;
}

... where 'hook' is replaced with the name of your custom module, and [content-type] is the machine name of your content type.

The API function is hook_form_FORM_ID_alter()

For the search form theming, you probably want something like template_preprocess_search_results() in your template.php of your custom theme, and/or adding a custom search result template to the theme's templates folder.

Oh, and in case it needs saying again,

DON'T HACK CORE


Convert Drupal error message to JavaScript alert

It think the better messages module is for you.


How to have a drupal module respond on node creation

All credits to Clive, but here is the answer.

You need to write a custom module: Simply write a MYMODULE_node_insert($node) function containing the code you want to execute. Drupal will call that function every time a node is created (when the module is enabled).

If you are changing the code of a module that is already enabled, you should clear Drupal caches, as otherwise Drupal will not notice the module contains a new hook implementation. This can be achieved by disabling the module before editing it, and re-enabling it after the code has been changed.


Drupal 8 dropping session variables on password reset. Gives 403 Access Denied

This is an issue with symfony/http-foundation v3.4.24. See https://www.drupal.org/project/drupal/issues/3045844.


how to combine profiles and content types in a view

With Content-type view, you can use the "relationship" feature in Views and have access to the profile fields of the author of a certain node that is listed in the view. The same is valid for the Filters of that view.

To do so, edit your view and expand the "Advanced" settings section on the right. Then click on Relationships -> Add and add the relationship "Content: Author".

Hope that helps.


How to extract query placeholders for debug purposes?

This can be done using arguments:

echo (string)$query;
var_dump($query->arguments());

This simple code will give you both query and arguments, for simple debugging.


Specify a single node to load a stylesheet on

There are several very good solutions, please see the question "Any way to add CSS for a single page/node?"


How can I get the order ID from Commerce (using Rules)?

As you have mentioned, you want to act on completion of the order, so there is a hook of drupal_commerce, which get called on completion..

hook_commerce_checkout_complete($order)

I have used this hook for some action at the order completion in my custom module. If you call this hook in your custom module then $order variable will have all the information related to order. Check this in your custom module --

function MYMODULE_commerce_checkout_complete($order){
  dpm($order);
}


Translate custom string from programatically defined block

In order to make strings translation possible you need to pass it through the t function.

$block['content'] = t('Hello');


Ok, I kind of found my way through it eventually. Still pretty amazing the amount of possibilities. Makes me dizzy.


D7 to D8 users migration processes 0 items

Ok I tried it on a new site install and the code works and migrates users perfectly. All I can think of is that db got corrupted after running migration and rolling back a number of times.


How to make a content type a Ubercart product

Go to admin/store/products/classes.

From there you'll be able to assign a product class to an existing content type, after which you should see the Ubercart-specific settings on the content type edit form.


Exception handling for incorrect content type for request in custom REST API plugin

For the record, here is how I managed to solve the issue. This is a workaround but it allows for graceful degradation.

I created an event subscriber that extends
HttpExceptionSubscriberBase
There is an onException method that retrieves the event that generated the exception
From the event, we can get the request type and handle the exception.
By overriding the method we can handle this exception

class MyClassService extends HttpExceptionSubscriberBase {
public function onException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();

    // Make the exception available for example when rendering a block.
    $request = $event->getRequest();
    $request->attributes->set('exception', $exception);

    $handled_formats = $this->getHandledFormats();
    $format = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, $request->getRequestFormat());
    if ($exception instanceof HttpExceptionInterface && (empty($handled_formats) || in_array($format, $handled_formats))) {
      $method = 'on' . $exception->getStatusCode();
      // Keep just the leading number of the status code to produce either a
      // on400 or a 500 method callback.
      $method_fallback = 'on' . substr($exception->getStatusCode(), 0, 1) . 'xx';
      // We want to allow the method to be called and still not set a response
      // if it has additional filtering logic to determine when it will apply.
      // It is therefore the method's responsibility to set the response on the
      // event if appropriate.
      if (method_exists($this, $method)) {
        $this->$method($event);
      }
      elseif (method_exists($this, $method_fallback)) {
        $this->$method_fallback($event);
      }
    }
    // We are now assuming that this a special RuntimeException
    // where the Content-type header is not set to json or missing.
    if ('json' != $request->getContentType()) {
      if (method_exists($this, 'on415')) {
        $this->on415($event);
      }
    }
  }

public function on415(GetResponseForExceptionEvent $event) {
    $method_exception = [];
    $method_exception['message'] = 'Missing or unsupported Content-Type request header.';
    $response = new JsonResponse($method_exception, 415);
    $event->setResponse($response);
}


Check out item 2 on this page on setting up sites in Aegir.

  Login to your DNS control panel at your domain registrar, or wherever
  your nameservers are, and setup the DNS for the domain name to point
  at your Aegir server. It's worth including a wildcard record - ie an
  'A' record for '*' to resolve to your aegir server - then you can
  easily setup new sites on subdomains without having to ever setup DNS
  again!

This video also looks pretty neat, not sure how much it'll help though.


You are passing 'node' as the $hook value, although your data is for a taxonomy term rather than a node. Trying using the hook 'taxonomy_term' instead of 'node'. I'm not sure what the proper structure for the $variables array is, but if you have the full term object, I would try just passing $term as the second parameter.

documentation for theme()
http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7

documentation for theme_taxonomy_term()
http://api.drupal.org/api/drupal/developer--theme.php/function/theme_taxonomy_term/7


How to dynamically group content in a views listing

Try this out.

Add the taxonomy term (or entity) reference field to your output, exclude it from rendering, and configure the format settings to group on this field.

Add a relationship to you view based on the term (or entity) reference field you are using to reference the taxonomy terms. With this relationship, you can now add a sort field using the taxonomy term's weight. When you click to add a sort field, filter the options to taxonomy term using the drop-down select to the right of the search field in the add sort dialog. Once filtered, you will now see the taxonomy term weight.

Adding this to your sort, will allow you to sort the view results based on the node's referenced taxonomy term's weight within the taxonomy vocabulary. You could also sort on the term itself, if your term names will include numbers like, "1. Chapter 1" and "2. Chapter 2", etc.

Jason.


What is the difference between _form_validate vs form_validate?

You're totally correct, Drupal's coding standards denote anything with a _ prefix is seen as a pseudo-'private' function. As such the _form_validate() function was never meant to be called directly. Unless you really need to use it, and you're absolutely positive there's no other way to accomplish what you want, I wouldn't advise using it.

In fact only one function in the whole core system calls _form_validate(): drupal_validate_form(). It would stand to reason that you should be using this function instead (being that it's not marked as a private function).

These are the functions that Drupal uses internally to validate a managed form, so if you're using the Form API correctly you should never need to call them. Adding validate handlers to a form to validate individual elements is the correct way to do things.

Just to clear up a wee bit of terminology as well, hook_validate() has nothing to do with the form API as such; it's used by node-providing modules to validate nodes before saving. The validation handlers that you add to forms (with custom forms, or through hook_form_alter(), don't have a particular 'Drupal name' that I'm aware of.

Also, you don't actually even need to use the standard named _validate function if you don't want to...you can add a function with any name as a form validate handler:

$form['#validate'][] = 'my_strangely_named_function';

Drupal just looks for FORMNAME_validate() by default, and runs it if it exists.


You need to print image src like this:

<?php print file_create_url($uri); ?>

Just change $uri with uri of your image ($fields['field_news_image']...)

Take a look on function file_create_url as well.


How to run a drupal application in github?

You can not execute Drupal in Github, just because Drupal requires a server running PHP, which isn't supported by github.

  Github Pages is not a full-featured web host. It will not execute PHP, or any other arbitrary code.
  Source

You could convert your Drupal site into a static site and upload it on github, but the website would not be dynamic anymore. If you decide to do this, you could host it using Github pages, but you would not be executing Drupal; instead, you would be going to show a static version of your Drupal website.

If you wish to add a static version of your website for Drupal 7, you can look at the Static Generator module. If you are running Drupal 8, you can use wget --mirror http://example.com and this will provide copy of your site's HTML.


Webform submission via URL supplied data

Webform MySQL Views

  These views may be useful when you need to access this data from an
  external application in an automated fashion without exporting,
  importing, or the use of a web-based API.

View will be automatically updated whenever you add, remove, or reorder the components for that Webform.


The Database Logging (dblog) is responsible for logging to the Watchdog table. Uninstall the module and it will remove the table and logging to it.


Taxonomy terms won't arrange themselves by ID but will work alphabetically instead

The order in which you enter the taxonomy terms is not important to how they are displayed. Drupal defaults to alphabetic ordering, but you can adjust this order manually.

Go to Content management > Taxonomy > Your vocabulary: List terms (via admin/content/taxonomy/list) and reorder the terms by dragging the handle on the left. This is also the order Hierarchical Select uses.

You can also try out Taxonomy Manager to see if this provides you with a better interface for reordering large numbers of terms.


Drupal 8: Node preview when using Page Manager

Not ouf the box because page_manager is about routes, and node preview is a completely different route than viewing a node.

Something like Display suite and probably also Panelizer (never really used it myself) whould probably work there though.

That said, it should be possible to build something too with Page Manager too by creating a second page (with a duplicated page variant(s) that you need to keep in sync somehow) that overides the preview route, but you also need to somehow write a context provider that loads the node based on the passed tempstore argument and also a write a block that replicates the UI elements for selecting the view mode and going back to edit


You're accepting $form_state by reference, so the changes you make will definitely persist onto the incoming variable when your function loses scope. The variable/calling function doesn't control whether it's a reference here, your function signature does. The FAPI doesn't use the old pass-by-reference style (e.g. foo(&$bar), which has been deprecated and removed), so you're in control of that.

Chances are the webform submit handlers are running before yours, so the changes you make aren't actually used by anything, despite being correctly added to the array.

To get around it, simply use a validate handler instead. This will run before the form submission, and changes you make to $form_state['values'] will be available to the webform's submit handlers (as well as your own if you need to do extra processing).

I think you can probably use exactly the same code as in your submit handler.


The Paragraphs Grid module provides this functionality.

  With Paragraphs Grid, you can display multiple paragraph entities in a
  grid. Supports Out-Of-The-Box Bootstrap 3.0 and 4.0 and CSS grid
  from MDC (Material Design).


Don't use the low-level config, that doesn't trigger the necessary API calls.

Use FieldConfig::create() and FieldStorageConfig::create()


How to move drupal into a subdirectory so non-drupal content works in the original folder?

If your non-drupal files are just a few and are static content (just plain HTML files or similar) you can create symbolic links in the root Drupal foolder that point to your non-drupal files.

Webserver (Apache at least) will serve those files if the URL points to them, instead of call index.php with the URL rewriten into params.

This way if you accidentally delete root Drupal directory (for example, using an automatic core update) you only have to put the simbolic links again, not all your non-drupal files.


You could use Views Search and build a views with only the title of nodes as an exposed filter, then this module convert your exposed filter in a search option.


Check out the variety of cron modules that set intervals, like Elysia cron.

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


Determining content access by role for viewing content?

To further complete the list of content access modules you mentioned, i.e.:

  There does not seem to be a solid solution for Drupal 8 out there. Content Access is unfinished, Permissions by Term is too restrictive, and Access by Entity currently does not work.

I recommend you have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types).

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Module integrations

The Group module integrates with various other (popular) modules, such as Views, Rules, etc. These integrations are more or less out-of-the box (not dozens of extra modules needed to make those integrations work). Simply because everything is entity based.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Podcast "Using the Group module as an Alternative to Organic Groups in Drupal 7 and 8".

PS: this answer applies to either D7 or D8.


How would one upload a list of users via a .csv file and have them blocked by default?

I suggest setting up a Migration using Migrate CSV. When Feeds is ready, it should be possible, but it looks incomplete at the time of posting.

Using the migrate code that you implement, set the accounts as blocked by calling $user->block() per User import.

Block any anonymous user registrations, this will make new user additions possible only by admins.

In place of the user reg form, create a new custom form using Webform module or core Contact module. You can replicate the fields from the reg form of use to you there. On form submission, using a custom module including a hook_form_FORM_ID_alter, do a check on the submitted form for email address and verify if it matches, then call $user->activate() to unblock the user account.

Or if Rules module provides you the necessary settings through the UI, you could try the email address check using that, but this module maybe incomplete for this type of check at present.


How can I conditionally alter search API relevance score?

Since everyone was telling me to solve this during the query, I decided to have another look at this approach. My main issue was not being able to order by the flagged status, which was eventually solved with an expression.

In the end I managed to get what I wanted with an implementation of hook_search_api_db_query_alter.

function mymodule_search_api_db_query_alter(SelectQueryInterface &$db_query, SearchApiQueryInterface $query) {
  global $user;
  $uid = $user->uid;

  // Left join indexed flag table into search index.
  $db_query->leftJoin('search_api_db_product_index_field_my_flag_field', 'flag', 'flag.item_id = t.item_id');
  // Set a value of 1 for entities flagged by the given uid, 0 otherwise.
  $alias = $db_query->addExpression('CASE WHEN flag.value = :uid THEN 1 ELSE 0 END', 'flagged', array(':uid' => $uid));
  // Order by the flagged value (1 or 0), highest first.
  $db_query->orderBy($alias, 'DESC');
}


Issue with Registration codes module in Voucher mode, trying to fix

This is more of an advice than a clean solution to the problem: hack the module and apply the patch if it works for you without interfering with other modules.

As you said, the module isn't maintained well and it is not updated recently (last commit was almost a year ago). If you don't have enough time to go over everything yourself, it is better to just fork it than hope that the maintainer will fix it.

Create a new folder under "sites/all/modules" called "fork" and move the module there. This will make sense later on for you or anybody else working on the site.


TypeError: $.ui and $element.dialog is undefined

Thank you everyone for helping.
I informed of the senior development of your suggestions. He was able to find the issue. Font Awesome module was installed incorrectly, he also updated to the latest core. We've uninstall Font Awesome and migrated to using Font Awesome CDN.


Set up two content types, "Hotel" and "Country" and use the Entity References module to define a relationship between the two. Then configure it to display a "Rendered entity" formatter, that renders the references entity using a configurable view mode


Seven subtheme not inheriting correct block structure

You can provide custom block configurations in config/install as with a module. As soon as there is at least one block, Drupal will not add any additional blocks, if there are none, it will copy those from the default theme.


Adding an exposed view filter inserts the following (sample) code into the view output:

        ...

        <form action="..." accept-charset="UTF-8" method="get" id="views-exposed-form-...">

                     ...

                           <select name="tid" class="form-select" id="edit-tid" >
                              <option value="All">...</option>...
                           </select>

                    <input type="submit" id="edit-submit-..." class="form-submit" />
                 ...

It is not clear, though, why you can't find out the same by simply creating a view, exposing its filter and looking up the source code. Perhaps you could explain your question better?


Update the number of comments without refreshing the cache

Long story short, you need ESI or AJAX to do what you want.

This will help you get there, but I don't believe any of the below modules will do exactly what you're looking for.
http://drupal.org/project/esi
http://drupal.org/project/ajaxblocks


Guard/LiveReload/Sass/Compass CSS Caching Issue

Ensure that you have scss files in your LiveReload "files to watch" option, this will ensure your changes apply from node to node, without having to manually refresh just because you changed pages. Not sure of any side effects as of yet.


Why does boost turn off standard caching?

It's the System module that disables the aggressive caching when there is a module that implement hook_boot() or hook_exit().

The explanation is reported in the description text that appears in the form field to choose the type of caching.

  The normal cache mode is suitable for most sites and does not cause any side effects. The aggressive cache mode causes Drupal to skip the loading (boot) and unloading (exit) of enabled modules when serving a cached page. This results in an additional performance boost but can cause unwanted side effects.

The code that executes that verify is the following one (system_performance_settings()):

  $problem_modules = array_unique(array_merge(module_implements('boot'), module_implements('exit')));
  sort($problem_modules);

  if (count($problem_modules) > 0) {
    $description .= '
' . t('The following enabled modules are incompatible with aggressive mode caching and will not function properly: %modules', array('%modules' => implode(', ', $problem_modules))) . '.
';
  }

Boost only changes the content of a Drupal variable with variable_set('cache', CACHE_DISABLED); as it does it in its implementation of hook_enable(), it will disable the normal caching all times it is enabled. The reason for disabling it is reported in a comment before the code that changes that variable: "Forcibly disable Drupal's built-in SQL caching to prevent any conflicts of interest."
That means the module disables it just to avoid that both Drupal and Boost use their own cache, with the result of obtaining data from a cache that is then replaced with the content of another cache.

It could have been a better idea to hide the cache selector when Boost is enabled. In that way, users could not enable the cache that Boost disables when it is enabled.

As side note, hook_boot() has been removed from Drupal 8, and hook_exit() is probably going to be removed from Drupal 8 too. What I reported here for Drupal 6/7 will not be anymore true for Drupal 8.


How to add image field in a custom module form?

The default_value attribute accept an array in case of managed_file:

  $form['my_file'] = [
      '#type' => 'managed_file',
      '#title' => 'my file',
      '#name' => 'my_custom_file',
      '#description' => $this->t('my file description'),
      '#default_value' => [$config->get('my_file')],
      '#upload_location' => 'public://'
    ];

In The submit function you are using a field name different from the declared one in the buildForm().

The value of a managed_file should be an array even when the field is not multiple:

$form_state->getValue('default_press_release_image')[0];


How do I use Drush correctly to restore a site via the arr command?

settings.php is just an executable php file, so it seems on the surface that there should be no reason for you to do the editing step described above as long as

a) you have not inserted anything in your settings.php file (like a 'return' statement) that halts execution before the end

and

b) the database information that Drush writes at the end of settings.php is the same as the database information you hand-edit into the normal location.

If you are doing the editing information because the database information on your testing server is DIFFERENT than the database information on your production server, then you would be better off using sql-sync to migrate your database from one to the other, and migrate your code with either drush rsync or a version control system such as git.  By default, drush rsync will not transfer your settings.php file, so you can customize it in each location and not have to worry about it being overwritten.  If you use a vcs, you could exclude settings.php e.g. by using a .gitignore file.

Finally, I should add that it is only viable to use sql-sync or archive-dump/restore to move a whole site from testing to production BEFORE you have user generated content. If you ever have users who create accounts, add content, post comments, etc., copying the whole site will overwrite all of that information.  Usually, folks copy the database from live to test only, and copy only code from test to live.  To move configuration, look into the features module, or drush ctools export bonus.

Update: archive-dump / archive-restore does support changing database specs, and seems to be working correctly per your use case described above. Note, however, that you said in your updated text that the two db records are the same, but in fact they have different database names. This, I expect, is as it should be; I further presume that the database info archive-restore is writing to the end of settings.php matches the info you pass in on the command line.


Display random value from multi-value field in Views

Re-querying with Views for information you already have is excessive. I think a better option is to use something like
 Single Image Formatter which can display a random value from a multivalue image field.


How can I hide exposed filter control if the filter is not applicable to existing views results?

You have to create a small module or add a function into template.php where you use a one of the hook alter functions. You test your view results for a given set, and if you at that result don't need the filter you unset it. Probably the best hook is: hook_views_pre_render.

"https://api.drupal.org/api/views/views.api.php/group/views_hooks/7"

Check out the comments on the hook_views_pre_render function to get an idea of how to use it. Hope this gets you on your feet.


Right way to start with a Bootstrap subtheme?

First of all, there is a guide to begin with subtheming with Bootstrap here. And I recommand you to download the starter kit to get ready-to-use subtheme.

1) and 2)
To create a subtheme, you don't have to edit any files in your base theme. Just create a custom theme, in sites/all/themes/, just next your bootstrap folder, and declare the yourtheme.info file like this:

name = yourtheme
description = Custom Bootstrap subtheme
core = 7.x
base theme = bootstrap
stylesheets[all][] = css/style.css

It is going to make the heritance of all your bootstrap files automatically.

You can create a new empty css file, in yourtheme/css/style.css, and customize.

You can also create multiple css files, as you said, but you have to declare it in the .info file aswell.

3) LESS is supported by Bootstrap. You just have to follow the guide I told you and have a local LESS compiler to generate CSS.

======

BIG EDIT:

======

How to set up a new Bootstrap subtheme

A) Download Bootstrap project (7.3 is fine to me). Place the bootstrap folder in sites/all/themes/.

B) Download jQuery Update project, which is required by Bootstrap. Go to yoursite/admin/config/development/jquery_update and set the default jQuery version to 1.9.

C) In your bootstrap folder, you're gonna find bootstrap_subtheme folder. Move it to sites/all/themes/ and name it banana (let's suppose your custom theme is called Banana). So you have bootstrap and banana folders at the same level.

D) In banana, rename the bootstrap_subtheme.info.starterkit file to banana.info. And edit its content like this:

name = Banana, a Bootstrap Sub-theme
description = A Bootstrap Sub-theme called Banana.
core = 7.x
base theme = bootstrap

E) Now you have a pretty new Banana theme, inheriting all from Bootstrap theme, and that you can activate in yoursite/admin/appearance/.

F) If you want to try a customization, go to sites/all/themes/banana/css and make a little change to style.css (see, it is not 6400+ lines ;-)). Refresh your site and see if it is applied.

G) If you want to work with LESS, you have to set up a local LESS compiler on your computer. This one seems to be simple to install and configure. Personaly, I use SASS and Ruby Gem to compile, so I cannot give your further information about another compiler here. Maybe someone will.

H) Once you're ready with your compiler, you just need to make your edit in sites/all/themes/banana/less/ folder. All the .less files that appear here are included in style.less. This is the one you have to compile (only this one) to generate css/style.css. Bootstrap gives you 3 empty files where you can put your code, content.less, footer.less, header.less. You can use them or just create new ones (don't forget to import them in style.less if you add new files).

I) Make some changes, compile and refresh your site. See if it is applied.

I wish you good luck (and a merry Christmas ^^)


I see you have added views tag views-filters, so, I think, you don't mind to list your content with Views.
If your field field_year is integer it is really easy to sort your content:

Some notes:

If you need block, just create Block display in Views. New block will be available on admin/structure/block page.
Add fields you want. Here I'm showing only title as a link to the original piece of content.
Remove all sorts and add your own by clicking on the Add button. It's very easy to find your field by it's name or machine name.

Result:

Yes, active class is added automatically.
Views module has tons of settings. To learn more please take a look at “Taming the Beast: Learn Views with NodeOne” series.


Displaying a field of an entitiy reference

If you want to do it only in code, do a node_load($node->field_related_page['und']['0']['target_id']. If you want a view, use a relationship and show gallery field with the relationship.


How do I ensure that a 'no results' view block is still refreshed by Block Refresh

Set the 'No Results' behavior to 'Global: result summery' and add some text to give as a response.  This will ensure that the view is rendered and active, even if there are no results.

This will allow block refresh to add new content as it become available.


Installed Revisioning Module, how do you make it default to create new revision?

You can alter the node edit form following the Revisioning's implementation.

/**
 * Implements hook_form_alter().
 */
function myModule_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['#node_edit_form'])) {
    if (isset($form['revision_information']['revision_operation'])) {
      $form['revision_information']['revision_operation']['#default_value'] = REVISIONING_NEW_REVISION_NO_MODERATION;
    }
  }
}

/**
 * Implements HOOK_module_implements_alter().
 *
 * Ensure our hook runs after revisioning_form_alter().
 */
function myModule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['myModule'];
    unset($implementations['myModule']);
    $implementations['myModule'] = $group;
  }
}


You can use template_preprocess_views_view_fields function in order to do it.


How to reload Google chart on ajax submit?

The issue is already created on drupal.org for this and you can try  the code from the below mentioned url:
Ajax load of chart


How to show "Add to compare" button in views using "dynamic properties" module in d7?

It will not support by views at the moment, see the Issues for Dynamic properties.

Check this also http://drupal.org/node/1852656


How to pass an argument to be used in the view called by rules

I found 2 working prototypes.
Each require a taxonomy-list "field of interest" in both user and node.

Users can select multiple items, according to their fields of interest.
When registering a new post, the posting user can indicate in which field of interest (one) this post is matching.

ONE

using 5 views (one for each term) to select the email adresses of users interested in this "field of interest".
In the action I use "switch case" (from conditional_rules) to select the view corresponding to taxonomy-term of the new node

TWO

fetch entity (user) by taxonomy term(field of interest)

loop thru the list of users

THREE

Finally I chose to make 5 views and 5 reaction rules, each rule having as condition a particular value of the taxonomie term in the new node en using the relevant view to select the users. No switch case needed.


How to let selected role submit multiple data for 1 node?

The Field Collection module will let you do a couple of helpful things here:

you can group a set of fields, ie store name, price so that this data is part of the same entity
you can embed links to add/edit/delete field collections right on the node.

Embedding the form in the node is trickier, but doable, and Field Collection will get you off to a good start.

Once the Field Collection module is enabled, create a field of the type field collection on your content type. Set the widget to 'embedded'. Then go and add individual fields to your content type.

There is basic documentation at https://www.drupal.org/node/1353926 and a video tutorial at https://www.youtube.com/watch?v=1V1ofpgUw-Y.


Comment Author details are not displayed when comment is submitted by REST API

Just adding the solution here.

To get or determine a specific REST parameters, add these fields in your view or content manage fields, then try to access it by running the GET method command. It will show up all parameters of the content/node you need.

Then you can use POST method when planning to update or creating node of your need.


D8 Prepopulate webform full_address value field from url?

Thru trial and error I made the composite element full_address prepopulate using
&full_address[value]= {{ field_address }} as the receiving field/element name.
putting the brackets in made it work. Ahhh...


Is it possible to run a Drupal 7 site without jQuery?

jQuery is part of Drupal core - and because of this, you can't tell WHAT contrib modules are going to be using it.  Well, you can, but it'd involve checking any included scripts of any module. Also, you wouldn't remove poll.module or blog.module just for server side performance if you're not using them - I would suggest the same applies to jQuery.

I don't think removing jQuery is an option at all realistically, it's not worth the hassle of even trying.

The following, however, are MUCH better options.

For starters, get your hands on the jQuery Update module if you're not using it already. One of the best things you could do to improve jQuery performance is use the most up to date version of the library possible.

Next, try Boost:.

  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic.

or Varnish if you are on a dedicated hosting plan and have the resources to set it up (Drupal module here).

Serving static HTML pages will take substantially less time, than serving a full dynamic page.

Lastly, if it's a REALLY simple site, evaluate whether or not you even NEED Drupal?

Could you perhaps use a Drupal back-end to manage your content and combine it with the Services module to supply your content to a more performance focused site with a lightweight framework such as Laravel?  I've run into situations before where I've used Drupal because "IT'S WHAT I KNOW DAMMIT", where I could realistically have used a much lighter framework and removed a lot of overhead.

EDIT

I forgot to mention the performance tag.  Check out other questions tagged with performance and there will be a plethora of people who might have similar front-end performance issues/ideas!


how to remove password confirmation field in user registration form?

The following code works for me in Drupal 7.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#title'] = 'Password';
}

Please note that the user registration form and the user profile form both have password confirmation fields and are not the same form.  You will need to alter both forms if you wish to remove all password confirmation fields.


How to rename the views tabs in user accounts

The Tab Tamer module gives you a user interface to do that.


How to use Rules to transform upvotes and downvotes towards User Points?

in these pages you can find what you need.

User Points This is a module

User Points Contributed modules more modules!

Choose the one that fits in your website.


First I assume you have drush 8 since that is required for both D7 and D8.  It's also the default on drush.org.

The best way to deal with multiple Drupal sites is via Drush Aliases.

Basically you create a .drush directory in your home directory and create a aliases.drushrc.php file in it.  For each site, have an entry with the minimum information of:

$aliases['d7'] = array (
  'uri' => 'yoursite.dev',
  'root' => '/path/to/drupal/root',
):

There are a lot more options but those are the required ones for local sites.

To use them, run drush commands using the @alias option.  E.g.:

drush @d7 status

This will let you switch between multiple local sites.


$connection doesn't exist in the context of hello(). You need to use $this->connection if you're wanting to use the Connection that's built in your object.


This depends on your template suggestions.

Open template.php in your theme folder, and look for a function named YOURTHEME_preprocess_page, if it does not exist, create it like:

function YOURTHEMENAME_preprocess_page(&$vars)
{
    debug($vars['theme_hook_suggestions']);
}

And see what suggestions (and in what order) you have.

EDIT: this is a preprocess function I used in a theme of mine, in theme's template.php:

/**
 * Implementation of hook_preprocess_page()
 * @param $vars
 */
function THEMENAME_preprocess_page(&$vars){
    // I like to store templates in different folders inside the theme dir
    foreach($vars['theme_hook_suggestions'] AS $i => $ths){
        $vars['theme_hook_suggestions'][$i] = 'pages/' . $ths;
    }
}
/**/

In your case, simply do debug($vars, 'preprocess page vars!'); to see what variables you have a dispostion (please note: flush the cache after editing/creating this kind of function, and the output of debug($vars) can be very big!) and then add your template suggestion.

Maybe this can help: theming d7 webforms


How to override Breadcrumb theme template?

As mentioned by @Clive, breadcrumbs are not entities so I was not be able to get it done by adding a mytheme_theme_suggestions_breadcrumb_alter. Instead to solve the problem I had to do the following. On top of this, I ended up downloading and enabling Easy Breadcrumb to further modify the Breadcrumb

Copy the breadcrumb.html.twig file from the Classy theme into my mytheme directory
Clear cache
make any edits into the sites/themes/custom/mytheme/templates/navigation/breadcrumb.html.twig file
save and clear cache (if necessary)


Trouble redirecting users after implementing LDAP

I was not able to find a hook that gave me what I wanted, but as a sort-of work around, I created an event subscriber that uses checkAuthStatus() to check the user and path, and redirect when necessary.

This is sub-optimal, because this event fires on every page load, as far as I can tell, but at least we got our feature.


Authcache settings for blocks or views in panels

Note that each fragment which is loaded from the server results in an additional request. Hence it is beneficial to minimize the amount of fragments and it follows that you should pack all your personalized panes into one request if possible.

Note also that you only can load panels/panes if you place them with page manager. Neither Panelizer nor Mini Panels are supported at the moment (see these issues)

You should not nest authcache fragments. If you do then, the outer most wins. Authcache will not add any fragment placeholders inside fragments loaded via Ajax/ESI.


Paragraphs: referenced entity error on save

User 21 was deleted, but 21 was still stored as the value in the uid column of the paragraphs tables. Changing the uid to that of an existing user (23) solved the problem:

UPDATE paragraphs_item_field_data SET uid = 23 WHERE uid = 21;
UPDATE paragraphs_item_revision SET revision_uid = 23 WHERE revision_uid = 21;
UPDATE paragraphs_item_revision_field_data SET uid = 23 WHERE uid = 21;

Run SQL, empty cache, reload edit page.

Note: other tables also contain the uid 21, but without a (noticeable) adverse effect.

UPDATE file_managed SET uid = 23 where uid = 21;
UPDATE node_field_data SET uid = 23 where uid = 21;
UPDATE node_field_revision SET uid = 23 where uid = 21;
UPDATE node_revision SET revision_uid = 23 where revision_uid = 21;

And two from contrib:

UPDATE crop_revision SET revision_uid = 23 where revision_uid = 21;
UPDATE redirect SET uid = 23 where uid = 21;


How to create a Sub-theme based on a Zen Sub-theme

It shouldn't be too hard ... I have a live site running a sub-theme of an AdaptiveTheme sub-theme (Sky). The only thing you have to is create your theme folder and copy the existing zen-sub-theme.info to your own zen-sub-sub-theme.info and rename the base theme value to the zen-sub-theme.

See this page, some magic inheritence occurs with CSS if you define 1 stylesheet for your theme:
http://drupal.org/node/225125

By creating your own .info file you are defining regions / ccs files and theme specific variables. You will also probably want to copy the zen-sub-theme's template.php file as well (renaming the functions to your themes name).


Translating the months in the archive view

Well, if you have tried all those options, what if you try to replace the respective values from a common view template, using for example, preg_replace() PHP functions, to change this values?

for example: Here is the part of views-view-unformatted.tpl.php when each result is printed:

<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes[$id]; ?>">
    <?php print $row; ?>
  </div>
<?php endforeach; ?>

you can use a custom views-view-unformatted.tpl.php specific to your view, and use preg_replace() to detect and replace any specific term in $row, according terms that you want. for example

<?php
$string = $row;
$patterns = array();
$patterns[0] = '/jan/';
$patterns[1] = '/feb/';
$patterns[2] = '/mar/';
$replacements = array();
$replacements[2] = 'othermar';
$replacements[1] = 'otherfeb';
$replacements[0] = 'otherjan';
echo preg_replace($patterns, $replacements, $string);
?>

see preg_replace() to get more details. I guess that you can use Devel module to see impact of this way against your site performance.

I hope information be useful.


Last-Modified header is changed, even if the resource hasn't changed

The code that is causing the issues you're describing lives in drupal_serve_page_from_cache(). Instead of using a hash of the contents of the cache; Drupal uses the $cache->created value. Looking over everything hacking core is the only option at the moment. I'll see if there can be a way of not hacking core if one has total control of the cache backend; if there is a way look for an update inside of https://www.drupal.org/project/apdqc


Views Exposed Filter Form Submit handler

The views exposed form will be submitted every time you view it. If you check the render_exposed_form() you can see they are setting the $form_state['always_process'] => TRUE, this means that the form will be submitted always while processing it. And this is understanable because submitting the exposed form and passing the argument in $GET are the same in view.


Here is an "educated" guess:

Your site is configured so that anonymous users are NOT allowed (= do not have the permission) to delete nodes.
Cron (always) runs with user anonymous.

Up to you to confirm if bullet "1." applies, but rest assured that bullet "2." is true (in any Drupal 7 site). So if "1." indeed applies, the answer to your question (= "What am I missing") is that to get this to work you need to grant delete of nodes to anonymous users. I bet it is not going to be what you want to do (I wouldn't ...), but trust me, that is what you're missing.

And BTW, it must be that the userid you used to "successfully manually delete the nodes with VBO" does have the required permission.

To verify if my guess makes sense: (temporary) grant access to the VBO view to anonymous users, logout from your site, and repeat your manual attempt to delete the nodes with that VBO view again (as anonymous user). I bet it will fail with some sort of permission issue. Turn on Rules debugging (within Rules sessings) to get more details about that via the Rules logging messages shown near the top of your screen).


how to pass variables from one module to another module?

As alternative, you can use also drupal_static() if the value you pass from a module to the other doesn't need to be saved past the page request. When both the modules pass to drupal_static() the same value for the first parameter, they get the same static value.

In the case you use drupal_static(), you must be sure the module that is setting the static variable is executed before the module that reads that value.


Drupal's annotation system is based on the Doctrine PHP library, and not on Symfony like the rest of Drupal.

Doctrine uses a global annotation registry to map classes to files (rather than an autoloader). This page contains the list of classes in that registry.

This issue from 2013 shows the Drupal maintainers' decision to remove the need to import annotation classes.

You wouldn't know this by looking at the official Drupal documentation -- they say the annotation classes are loaded "magically".


How do I increase time of slide in jcarousel?

Try this. Click on "View Transition Advanced Options" and into "Timer delay" set time in milliseconds as shown in below image.


What alternatives exist for Autologout in D7

You can just lower the cookie lifetime in your settings.php file as a temporary solution.

  Set session cookie lifetime (in seconds), i.e. the time from the session is created to the cookie expires, i.e. when the browser is expected to discard the cookie. The value 0 means "until the browser is closed.

ini_set('session.cookie_lifetime', 2000000);


How do I set up a default value for a text field?

Usually you setup the default value when configuring the filter -- if you've got an exposed content:type filter, then you set the default values by selecting one or more content types in the Configure filter criterion dialog.

I wouldn't do this via hook_form_alter (or similar) as you'll be fighting Views the whole way.


Webform what is format required to prepopulate datetime element

You need to use an ISO date.

?apptdate=2018-06-13T01:01:01-0400


How to use the Rules module to unset all flags (set x days ago) when cron runs?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below.

Step 1: Create a Rules Component to unflag a node

Create a Rules Component to unflag (= unset the flag) of a node that was flagged by a given user. Assume you give it a machine name like rules_unflag_node_flagged_by_a_user. Use parameters like flagged_node (for the node) and flagging_user (for the user who flagged). And assume that the machine name of your flag is my_special_flag.

Here is a Rules Component (in Rules export format) you can use for this (using the above mentioned machine names):

{ "rules_unflag_node_flagged_by_a_user" : {
    "LABEL" : "Unflag node flagged by a user",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "rules" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "flagged_node" : { "label" : "Node to be unflagged", "type" : "node" }
    },
    "DO" : [
      { "flag_unflagnode" : {
          "flag" : "my_special_flag",
          "node" : [ "flagged-node" ],
          "flagging_user" : [ "flagging_user" ],
          "permission_check" : "1"
        }
      },
      { "drupal_message" : { "message" : "Node unflagged for user  [flagging-user:name] (uid=[flagging-user:uid])" } }
    ]
  }
}

Use the Rules "Import Component" facility (located within /admin/config/workflow/rules/components) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it.

Consider the Rules Action drupal_message as for QA-testing only (remove it in your final version, no need for that Rules Action).

Step 2: Schedule the execution of the Rules Component

Create a rule like so:

Rules Event = After a node gets flagged (with the flag you're already using).
Rules Action = Schedule the execution of the Rules Component (created in Step 1), for execution within x days.

Here is a Rule (in Rules export format) you can use for this (using the above mentioned machine names):

{ "rules_schedule_the_unflag_a_node_flagged_by_a_user" : {
    "LABEL" : "Schedule the unflag a node flagged by a user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler", "flag" ],
    "ON" : { "flag_flagged_my_special_flag" : [] },
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "task" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]"
        }
      },
      { "schedule" : {
          "component" : "rules_unflag_node_flagged_by_a_user",
          "date" : "+7 day",
          "identifier" : "[flag:name]-[flagged-node:nid]-[flagging-user:uid]",
          "param_flagging_user" : [ "flagging-user" ],
          "param_flagged_node" : [ "flagged-node" ]
        }
      }
    ]
  }
}

Some more details about the above rule:

The scheduled date of the Rules Component is within 7 days (cfr. your "x" days).
The identifier of the scheduled task is [flag:name]-[flagged-node:nid]-[flagging-user:uid], which should ensure the scheduled tasks have unique identifiers.
The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed if for whatever reason the same user flags the same node with the same flag (so that it only triggers 1 reminder, and with the most recent date).

Use the Rules "Import" facility (located within /admin/config/workflow/rules) to import it in your own environment, but make sure the machine name of the flag matches with your own machine name for it (and review the value of +7 day to fit your value of "X days"). Then use the Rules UI to enable the rule (it's disabled by default).

Step 3: Run cron periodically

Rules scheduled for execution using Rules Scheduler, will actually be executed "next time cron runs" (after the scheduled date/time has arrived). So make sure to (a) actually run cron and (b) schedule the execution a bit before the cron job will actually run them.

Example: if you want the unflagging to happen every night at (say) 2 am, schedule the Rules Component's execution at (say) 1:55 am, and make sure cron runs at 2 am sharp.

Notes:

The above logic will only apply to nodes flagged by users after the Rule component (Step 1) and Rule (Step 3) was activated.
No need for custom PHP code.

PS: I'm assuming this question is about D7.


View Slideshow with different effects on the same view

If you want to implement different effect for each slide, then you can use views fractionslider module to implement same.

  jQuery plugin for image/text-sliders. It allows you to animate
  multiple elements per slide. Set different animation methods like fade
  or (from) left, delays and easing for each element, or simple set some
  defaults in the plugin options. You also have full layout/design
  control through html and css (every html-element can be animated). Its
  also fully responsive.


AJAX HTTP error on wsclient REST service

It appears that both examples provided by the author no longer work, most likely because the API's changed. See link to author page above.


Loading a specific node revision for view

I think you have misunderstood the usage and intent of hook_node_load. What you do is changing the revision ID (vid) after the node has been fully loaded. Same for hook_node_view(), you are not supposed to replace $node in there, but add additional content to render to $node->content.


Is it possible to use another menu as a submenu of a menu?

There are not settings I am aware. I have not done an exahaustive search for a module. However, you could write your own implementation with a custom module implementing hook_menu(). Simply put, you would create a new menu. Then, you would iterate through the other menu's in your implementation adding each element to the new menu.


Why don't I get a value from drupal_static()?

The default value returned by drupal_static() is NULL; this means that, when you call the function passing for $name a value that has not been used from another function, the value associated with that name is NULL, or the second argument passed to drupal_static().

In your case, you need to call tellafriend_userfullname_function() twice: once to initialize the static value, and once to get the static value.

function tellafriend_form_submit($form, &$form_state) {
  $var = tellafriend_userfullname_function();
  $params = array();

  if ($form_state['values']['cv_included'] == '1') {
     $params['1'] = array('uri' => $var->field_cv_upload['und']['0']['uri'], 'filename' => $var->field_cv_upload['und']['0']['filename'],);
  };

  // Other email set-up goes here.

  $message = drupal_mail('tellafriend', 'notify', $email, language_default(), $params);
}

function tellafriend_mail($key, &$message, $params) {
  $var = tellafriend_userfullname_function();

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['body'][] = $var->field_full_name['und']['0']['safe_value'];
}

In this case, I would not use drupal_static(), for two reasons.

The value you set and get from drupal_static() is a value you can get from a global variable
Even if that would not be the case, you could simply use a static variable inside tellafriend_userfullname_function(), since drupal_static() is used for a static value that needs to be reset externally from the function that defines it

If you look at the code of drupal_bootstrap(), you will notice the following comments.

  // Not drupal_static(), because the only legitimate API to control this is to
  // call drupal_bootstrap() with a new phase parameter.
  static $final_phase;
  // Not drupal_static(), because it's impossible to roll back to an earlier
  // bootstrap state.
  static $stored_phase = -1;

drupal_static() is not a replacement for every static variable that could be used from a function; it should be used when the static variable is used to save a state another function could need to reset. The documentation for drupal_static() says:

  A guideline is that if a function's static variable does not depend on any information outside of the function that might change during a single page request, then it's ok to use the "static" keyword instead of the drupal_static() function.

As example of when drupal_static() is used, see menu_reset_static_cache(), which contains the following code.

  drupal_static_reset('_menu_build_tree');
  drupal_static_reset('menu_tree');
  drupal_static_reset('menu_tree_all_data');
  drupal_static_reset('menu_tree_page_data');
  drupal_static_reset('menu_load_all');
  drupal_static_reset('menu_link_get_preferred');

If menu_tree() didn't use drupal_static(), resetting the static variable it uses would not be possible, if not changing the function to use the following code.

function menu_tree($menu_name = NULL, $reset = FALSE) {
  static $menu_output = array();

  if ($reset) {
    $menu_output = array();
  }

  if (isset($menu_name)) {
    if (!isset($menu_output[$menu_name])) {
      $tree = menu_tree_page_data($menu_name);
      $menu_output[$menu_name] = menu_tree_output($tree);
    }
  }

  return $menu_output[$menu_name];
}

This would have been possible, but it would have changed the interface between the function and the functions using it. Since this is a common pattern among different Drupal functions, defining drupal_static() and using it in those functions needing it has been a Smart Thing™.


You may try using WordPress Migrate which supports migrating WordPress blog exports (WXR format) into Drupal using Migrate module. Check also Migrate Extras which provides additional support for contrib modules.

For any other extra functionality which is not covered, you've to extend it by writing your own custom class. Check Migrate Example for example of migration data.

See also: What is the most reliable way to migrate a Wordpress site into Drupal?


Is it possible to get last modified date for certain field?

I took a quick look at the field_data_xxx and field_revision_xxx tables and there is no time stamp field, which means you wont be able to get the last modified dates for fields.

You can probably use Field Attach API to add time entries to a custom table which will contain field_key, entity id, bundle id and time-stamp columns.


If $node->icon is the path relative to public://, then you can use the following code.

if ($wrapper = file_stream_wrapper_get_instance_by_uri("public://{$node->icon}")) {
  $url = $wrapper->getExternalUrl();
}

The code works also for stream wrappers that are not local, for which the file is not local to the server running the code.


I found the problem, I was using the same variable names (for example $query) in different custom modules I build. Changing these variable names to unique names made it work perfectly.


Make a public object property visible in other places

I would use a function to instantiate your class in a static fashion and then you have access to the same instance across your page load:

function MYMODULE_jcart_instance() {
  $jcart = &drupal_static(__FUNCTION__, NULL);

  if (!$jcart) {
    module_load_include('php', 'shop', 'jcart/jcart');
    $jcart = new jCart(); // Or whatever this might be
  }

  return $jcart;
}

From then every time you need access to the jcart class instance anywhere else on the site you just call:

$jcart = MYMODULE_jcart_instance();

Just a quick note, putting in an include into html.tpl.php is not a good way to do this. The theme layer is not invoked until all other processing has been done so your include should really be in a module file. I've shown this above using the module_load_include() function.

Hope that helps

EDIT

I've just seen your previous question relating to this and you mention that the class is instantiated in the include file already. If that's the case just change your static function to this:

function MYMODULE_jcart_instance() {
  $included = &drupal_static(__FUNCTION__, FALSE);

  if (!$included) {
    module_load_include('php', 'shop', 'jcart/jcart');
  }
}

and then add a call to this in hook_init() (this will be called before pretty much any of the rest of your code):

function MYMODULE_init() {
  MYMODULE_jcart_instance();
}

If $jcart is declared in global scope you'll need to add global $jcart to the functions that want to use it.