Is it possible to create web service CRUD operations for contributed modules in drupal 7?

Yes, the Services module has an API, details of which you can find in the module files. You can use that API to provide CRUD for anything at all. See Creating a resource for Services 3.x for a full module example.

Since private messages are entities, you might also look to the Services Entity API module for inspiration (or, it you're particularly lucky, a pre-built solution, depends what you need, and whether you can use an alpha release):

  This module provides support for all Entity API entity types to Services. All entity types get a standard resource, similar to what Services provides for code entity types such as nodes.


Display content referring other content in a mapping table

I don't think you can build that with views or another UI tool just by clicking it together.

It should however not be too complicated to build with a but of custom code.

You need to build an entity query that gets all TypeA nodes, another one that gets all TypeB nodes, loop over Type, and for the columns, loop over the Type B and check if you have a reference for them in your field.

IMHO writing out the full code is too much for a single question, I suggest you get started and if you have problems, ask specific questions.

Obviously that table will get huge if you have a lot of nodes of either type or even both.


Rules - show information after certain time

If you want to achieve it with rules, you can do it with the following steps:

Add new rule
React on event: Content is viewed (under Node section)
Add new condition: Data comparison
Data to compare: node:created
Operator: 'is lower than'
Data value: Switch to the direct input mode and put '-2 weeks', or '-14 days'
Add new action: 'Show a message on the site' (under System section)
Put your message in as value, and select the type of the message. E.g. 'Status'


Fetching more than id's of an entity using EntityFieldQuery

No - you need to load the comment (comment_load()) to get property and field data attached to the results of an EFQ - its job is to load IDs only.

An alternative would be mikeytown2's EntityFieldQueryExtra class, which does allow you to attach field and property data to the results of the query.


PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1532856' for key 'PRIMARY': INSERT INTO {watchdog}

There are 2 things going on here.

The PDOException is because Watchdog is trying to insert a duplicate primary key, 1532856. Your auto increment value could be off or some other table corruption could be going on there. A simple fix is to truncate the watchdog table if you don't care about maintaining old log data. Otherwise, you could try to repair the table or fix the auto increment value if you want to retain old log data.
The error being logged has to do with your field-collection-item.tpl.php template in the Nexus theme on line 37. A key called field_enter_module_name_here is being referenced when it doesn't exist. It looks to be a custom template addition to the theme (it doesn't exist in the 7.x-1.3 release). Given, the key name, it sounds like some sort test code dropped into this template. This is warning so it shouldn't be a critical problem, but you should fix it to clean out extraneous errors from filling up your logs.


Use hook_form_alter() on its form ID. The form is built via Views, and I can't recall the ID off the top of my head, but any time I don't know the ID to use I just use a general hook_form_alter() and print out the form ID of every form on the page. You'll find it fast.

Depending on the type of data you're collecting and how you need it stored, it could be that you add a field to the base order type and then populate it based on the value of whatever field you add to the shopping cart form.


Create new node and assign it to user after they have been registered

This is very easy to do in D8 Rules. Here is an export of a Rule which does what you asked - when a new user is created, it creates a new node (of type article, as an example). It then sets the node author to be the new user. It then sets a field of the new node (the body field, in this case) to a value take from the user (the user's email address, in this case). As you can see, Rules are stored in YAML files, and are imported/exported like any other configuration in D8. So you can just import this and you will immediately have a working example which you can then modify to use the specific fields you've defined on your user entity and node type. This Rule additionally displays a system message, which is a very useful way to debug Rules.

langcode: en
status: true
dependencies: {  }
id: create_a_node_for_each_new_user
label: 'Create a node for each new user'
events:
  -
    event_name: 'rules_entity_insert:user'
description: 'Node fields will be populated from values entered on the user form.'
tags: {  }
config_version: '3'
expression:
  id: rules_rule
  uuid: c9428f2d-c0b9-47bf-a7e5-3f2cc8af9f54
  conditions:
    id: rules_and
    uuid: 47b8d622-ed38-4977-8e58-4cca6d89260a
    conditions: {  }
  actions:
    id: rules_action_set
    uuid: d96fd6b5-1638-4b15-adde-5f5d7673fb8f
    actions:
      -
        id: rules_action
        uuid: e09cd52d-76fe-4682-91de-bfed58a651ab
        context_values:
          message: 'Node created using information entered by <em>{{ user.name }}</em> when registering'
          type: status
          repeat: false
        context_mapping: {  }
        context_processors:
          message:
            rules_tokens: {  }
          type:
            rules_tokens: {  }
          repeat:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_system_message
      -
        id: rules_action
        uuid: fe2acb55-9234-4754-9d2b-3d1889d1775c
        context_values:
          type: article
          title: 'Article created by Rules for {{ user.name }}'
        context_mapping: {  }
        context_processors:
          type:
            rules_tokens: {  }
          title:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: 'rules_entity_create:node'
      -
        id: rules_action
        uuid: 743be03f-d1b7-4251-a1ac-80b17aa5c86e
        context_values:
          value: '{{ user.mail.value }}'
        context_mapping:
          data: entity.body
        context_processors:
          value:
            rules_tokens: {  }
        provides_mapping: {  }
        action_id: rules_data_set
      -
        id: rules_action
        uuid: 91f3c8f2-eb47-46e6-a9dd-2affc90e15d2
        context_values: {  }
        context_mapping:
          data: entity.uid.target_id
          value: user.uid.value
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set


What settings from a zen sub theme are not saved as files?

There are two major locations for theme configuration - be it a sub theme or a primary theme:

http://example.com/admin/appearance/settings/yourtheme

For a zen sub-theme, this page lets you configure display of logo, site-name, slogan, and more, including a couple of menus. Also the favicon (shortcut icon), breadcrumb settings, and more can be found here.

http://example.com/admin/structure/block

You need to configure each block's "Region Settings" (click "configure"  on the right), to assign or adjust a region for the block to your new theme. The region settings provide a pull-down menu with available regions for each enabled theme.

If you want to duplicate settings from one sub-theme to another sub-theme, make sure you adjust all files in the theme folder (theme.info, template.php, theme-settings.php). If you do extensive theme pre- or post processing, and change themes frequently, you might want to roll these into their own custom modules (see How to modify module output via another module - whois module? for an example of the same functionality as theme pre-processing or custom module).

There might be additional settings in contributed modules - you mentioned panels.


Show term description when grouping by taxonomy term

One option for solving this is to rewrite the output of your view fields to meet your formatting requirements, which consists solely of configuration steps -- no code changes needed :).

On your view, add the Taxonomy: Term field and the Taxonomy: Term description field.  Make sure the Term field is above the Term description field.
Next, edit the Term field, select Exclude from display, and click Update.
Now, edit the Term description field and check Rewrite the output of this field. You can set this Term description field to include the formatting you desire of your Term name and Term description using the available tokens, which are listed in the Replacement patterns fieldset.

For example, try placing the following into the rewrite Text textarea:

[name]

[description]

Be sure to click Update after you have finished configuring the Term description field.

Last, in your field settings, select Group by Term description and voilà, you should have all the data you want in each grouping section. As long as your term names or term descriptions are unique, this should group as expected.


Illegal choice error in views exposed filter select list

Don't choose select all option (it is a simple javascript effect to choose the values) or don't select any user from list. If you just choose expose the filter option it will display all the users list automatically.


Moved Drupal 6 site to new server - can't login

This happened to me so many times back in the days of Drupal 6.

99% of the time it was caused by the anonymous user record having been removed from the users table in the database.

Try adding a user to that table with a uid of 0 (and all other fields empty); if the above is what's causing the problem, that should fix it.


Is it possible to use Rules to make an action to entities that refers to other with entity reference

Finaly i found the solution to this problem using module Views Rules.

I create a view of users, i pass the nid as an integer and set a content referencing to the user.

I don't know if there's a better way but this works fine.


Requestee user cannot remove a one way User Relationship with requester user

I applied the patch listed here (https://www.drupal.org/node/1328170#comment-6980582) and that resolved the issue.


I would do this with CSS as @Ivanhoe123 suggested.

fieldset {
    width: 100px;
}


Accessing imagecache path inside template

Using the Contemplate module is not recommended since it puts PHP code into the database which is generally considered a security vulnerability and non-performant.

You want to use theme('imagecache', ...) instead, which will return the HTML img tag with the proper path.


Display node content with frontend theme in admin route

If this is a custom route (defined in a routing.yml file with a custom controller) you are able to do this by defining the route in the routing yaml with
options:
    _admin_route: FALSE

Which will cause the route to be treated as a "frontend" route. However it sounds like this is likely not the case here.
If you simply want to have previewing of standard content, the core preview function (the button next to "Save") is the standard mechanism to do this.


Custom entities created time is always the same

I had my php code cached before adding the setCreatedTimemethod to my custom entity. After clearing the cache everything was fine!

So in general: add the setCreatedTime method to your custom entity to make your created timestamp work.


How to add a menu link to a menu programmatically?

I was using the wrong namespace.
Use the following namespace

use Drupal\menu_link_content\Entity\MenuLinkContent;

and then the following code will work.

MenuLinkContent::create([
      'title' => 'Example link',
      'link' => ['uri' => 'internal:/node'],
      'menu_name' => 'main',
    ])->save();


How do I programmatically disable a form?

The D8 way to do this is to write a custom access check.

This is the one which now checks the access for the user register form:

src/Access/RegisterAccessCheck.php

<?php

namespace Drupal\user\Access;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Access check for user registration routes.
 */
class RegisterAccessCheck implements AccessInterface {

  /**
   * Checks access.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The currently logged in account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    $user_settings = \Drupal::config('user.settings');
    return AccessResult::allowedIf($account->isAnonymous() && $user_settings->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY)->cacheUntilConfigurationChanges($user_settings);
  }

}

user.services.yml

services:
  access_check.user.register:
    class: Drupal\user\Access\RegisterAccessCheck
    tags:
      - { name: access_check, applies_to: _access_user_register }

user.routing.yml

user.register:
  path: '/user/register'
  defaults:
    _entity_form: 'user.register'
    _title: 'Create new account'
  requirements:
    _access_user_register: 'TRUE'

Put these files in a module and change user to mymodule and choose a custom class name.

To successfully override the route in mymodule.routing.yml you have to adjust the module weight. Or instead change the access settings of the existing route in a RouteSubscriber, which is a bit more work to do, but the better solution.


That setting is stored in the variable table as a serialised PHP string (in the "error_level" var) - I wouldn't advise updating that table manually with SQL (although obviously you can if you need to).

Far better would be to install Drush, and use vset as part of your deployment process instead:

drush vset error_level '2'

The available options are:

0 => None
1 => Errors and warnings
2 => All messages


I'm guessing what you actually want (from a user story perspective) is if a certain condition is met another, otherwise hidden, field is shown. As @geoff points out that field would need to exist on the content type.

I believe the correct way to do this within the Form API is with the #states parameter in order to conditionally show/hide the phone field.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states


How do you build up a LIKE condition in a db_select() query?

After digging through Drupal Documentation found a solution in db_like API documentation page and SelectQuery:condition handler doc page..

For example

$result = db_select('field_data_field_name', 'f')->fields('f', array(
    'entity_id',
    'field_name_value'
))
->condition('entity_type', 'user')
->condition('bundle', 'user')
->condition('deleted', 0)
->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')
->distinct()
->range(0, 10)
->execute();

Condition to use for like query is

->condition('field_name_value', '%' . db_like($last_item) . '%', 'LIKE')


How to install another module when a module is being installed

If a module depends on another module, you have to declare it as a dependency. The way Drupal handles this, is through the *.info.yml files, which define the basic module attributes.

In 'travel_list.info.yml' add this key:

dependencies:
  - field_group:field_group

Doing that, whenever you install the module 'travel_list' it will enforce you to install 'field_group'; this means that if you try to install 'travel_list' module and 'field_group' is not installed, the installation will abort reporting that 'field_group' module is needed.

Developing an script that downloads and triggers the module installation is far away from good practices and can lead to a number of unpredicted situations, starting by the fact that the required modules of your Drupal are defined in the composer.json.


Add your search paths to list of pathes boost ignores, either via UI or in the line

RewriteCond %{REQUEST_URI} (^/(admin|cache|misc|modules|sites|system|openid|themes|node/add|comment/reply))|(/(edit|user|user/(login|password|register))$) [OR]

Boost should always be skipped for dynamically generated pages, it can't handle it to well.


/**
 * Implements hook_field_widget_form_alter()
 */
function HOOK_field_widget_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'commerce_price') {
      if (empty($element['amount']['#default_value'])) {
        $element['amount']['#default_value'] = 0;
      }
    }
  }
}


There is a block in drupal 8 for displaying breadcrumb on your pages.
First set visibility of that block on the pages you want to show breadcrumbs.

Then in template_preprocess_breadcrumb in your theme's .theme file you can change the breadcrumbs variables.

For additional functionality you can create breadcrumb.html.twig file in templates folder of your theme.


There is data for the field - On uninstalling module

This is a known limitation to Drupals Core and this finally gets resolved for Drupal 8.5.x, see this issue:
https://www.drupal.org/project/drupal/issues/2282119

But for versions earlier there is an option to workaround this, by creating a form that handles the cleaning of added data to make the uninstall validation pass. This is a UI solution but you still need to add a not somewhere that users know how to find the form. See how the Flag module handled it:
https://www.drupal.org/node/2409673

There are other options like creating a drush command, but what you basically need to do is to clean the added data from the database to make the validation for uninstall pass and allow users to uninstall the module.


Load Pages Using AJAX to Allow for a Continuous Music Player

To quote my answer to the same question at StackOverflow:

  Ajax pages makes it possible to load every page via Ajax with minimum effort. A player can be put in a region outside of the Ajax-loaded area, making for continuous playback. There are demo links on the project page, check them out.


Selecting image for embedded youtube video

Sadly you cant if its not your video. This is chosen either by youtube or if your a youtube partner you can upload your own image (I think they have a tool nowadays which lets regular youtube users choose their thumbnail for their video).

If you visit this page:

https://developers.google.com/youtube/2.0/developers_guide_jsonc

You will see down the page there is a default/hqdefault thumbnail that comes with every video feed.


How can I set a separator for a taxonomy field?

You can do this in Twig.

Place this file in the templates folder of your theme (field-tags is the field name):

field--field-tags.html.twig

 <div{{ attributes }}>
    {% for item in items %}
      {% if not loop.last %}
        <span{{ item.attributes }}>{{ item.content }} - </span>
      {% else %}
        <span{{ item.attributes }}>{{ item.content }}</span>
      {% endif %}
    {% endfor %}
  </div>

To add classes use {{ attributes.addClass() }} or {{ item.attributes.addClass() }}, see https://drupal.stackexchange.com/a/212307/47547


How do I add content type in taxonomy settings?

Drupal 7 and 8 Core does not have that. I've never used Drupal 6, based on your question, it seems like they changed how tax terms are added to content types in D7.

For Drupal 8, all you have to do is go to Content Type (ex: Article) >> Manage Fields >> Add Field >> Select: Taxonomy Term >> Save Field Settings >> Checkmark your vocabulary >> Save settings.


Given a block_id, what would be the most reliable method to decide if the block was generated by Views?

As Clive said, each block will contain the module name from which it was created in the block configuration. For views blocks, it's views module.

This module information will be available in the form structure itself, like below:

$form['module']['#value']

So you don't need to query the database to retrieve it.

Pseudo code:

function my_module_form_block_admin_configure_alter(&$form, &$form_state) {
  if ($form['module']['#value'] == 'views') {
    // ...
  }
}


How can I assign users different profile pictures upon registration based on gender?

A simple approach might be to retheme the gender field itself so that it displays an image based upon its value, eg, instead of displaying male, it displays an image with path sites/default/files/male.png.

In D6, this would mean copying CCK's content-field.tpl.php to your theme directory and then creating content-field-field_gender.tpl.php and jiggering things up in there, eg...

print theme('image', 'sites/default/files/' . $item['view'] . '.png')

...instead of just print $item['view'].

My quick look at D7 here suggests that copying Field's field.tpl.php to field--gender--profile.tpl.php in your theme's directory would be basic starting point there and instead of render()ing $item, doing something similar with its value.

Then, in either version, just make sure you have three images in your files directory called male.png, female.png and unknown.png (or files based upon whatever the values of your gender field are.)

With this approach, you only have three files to deal with instead of a file uploaded and stored for each and every user.  Another side benefit is that they will be easily cached by your users' browsers.

ADDITION:

Based upon new info from comments and other answers, you could do something like this in your user-picture.tpl.php template:

if (!empty($account->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($account->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
} else {

  $file_path = 'sites/default/files/' . $account->field_gender[LANGUAGE_NONE][0]['value'] . '.png';
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file_path));

}

where the new stuff is the else .... Pardon my D6ism if sites/default/files is wrong in D7, but basically you just want a path on your system to where you've stuck male.png, female.png and unknown.png and you display them when your profile_picture field is not set.


What would cause a Drupal site to display a 500 error or a blank page depending on browsers?

The article about The White Screen of Death (Completely Blank Page) is a good place to start.

Depending on your shared host, you can often get access to logs if you poke around your control panel, or they sometimes are copied into your home directory.

Since you explicitly mentioned shared hosting, your best best is to open a trouble ticket.  They can tell you exactly what is wrong fairly easily.

If it is a true 500 error, then my guess is that one of these two lines in the .htaccess is causing the problem.

Options -Indexes
Options +FollowSymLinks

You can try commenting them out one at a time and see what happens.  I suspect that your host has AllowOverride set to None and one of those is trying to set a non-default value that the host has set.


I would look at the references module, this will allow you to manually set relationships between your "people".


How to properly manage field types for a content type created by a module?

To properly manage fields added by a module, so that a field is added and removed when the module is installed and uninstalled, add an enforced dependency for your own module to the yaml file:
/config/install/field.storage.node.field_example.yml
...
dependencies:
  enforced:
    module:
      - mymodule

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


Update default value of form element with AJAX

The value must be set in the hook_form_alter, not in the callback of ajax :

function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );

  if(!empty($form_state['values']['field_user_email']){
       $form["field_user_city"]['und'][0]['value']["#default_value"] = "foo";
  }
}

function user_ajax_check($form,$form_state){
    // load the user then
    return $form["field_user_city"];
}


I have pretty much the same code as you have with the exception that I have a hook_theme_suggestions_page_alter(). With the _alter attached to it.

Try putting the HOOK in a custom module instead of the .theme file.


How do I load information for views programmatically?

Sounds like you could use views_get_view_result().

views_get_view_result($name, $display_id = NULL)
Get the result of a view.

Also take a look at this answer for a more complete solution.


How to allow any file extension (or use a blacklist instead of a whitelist) for file fields in Drupal 8?

Implement a hook alter on the node form or the field level and  in it change the validator to your custom function:

/**
 * alter form field element:.
 *
 * Implements hook_FORM_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
    $upload_validators = array(
        'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
    );
    $form['your_file_field_element']['#upload_validators'] = $upload_validators;

}

Alternatively you can change the behavior of the field on any node, or entity by altering the widget form:

function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {
   if ( "condition to check if it's your field" == TRUE) {
     $upload_validators = array(
            'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
        );
        $element['#upload_validators'] = $upload_validators;
  }
}

Then write you own function to do what you want:

function my_module_file_validate_extensions_blacklist(stdClass $file, $extensions) {
  $errors = array();
  $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (preg_match($regex, $file->filename)) {
    $errors[] = t('files with the following extensions are not allowed: %files-allowed.', array(
      '%files-allowed' => $extensions,
    ));
  }
  return $errors
}


How to change checkboxes options with ajax callback

I think the problem is simply a matter of the order the functions are run in.

The AJAX callback will run after the form has been built. So even though you're adding the new item to the database, the code to build the checkbox options (from $user_hardware = _get_users_hardware($user); downwards) has already run. Since it's already run, the new DB item won't be shown until the next time the page is loaded.

If that is the problem the fix would be as simple as adding a bit of code to the end of your _update_hardware() function, to populate the new options:

// ...

// Insert the hardware in to the database...
db_insert('waiver_hardware')->fields(array(
  'user_id' => $user->uid,
  'date_added' => REQUEST_TIME,
  'hardware_type' => $hardware_type,
  'manufacturer' => $manufacturer,
))->execute();

$hardware_options = array();
foreach($user_hardware as $h)  {
  $hardware_options[$h['hid']] = $h['hardware_type'] . ' (' . $h['manufacturer'] . ') ' . 'S/N: ' . $h['serial_number'] . ', Last Seen: ' . date('D, n/d/Y g:i a', $h['last_seen']);
}

$form['user_info_div']['selected_hardware_checkboxes']['#options'] = $hardware_options;

return $form['user_info_div'];


How set div in a specific position inside .tpl.php file

Well, there are three solutions for your problem,

Forget about the div with class uniscicampischeda and try to work with the existing classes in order to align them to right.
If you want to insert the div.uniscicampischeda, try to find out which one of the PHP lines generates the
..
, then edit the .tpl file and put the DIV before that PHP line.
As the last solution and also the most complicated one, in your template.php create function hook_preprocess_views_view_fields(&$var), in this function get the Views fields value and insert them in to the $var array, then in the .tpl file use those keys of the $var array as the variable that generates the corresponding value. Using this solution you will have much more freedom to theme your view output.

If you need help about any of these solutions just let me on it.


variable_get() using "default value" with no reason in Pressflow 6

If you look at the code for variable_init() used by Pressflow, you will notice the following:

If the MAINTENANCE_MODE constant is defined, it tries to acquire the "variable_cache_regenerate" lock; this means the code will not be executed until lock_acquire() doesn't return TRUE.
In the case lock_acquire() doesn't return TRUE, the function will call lock_wait('variable_cache_regenerate'), and then recursively call itself.
After 49 recursive calls, the function set the $variables variable to an empty array; doing so, all Drupal variables are set to their default values.
The comment in the function says:

  Try a limited number of times to avoid
    // infinite recursion if the database connection is invalid for
    // some reason, e.g., mysqld restart, loss of network, etc.

This behavior is not present in the function used by Drupal 6, where variable_init() doesn't use any lock.

Similar code is used from Drupal 7, even though there is a slight difference: Drupal 7 reads the values of the Drupal variables from the database, while Pressflow doesn't do that. Compare the following snippets; the first one is used in Drupal 7, while the second one is used in Pressflow 6.

// Cache miss. Avoid a stampede.
$name = 'variable_init';
if (!lock_acquire($name, 1)) {
  // Another request is building the variable cache.
  // Wait, then re-run this function.
  lock_wait($name);
  return variable_initialize($conf);
}
else {
  // Proceed with variable rebuild.
  $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
  cache_set('variables', $variables, 'cache_bootstrap');
  lock_release($name);

  // Wait for another request that is already doing this work.
  lock_wait('variable_cache_regenerate');

  // Run the function again. Try a limited number of times to avoid
  // infinite recursion if the database connection is invalid for
  // some reason, e.g., mysqld restart, loss of network, etc.
  $recursion_depth++;
  if ($recursion_depth < 50) {
    return variable_init($conf, $regenerate, $recursion_depth);
  }

  $variables = array();


How to display Articles on another page ? not in home page

You are looking for Views module:

  You need Views if

  You like the default front page view, but you find you want to sort it differently.
  You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain type.
  You like the idea of the 'article' module, but it doesn't display articles the way you like.
  You want a way to display a block with the 5 most recent posts of some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.


call mp3player field (CCK Field) in a page

From the readme.txt file of that module.

  Pop this code anywhere to insert an audio player:

if (module_exists('mp3player')) {
  print theme('mp3player', 'Default', $audio_file_url, $audio_title, $audio_artist, $description);
}


I found a module called Web Service Clients.  It is still unstable, but it works.

  Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being ingesting content from other Drupal installs via the Services module XMLRPC server.


Assuming both views are showing the same page, it could be accomplished using something like this:

Using Views Field Views, create the second view as a child field of the first

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

pass the arguments (instructions included in module) to the second view to ensure it is getting the correctly information
use Views Auto Refresh, Views Flag Refresh or Block Refresh - depending the exact set up you have and want to refresh the second view


How do I join across two different databases?

Yes, with caveats that your DB infrastructure config will dictate if you can do this.

While MySQL allows you to do cross DB table joins, the DB user needs privileges to access both DB's to do it. Additionally, Drupal can only use one DB connection to execute a cross DB table join query.

So if you had a connection defined in your settings.php, called my_connection, and it had access to 2 DBs called DB1 / DB2
You could do things like:

// Assuming 'my_connection' defined in settings.php has access to DB1 & DB2
$db_key = 'my_connection';
$example_join_query = 'SELECT * FROM `DB1`.users AS u1 LEFT JOIN `DB2`.users AS u2 ON u1.uid = u2.uid';
$connection = \Drupal\Core\Database\Database::getConnection('default', $db_key);
$example_results = $connection->query($example_join_query)->fetchAll();

// Same idea, with dynamic queries
$query = \Drupal::database()->select('`DB1`.users', 'u1')->fields('u1');
$query->join('`DB2`.users', 'u2', 'u1.uid = u2.uid');
$query = $query->fields('u1');
$query = $query->fields('u2');
$example_results = $query->execute()->fetchAll();

If your DB infra config is something like 2 isolated hosts, you'll need to take a different approach, like querying data for each DB connection then joining the resulting datasets in PHP code (instead of using a SQL JOIN).


Such a concept doesn't really exist in the config system. There is no overridden status like in cools/entity exports in 7.x.

Default config is only default config as long as it is a file in config/install. Once it is installed, it just is your configuration, there isn't really a connection anymore to the original default config file.

There is a hash in those files, so you could technically write something that looks for the default config file and compares the hash or even compare every single value. But keep in mind that default config can actually change, deciding whether you'd want your unchanged existing value or the new default is something that is surprisingly hard to do.

Not sure what you would want this for, the only thing that I can think of would be config for an install profile.


$_POST is:

  An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

That's not what you're doing. To receive JSON data in PHP you need to use:

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Or change the data type of your AJAX request to one of the values that will result in $_POST being populated.


Drupal Commerce custom Coupon Type not discounting

You may need to implement

hook_commerce_coupon_granted_amount_alter

to add your granted amount to the display there.

e.g:

/**
 * Implements hook_commerce_coupon_granted_amount_alter
 */
function MYMODULE_commerce_coupon_granted_amount_alter(&$amount, $coupon, $values) {

  if ($coupon->type == 'my_coupon_type') {
    $order = commerce_order_load($values->order_id);
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);

    // Do stuff to get amount from coupon...
    // ...
    // ...
    $amount = 1000; // example
    $currency_code = "USD";
    $amount = commerce_currency_format($amount, $currency_code, $coupon);
  }
}


/**
    * Implements hook_toolbar().
    */
    function backlinks_notifications_toolbar() {
        $items = [];
        $items['toolbar_menu_backlinks_notifications'] = [
            '#type' => 'toolbar_item',
            'tab' => [
                '#type' => 'link',
                '#title' => 'Notifications',
                '#url' =>  Url::fromRoute('<front>'),
                '#options' => [
                    'attributes' => array(
                        'title' => t('Backlinks Notification'),
                        'class' => array(
                        'toolbar-item',
                        'toolbar-icon',
                        'toolbar-icon-backlinks-notifications',
                        ),
                    ),
                ],
            ],
            '#weight' => 999,
            '#attached' => array(
                'library' => array(
                    'backlinks_notifications/backlinks_notifications',
                ),
            ),
        ];
        return $items;
    }

Hook available at
https://api.drupal.org/api/drupal/core%21modules%21toolbar%21toolbar.api.php/function/hook_toolbar/8.2.x


You will probably have to create a library, module, or simple a function Wick does the logic of this, and then call the function from where you want (views).

It's a pretty generic question, without more info is difficult to know what you are trying to achieve, but in similar situations what we use to do is create a separate library or module which is called from cron, for example.

This library will keep updated a second content type, with the contents of your files, RSS, XML, etc.

When views saves this content, you'll simply have to link both content types, probably making it faster simply reading contents and leaving the logic to a background process (managed by cron).

But again, maybe you are trying to achieve a different thing.


Show a webform input if user selects certain option from select list?

Update to a newer version of Webform where webform_conditional has been merged.

  Description: This modules enhances the existing Conditional Rules of
  the Webform Module. It adds the ability to make components dependent
  on select components(i.e. listboxes, radio buttons, and checkboxes)
  that appear on the same page.

  Important As of Webform version 7.x-4.0-alpha2 this module has been merged into Webform and is no longer necessary. The 7.x-2.x
  version of this module handles this upgrade. See: #1616376: Create
  Migration to Webform 4.x

Then when you make a webform node you will have additional local task labeled conditionals. Once you've added form fields to the webform -- you can set conditions using the administrative form found there.


Filtered HTML Text format without an editor

First you create your two text formats (if not already present).

Then you can use the wysiwyg module (http://drupal.org/project/wysiwyg) to display an editor for the Full HTML text format (on /admin/config/content/wysiwyg). wysiwyg will only display editors that you have set up properly (usually by placing a third party library in sites/all/libraries)

You can limit use of the text formats via the permission settings.


Using Views "Rewrite the output of this field" tokens

There's a simple way to show only the first image in a field that allows multiple image uploads.

In the Configuration screen for the field, there's a dropdown called "Multiple Field Settings." Expand that, and you should see options for how many items you want to display, and which item in the list to start with. Change "Display __ value(s)" from all to 1. You shouldn't need to change the separator in your case, as you're only displaying one image.

See below for screenshot. This setting should work fine alongside "Rewrite the output of this field" tokens (I haven't had it not work).

http://img585.imageshack.us/img585/8644/multipleimagesshowonlyo.png

In a field with several images uploaded, I'm correctly seeing only the first as you can see here:

http://img713.imageshack.us/img713/5479/resultzc.png


Is there an interactive PHP testing tool for Drupal?

If you are running locally, you can install Netbeans and Xdebug and set break points, watches and everything.

If you want just a little better then drupal_set_message() you can run devel and the output from dpm() will be formatted by Krumo. That's at least helpful.


How can I make a Menu Block not auto-expand the current page's menu links?

I'm currently doing this with hook_menu_block_alter() calling itself recursively:

function THEME_NAME_menu_block_tree_alter(&$tree, &$config) {
    if($config['expanded']) {
        return;
    }

    foreach($tree as $link_key => &$link) {
        if(!empty($link['below'])) {
            if(!$link['link']['expanded']) {
                $link['below'] = array();
            } else {
                THEME_NAME_menu_block_tree_alter($link['below'], $config);
            }
        }
    }

    unset($link);
}

But this feels super sketchy and I'm not at all confident that it's the best solution. I could break the foreach() into a separate recursive function, but that hardly seems different, other than my general icky feeling which I'm not sure there's even a logical reason for me to have.


How to remove CSS files if the page being rendered is a front page in a theme?

The function you're looking for is drupal_is_front_page().


drupal_set_message doesn't display message sometimes

It sounds like you need to maintain a stable message storage solution until the operation is complete.
The D7 core message functions drupal_set_message() & drupal_get_messages() (the core function used when retrieving messages for rendering) are pushing/popping messages to session var, $_SESSION['messages'] These messages are designed around a single page request/received operation.
If there many different async requests going on with the same session (or other modules calling drupal_get_messages() with its default options), its likely $_SESSION['messages'] is being cleared out before rendering when you need it.
Try storing your messages somewhere else (e.g. another session variable) then call drupal_set_message() with your messages once the full operation is complete. If most messages are background ops, you should use consider watchdog() for logging background ops and then use drupal_set_message() for a "operation complete" message.


Show specific gmap in block based on node id

Add an argument to the view, the argument is the node ID, then you'll be able to retrieve fields and information only for the viewed node.

Example: http://through-my-eyes.be/portfolio/events/2011/04/07/drupal-government-days-2011


Devel module will Do it for you and happy Devel module is ported to Drupal 8 https://www.drupal.org/project/devel

Enable Devel and Devel Generate

go to "/admin/config/development/generate/content" give the number of content it will generate bulk content for you.


You can get nodes as shown below:

$nodes = taxonomy_select_nodes($tid); // $tid is term id
$nodes = node_load_multiple($nodes);

Ref: taxonomy_select_nodes -> https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_select_nodes/7

Update #1

To get some fields out of $node object use following:

foreach($nodes as $node):
    $tids = field_get_items('node', $node, '<TERM_FIELD_NAME>');
    foreach ($tids as $tid){
        if($tid['tid'] == <SELECTED_TID>){
            print $node->title;
            print render(field_view_field('node', $node, 'body'));
            print render(field_view_field('node', $node, 'tags'));
        }
    }
endforeach;

To render complete node you can use node_view function. In order to render multiple nodes you can use node_view_multiple function as shown below:

$content = node_view_multiple($nodes, 'full');
print render($content);


With the core testing, how do I set a database variable?

drupalVariableSet() has been removed as per Remove drupalVariableSet.

variable_set() is the function you should use. In fact, DrupalWebTestCase::setUp() uses it for some persistent variables used from Drupal core, right after the call to drupal_install_system().

  // Perform the actual Drupal installation.
  include_once DRUPAL_ROOT . '/includes/install.inc';
  drupal_install_system();

  $this->preloadRegistry();

  // Set path variables.
  variable_set('file_public_path', $this->public_files_directory);
  variable_set('file_private_path', $this->private_files_directory);
  variable_set('file_temporary_path', $this->temp_files_directory);

  // Set the 'simpletest_parent_profile' variable to add the parent profile's
  // search path to the child site's search paths.
  // @see drupal_system_listing()
  // @todo This may need to be primed like 'install_profile' above.
  variable_set('simpletest_parent_profile', $this->originalProfile);

As long as the following conditions are met, using variable_set() should work as expected.

The test class derives from DrupalWebTestCase and not from DrupalTestCase
variable_set() is called after parent::setUp()
The name of the persistent variable used in variable_set() doesn't contain typos


You can try using Apache Solr Views module.

Project page says

  In order to get the facet blocks provided by the Apache solr Search
  Integration Project you need to set up either arguments or exposed
  filters for the blocks. For instance, you could set up an argument for
  node type and the Apache Solr Search: Filter by content type block
  will work.


$node->rendered is set in node_search_execute():

$build = node_view($node, 'search_result');
unset($build['#theme']);
$node->rendered = drupal_render($build);

It contains the rendered node display for the search_result view mode.


preprocess_field() not working - what am I doing wrong?

I think it was the # in front of items that was messing things up. I have this working now as

function creative_responsive_theme_preprocess_field(&$variables) {
    if (user_is_logged_in()) {  return $variables;}
//if (in_array($variables['element']['#field_name'], array('field_audio_fast_', 'field_audio_slow_'))) {
    if (($variables['element']['#field_name'] == 'field_audio_fast_') OR ($variables['element']['#field_name'] == 'field_audio_slow_')){
        $variables['items'][0]=[];
        $variables['items'][0]['value'] = ' ';
        $variables['items'][0]['format'] = 'full_html';
        $variables['items'][0]['safe_value'] ='';
        $variables['items'][0]['#markup'] = ' ';
        return $variables;
    }
}

At first  $variables['items'][0]=[]; was producing a bunch of warnings about invalid arguments to core functions regarding children and parents and rendering. Then I cleared drupal cache. The thing is, the field I am replacing is an audio file field. So I think there must be a cleaner way to do this than above. Let me know if you have suggestions!


Make a view content only appear when user is logged in

What I did was quite simple:

Create the view normally, without access restrictions and link it to the menu.
Make sure the nodes themselves can only be seen by logged in users.
Create a No results behavior text that tells users to log in.
Show the login block only on the view's page.


As well as drush_iq, you might consider patch manager.


What MySQL privileges would a read-only drupal db user need

Looking through the core tables of a fairly lean install, these will probably need to be writeable:

access
batch
cache and cache_*
flood
history
node_access
queue
sessions
semaphore
users (for last login date)
watchdog

These I'm not too sure about, worth testing:

registry
registry_file
file_usage
blocked_ips

Contrib modules are different matter, you'll need to look at those one-by-one as it will depend on which ones you use (e.g. ctools has ctools_css_cache and ctools_object_cache)


How to add variables in *.libraries.yml in drupal 8

First add your acobot script inline:

function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with
      // alert("Hello world!");.
      '#value' => 'alert("Hello world!");',
      // Set attributes like src to load a file.
      '#attributes' => array('src' => 'http://js.acobot.com/' . check_plain($token) . '.js'),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world',
  ];
}

next add your library with *.js file where you can call push method

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

and pass user mail to  drupalSettings.

$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'user mail here';

All examples are available here https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


Weird behaviour when customising views-view-unformatted.html.twig with grouping


D8: Unable to set cache max-age on ResourceResponse

The referenced question from 4k4 describes how to disable the internal page cache completely.

To not disable but set an expiration on the anonymous/internal page cache, you can use the Expires header, just set it to a date in the future and that will be respected. That's the only thing that the internal page cache module currently respects.

See the linked core issue for more information, it's partially simply an overlook that it wasn't done before 8.0 but now it would be an API change to start respecting it and lots of things would then make Drupal uncacheable, like the language switcher block. So we'll have to be very careful with any change we make.


Defining a constant via a function provided by another module?

You can use the standard global keyword provided by PHP. This is better placed somewhere early in a page load. One that I can think of is hook_menu or hook_init.

Personally though I would strongly recommend to use the variable_get() function provided by Drupal.


Seems like your breadcrumb is working properly but you get the real path instead of the path alias. You can use drupal_get_path_alias.

$breadcrumb[] = l($title, drupal_get_path_alias('taxonomy/term/'. arg(2)));

Seems like you are setting title and breadcrumb in a .tpl file? Try to avoid that and put your logic in template.php.
Quick tip: views_embed_view can cause performance issues.


View Field Display placing table label on top of the description


The solution was simple: the naming of the regions need to use underscores, not dashes.

In theme.info.yml

regions:
  contact_first: 'Contact (First column)'

In the twig template:

{{ page.contact_first }}


Check out the module "References". It allows you to create a field where you can reference on other content types and nodes.


trying to dynamically change drupal commerce order

Going out on a limb a bit...

There's no function called commerce_new_order, you probably mean commerce_order_new()

Same thing with commerce_load_product() and commerce_product_load()


Change values of user input in hook_field_validate?

Perhaps hook_field_attach_submit can be used in your case?


Is there a way to display basic site statistics in a block?

This is a job for the views module. Using views in its most basic form you could have a block for the below in under 30 secs.

Content statistics: Most recent view

The most recent time the node has been viewed.

Content statistics: Total views

The total number of times the node has been viewed.

Content statistics: Views today

The total number of times the node has been viewed today.

Install views module, add new view, view name = stats, uncheck create a page, check create a block, continue and edit. Add fields and add the 3 above. Remove title. Add a contextual filter under advanced and use Content: nid, provide default value = content ID from url. Get rid of any filter and sort criteria and you should be good to save the view. You will now have a view block that you can place in any region to display this info.

The 5 most visited block would be similar except you would keep the content published filter and add a sort (descending) on Total views. You could use the "Use pager: Display a specified number of items | 5 items" to get a list of the top 5 most viewed nodes.


How to add redirect section to node edit on Drupal 8?

That's not a Drupal 7 feature but one from the redirect module. It partially exists in Drupal 8 as well but only lists the existing redirects, there is an issue open to add the ability to create a new redirect


How to implement a node limit per taxonomy term?

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed in the "blueprint" below.

Step 1

Use the Views and Views Bulk Operations module to create a view of all nodes that have a specific taxonomy term, in which you add a VBO field to it. Simply include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Step 2

Create a Rules Component like so:

Using these Rules Component parameters:

a parameter of data type that matches with the data type of your 'Taxonomy with "limit" field' (probably "integer"), let's assume the parameter has machine name node_limit.
a parameter that matches with the term reference field as defined in your node's content type, let's assume the parameter has machine name node_termreference (which can be either a single value, or it can have multiple values, depending on how you defined it in your content type).

With a Rules Condition "Check number of results returned by a VBO view", whereas:

you select the VBO view created in Step 1.
you want to check if that number of results is greater or equal to  node_limit (which is the 1st parameter used by this Rules Component).

Rules Actions:

Set an appropriate Drupal message (that the node limit for that term has been reached already).
Remove the term that was entered from the node_termreference field (which is the 2nd parameter used by this Rules Component); Which Rules Action to use for doing so depends on how that field is defined, e.g if it is a multi value field, then you should use "remove from list".

Step 3

Create a custom Rule like so:

Rules Events:

Before saving a new node (optionally limited to relevant content types).
Before updating an existing node (optionally limited to relevant content types).

Rules Conditions:

Entity has field, for the field that refers to your taxonomy term (to make this field available for further processing in your subsequent Rules conditions/actions). More specifically we'll need it (as a token) to specify a value for the node_termreference parameter to execute the Rules Component from Step 2 later on.

Rules Actions:

Fetch entity by ID, whereas you fetch the taxonomy term entered in the node being created or updated. By doing so, your 'Taxonomy with "limit" field' will become available as a token in subsequent Rules Actions. More specifically we'll need it (as a token) to specify a value for the node_limit parameter to execute the Rules Component from Step 2 later on.
Execute the Rules Component from Step 2, by passing that Rules Component the appropriate values for node_limit and node_termreference to actually perform its logic.

Done! .... only using (popular) contributed modules, with no custom code involved .... All you need is Rules, Views and Views Bulk Operations.

PS: the above is only a blueprint ... Mostly because your question has not sufficient details. E.g you didn't explain how those terms are defined in your content type).


LDAP Authentication + Drupal Registrations possible issue

If anyone is interested, here are some methods of resolving this:

You can do a force creation of all ldap users before putting your
application into production. Edit I've written a module for this: http://drupal.org/sandbox/mrryanjohnston/1308882
You can require everyone to authenticate with their email addresses.
    This, too, requires a few modules and a little bit of figuring
    out, but it can work. This module is the result of some of those
    efforts: http://drupal.org/sandbox/branana/1300714


Create Famous button in article type with value stored in database

Sounds like you might want the flag module.

You can create a "Famous" flag, where certain roles can flag items and administrators can remove the flag.

It allows you to set the text for flagging and unflagging, so you can have "Make This Famous" or whatever you like.

The only part I'm not sure about off the top of my head is showing who flagged the content as famous.
I'm not sure if there is a setting for that, however there is views integration so you could create a view that shows who has flagged the current node and put it as a block on the page.
Since only one person can make something famous in your system there will only ever be 1 result so you will get what you require.


After moving document root, pages can't be found

Browser cache was the issue.  Resetting the cache made everything go back to normal.


Assuming your theme extends Classy, you can add a menu.html.twig file in your theme to override the menu twig used:

https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21navigation%21menu.html.twig/8.6.x

This block here:

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

Simply add a new line:

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

If your theme does not use Classy as a base, then you have to refer to the Stable theme twig file which does not do this:

https://api.drupal.org/api/drupal/core%21themes%21stable%21templates%21navigation%21menu.html.twig/8.6.x

In this case, you would have to add the set block within the for item in items loop just like the Classy file does, and add addClass(classes) method on the li item:

{%
  set classes = [
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
    'section'
  ]
%}
<li{{ item.attributes.addClass(classes) }}>

This will add the 'section' class on every single li in the menu though, so, if you only want it to apply to the top level menu items for example, you could do:

{%
  set classes = [
    'menu-item',
    item.is_expanded ? 'menu-item--expanded',
    item.is_collapsed ? 'menu-item--collapsed',
    item.in_active_trail ? 'menu-item--active-trail',
    menu_level == 0 ? 'section'
  ]
%}

Additionally, if you only want this to apply to a particular menu and not all menus, then your Twig file needs to be named menu--MENU_NAME.html.twig. Clear caches to see any changes.


Drush not being found although installed [ubuntu 11.04]

Your problem is probably that Drush is not in your $PATH.  I did not try to install Drush-4.4 from Synaptic to test whether or not this is the case; instead, I would recommend that you install Drush via PEAR following the instructions on the Drush project page.  If you do this, your $PATH will be set, Drush will be found, and better yet, you'll be able to use the much-improved Drush-5.1 instead of the out-of-date Drush-4.4.

Edit: By "Dash Home", do you mean that you are trying to type "drush" into the Unity Heads-Up Display?  If so, instead run "terminal" from HUD, and then type "drush status" from the terminal prompt.  Then you should be good to go.  I'd still recommend installing 5.1 via PEAR.


Why Conditional Fields Validating the Hidden Fields?

Check that your measurements field isn't set as required in the field settings in content types. You could also provide a default of 0 I guess.


I created a ticket for this issue in the Webform module's issue queue and fixed the problem.

The best solution was to convert the placeholder input from a text field to a textarea so that you can now enter multiple lines of text as the textarea's placeholder.


How can i increase the size of color box pop up window in drupal 7. .?

You should probably check the settings at

admin/config/media/colorbox

If the issue is that the image is too small then you need to change the Image style to a different one or perhaps make a new one.

If you want to make the Colorbox larger you can use the Custom options on that same configuration page and set your own defaults for size. The Colorbox module should allow you to specify

initial width
initial height
max width
max height

If you choose Custom under the Options setting.


Drupal site menu overlay stuck in Chrome Browser when scrolling down

Hard to say without being able to inspect it, the z-index on #header won't work unless position is set to something other than static (the default value).

Try setting #header to be position: relative; or position: absolute; whichever is more appropriate and see if that helps, or at least helps narrow down the problem.


How can I track all Flagging/Unflagging history for statistics?

Yes there is a way ... using a combination of these (commonly used) modules:

Rules
Message
Views

Long story short:

Create a "Message Type" that you'll use for creating some type of custom logging (for the events you're asking about).
Use the Rules module to capture the events, with rules actions to create appropriate messages (= records in your custom log).
Use the Views module to browse the messages that got created.

For a variation of your question, where a similar technique can be used, refer to my answer to "Is there a way to send emails when someone logs in?".

PS: this answer applies to D7 ...


Adding a class to select options from Views Exposed Filters

Normally this would be accomplished with hook_form_alter, but sadly Drupal 6 doesn't support attributes in the options Form API element, which means you can't add any classes to it.

You're going to have to do this with Javascript. :-(

You can't start with something like this:

  $('.view-NAME_OF_YOUR_VIEW .views-exposed-widget option').each(function(index) {
    $(this).addClass($(this).val());
  });

This will get you

<option value="Liverpool" class="Liverpool">Liverpool</option>

I know it's not perfect, but sadly that's probably the simplest route.


It's hard-coded into template_preprocess_node() so to override it you'll need to implement your own preprocess function, either in a theme or custom module:

function MYTHEME_preprocess_node(&$vars) {
  if (variable_get('node_submitted_' . $vars['node']->type, TRUE)) {
    $date = format_date($vars['node']->created, 'date_type');
    $vars['submitted'] = t('Submitted by !username on !datetime', array('!username' => $vars['name'], '!datetime' => $date));
  }
}


How to write custom access for a route which redirects the user to another route if a condition is true

The issue if you click/visit example.route it automatically redirects to example.route.two is caused by the access method not only called when you visit example.route.one, but also on other pages with links pointing to example.route.one, for example in a menu.
So use access methods only for calculating access results. If this then results in a 403 you can catch it in an event subscriber and set a redirect response instead of the default 403 message.
See Dynamically change the "access denied page" title and body.


Set value in $form_state['storage'] seems to change before validation

I don't like the cache method as it is quite complicated. If cache method is the only way to do that. I would recommend using Session Cache API.

In this case, exposing the answer to the form and collecting it from $form_state['input'] would be my choice.

function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];

  $number1 = rand(0, 10);
  $number2 = rand(0, 10);
  $form['numbercheck'] = array(
    '#type' => 'textfield',
    '#title' => 'Please fill in the sum of '. $number1 .' and '. $number2,
    '#required' => TRUE,
  );

  // hidden field is only hidden to user but you still can inspect it
  // from source. So hash function is used to encrypt here.
  $form['checksum'] = array(
    '#type' => 'hidden',
    '#value' => isset($input['checksum']) ? $input['checksum'] : hash('sha256', $number1 + $number2),
  );

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

  return $form;
}

function mymodule_custom_form_validate(&$form, &$form_state) {
  $hash = hash('sha256', $form_state['values']['numbercheck']);

  // compare the hash result.
  if ($form_state['values']['checksum'] != $hash) {
    form_set_error('numbercheck', 'The sum was not correct');
  }
}


How to correct my rule to update user info on login using HybridAuth?

Some more details about the errors you encountered:

Data selector user:hybridauth:profileURL for parameter data is invalid.

Using the Rules Event like you're using, there doesn't seem to be something like user:hybridauth:profileURL, which I believe explains this error.
The selected data property doesn't support writing.

To understand the reason for this error, have a look at:

The question about "How to fix entity property X doesn't support writing, when setting content type field values?".
The Rules issue titled "The selected data property doesn't support writing." when Action: Set a data value is applied to a taxonomy field:tid.

With that, I'm fairly sure that the answer to the "Is it even possible"-part of your question is:

  I'm afraid it is NOT ... Though I'd love to see anybody tell me I'm wrong.


Get node ID that field belongs, in field.tpl.php being displayed in a block on any page

Found my solution!
I was trying to access the node id from the field.tpl.php template because I wanted to add a CSS ID (using the node id) to the field outer wrapper (a div). Which was in this field template.

What I ended up doing was removing this div wrapper from the field template, and just adding the CSS id to the div wrapper in the node.tpl.php template.

Since I only needed this CSS id in certain a view mode, I created a node template for my specific view mode.


How to display devel dpm messages on a panels generated page?

Put the code inside panels-pane.tpl.php file which is responsible for printing panel pane.
You can find this on Panels directory but you should better copy this into your theme folder and do there any modifications.


HTML comment based tokens in hook_views_post_render()

It is being stripped -- rewritten views field output still gets run through filter_xss_admin(), which strips out any HTML tag-like construct that isn't in the default allowed_tags list.

Instead of using a <!--something--> format, try using [SOMETHING] instead.


You can choose the target language, see more information in the API.

In code it would look like this.

$variables['string_in_spanish'] = t(
  'Hello World',
  [], // (The args in the string)
  ['langcode' => 'es'] //  The options
);

note that when using the t() function, the source language has to be English.


Two domains pointed at the same site, can't log in to one of them

I had this issue before. It is related to the cookie setting, try doing this:

<?php
if (isset($_SERVER['HTTP_HOST']) && substr_count($_SERVER['HTTP_HOST'], 'parentdomain.com') > 0) {
$cookie_domain = '.parentdomain.com';
}
?>


How to use Font-your-face fonts with CKEditor?

This looks like a long awaited and unanswered issue - https://www.drupal.org/node/1234030 - however I have found a page that describes how you can manually updated your CKEditor fonts list.

http://www.zyxware.com/articles/3692/drupal-how-to-add-fonts-in-ck-editor

I think this seems a bit too much, you would think that there would be a better system in place to support more fonts dynamically. There are apparently some hooks with the WYSIWYG module and Font Your Face - however as far as my knowledge goes CKEditor works better on it's own than as a part of WYSIWYG.


How to add "Size" option in my Commerce Product without adding lot of SKU that differs by size?

You're going to create 5 option set.

White with sizes
Blue with sizes
Green with sizes
Orange with sizes
Yellow with sizes

Each Option set create you created insert your size field (list type)

On your Shirt product type or whatever your product type is, create your sizes option set reference field

So when you create your 5 SKU you're going to choose which option set the user is going to use.

For Example:

Woman's T-Shirt WHITE (PRODUCT)
Option set reference:"White with    sizes"


Display user role with the Advanced forum module

In advanced forum module edit advf-author-pane.tpl.php in your chosen forum theme and and below print $account_name; you'll need a similar line like print implode(', ', $account['roles'];. It should be wrapped in some HTML tag (span, p, ...) so you can style its display.


How to set value to auto-complete field after form submission?

Finally I found the solution myself. I simply got a value from URL like this:

'#default_value' => (arg(3)!= 'none') ? arg(3) : '',


How to get constant string array field into db_query?

Not sure if this is a bug or not (I've seen weird things with single and double quote in PDO queries before), but either way you can work around it by using single quotes to wrap the expression:

$sql = "SELECT '\'a\',\'b\'' AS FieldStrArray";
$val = db_query($sql)->fetchField();
// $val == "'a','b'"


Payments and user balances/virtual coins

Yes, Userpoints should work for this, with one major exception: It doesn't support decimal values. There are patches available for both D6 and D7 but you're pretty much on your own when using them.

There is integration with Ubercart available for D6 and Commerce for D7 (http://drupal.org/project/commerce_userpoints) which allows you to buy points with money. There are also modules available in the Userpoints Contrib project for requiring points to create nodes, which you can combine with Userpoints Nodes and Comments to remove points when a node is created, resulting in the ability to sell creation of nodes. And, there is Userpoints Node access, http://drupal.org/project/Userpoints_nodeaccess, which allows to buy access to nodes (only the D7 version works).

In general, the D6 versions of the modules aren't well maintained, especially the modules in Userpoints Contrib are very unstable (while those ported to D7 should work pretty fine).

Disclaimer: I am the Userpoints D7 maintainer and might be biased.


How to render complete page when overriding page--node--add--typename.tpl.php

I think you  would need to return the form, not print it.

return drupal_render($form);

Printing from a function will cease the theme engine which would cause the other parts of the page not rendered.


Form submit POST renders page before submit handler is called

You need to add a submit callback that will handle the redirect:

 $form['#submit'][] = 'mymodule_search_callback'

And in that callback:

function mymodule_search_callback() {
   $form_state['redirect'] = current_path() . and your urlencoded serch term;
}

Messing with $form['#action'] is not the right way to do it.


How to resolve error 'migration_group' entity with ID 'migrate_drupal_7' already exists?

you can delete existing migration groups from: /admin/structure/migrate


How to send emails to 20,000 + registered members efficiently?

Below is a summary of how you can improve what you already have in place ...

Part 1 - Use a flag to keep track of the progress

Introduce an additional flag to allow "flagging" of some new or updated "entity" (eg "nodes") by all users "which you need to email all at once" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).

This of course assumes your eMails are to be triggered by such new or updated entities. But if you don't have such entities (= you have another reason to send such eMails), you could introduce a dedicated content type and use it as a kind of eMail template (with fields up to your own imagination). And each time you have a new eMail to be delivered, just create an appropriate node (of this dedicated content type) for it.
Create a rule to flag the newly saved (or updated) content, using the new flag (from step 1) for each of the users you already have in your existing "a view to select all the users on the site".
Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged nodes (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first X users only (pick a value for X that fits your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

eMail each of the users in that VBO list (you can probably reuse the Rule to "send an eMail" that you already have).
unflag (using flag from step 1) the node (for the user for which you just produced an eMail). This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within Y minutes or hours  (pick a value for Y that fits your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every Y minutes (or hours), Rules will eMail X users "as requested".

Part 2 - Recovering from an error

Sooner or later, Mr. Murphy will come along again, and it might cause some error again (eg after a few thousand users). If that happens, all that's needed is to repeat Step 5 ... And even if you didn't realize the error at first (only after X hours or days or so), all that's needed is to repeat step 5 as soon as the error got noticed.


Dynamic language negotiation by multiple top level domains

This sounds to me like the perfect use case for environment specific configuration. No runtime changes required. Just like you would swap the email addresses in your environments that are used to send emails and would swap the API keys in dev/test environments, you would swap this configuration there as well. You could use something like https://www.drupal.org/project/config_split for example.


Alphabetical view sorting in multilingual site not working for translated content

I solved that by adding this field as a relationship to the view and so name:field became accessible as sort criteria, which I then chose instead of content:field.


Moving file structure and documents from Static site to Drupal

What you could have done is use the Migrate module. It allows you to read from various sources (db, files, csv, etc.) and feed them to Drupal (db, files, csv, etc). It's essentially just a pipeline of read->process->save.

What I would do is create 2 migrations, one for the files and one for the pages. You migrate files first which essentially just tells Drupal they exist by creating records of them in the DB and where they are. During migration, Migrate creates a mapping table which tracks the source id (module-generated, you decide, usually by filename or hash) and destination id (entity id) of the content.

Then you migrate the pages. Migrate allows you to do processing on content before it gets saved to Drupal. Using the data from the mapping done in the file migration earlier (the entity ids), you simply need to look for the urls in the page content, use it to find the id Drupal assigned to it when it was migrated (there are APIs for this), generate a url from that ID, and replace the url in the content.

Migration is easier done than said actually.
This section extensively explains how to use Migrate. In addition, check out Migrate Extras and Migrate D2D as additional tools. Also, the Migrate module itself has examples in the source code which you can check out. And... a lot of trial and error.


Views filter of date - complicated relative format

There's no need for views_between_dates_filter for this use-case.  You might consider turning on the date_views module because it provides some niceties, but if you're using core date properties (like Post Date or Updated Date) then you don't even need that.  Just add 2 filters to your view:

One set to only show content where the date field is greater than or
equal to your specific desired start date (2015-05-01 00:00:00 for
instance)
One set to only show content where the date field is less
than or equal to your specific desired end date (2016-04-30 23:59:59 for
instance).

You don't need relative dates at all since you're setting up distinct views for each year.


Find out if a view returns any results and if it doesn't disable a link to that view

The one solution is hide empty terms. You can hide empty terms as shown here

Another solution is use php in your view or views template, use taxonomy_select_nodes function.

  Return nodes attached to a term across all field instances.

The tid can get from view. If the function return empty , dont provide link for that term.

Otherwise you can link term to your second view.


Selecting the taxonomy terms to use using a textfield to search them

You can try using Views to build a custom search with exposed forms. And the use the fields to display terms the way you need it. That is probably the easiest.


Language switcher links are hidden for anonymous users

After installing your module, I can confirm the behavior that you're seeing.

When I change the route to <front> I am able to see the links as anonymous.

What I know is that the menu system automatically checks if the user has access or permission before it displays the links.

So my first thought is there must be a Core bug with this <current> route.

When I check /core/modules/system/system.routing.yml all I see is:

'<current>':
  path: '<current>'

Which is interesting that this route doesn't have an access nor a permission key.

In /admin/people/permissions if I check this permission:

  Link to any page

  Warning: Give to trusted roles only; this permission has security implications. This allows to bypass access checking when linking to
  internal paths.

I can see the links as anonymous, but obivously we do not want to this.

When I try to add <current> via the UI, I cannot; even though, <front> is acceptable.

Therefore, my best educated guess, seems to me that the <current> route is not designed to be used in Menu links because it doesn't have an access key nor permission key. Also, this might explain why the language switcher is a block and not a menu link.

However, there is work around for this if you pro-grammatically print the menu and not perform an access check, but there is a caveat. You would have to make sure there is no link in this menu that anonymous is not suppose to see.

As per code provided in Menu system, "Rendering" section, comment out the access check part.

Example:

    $menu_tree = \Drupal::menuTree();
    $menu_name = 'MENUNAME';

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree
      ->getCurrentRouteMenuTreeParameters($menu_name);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree
      ->load($menu_name, $parameters);

    // Transform the tree using the manipulators you want.
    $manipulators = array(
//    // Only show links that are accessible for the current user.
//    array(
//      'callable' => 'menu.default_tree_manipulators:checkAccess',
//    ),
      // Use the default sorting of menu links.
      array(
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ),
    );
    $tree = $menu_tree
      ->transform($tree, $manipulators);

    // Finally, build a renderable array from the transformed tree.
    $menu = $menu_tree
      ->build($tree);
    $menu_html = drupal_render($menu);

    print $menu_html; // print the menu

If the above does not suffice, because of the caveat, you might want to look into

  Potentially write a custom menu tree manipulator, see
  \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators for examples. This
  is only necessary if you want to do things like adding extra metadata
  to rendered links to display icons next to them.

  source: Menu System

I believe here you will be able to target specifically the language menu links and make Drupal skip the access check only on those specific language links which would be the best solution.


Create your view as a content pane instead of a page. Then on your panel insert the content pane. You can also look at something like http://drupal.org/project/panels_everywhere as a more general solution.


referenced entity not showing up in the node view page or in any view I create

I just Googled the same issue and was led to this page.

You need to implement an access callback in hook_entity_info(), else the entity reference field won't load the entity.


How to add a new tab to user profile in administration?

If this is for Drupal 7, you should take a look at the profile2 module. It allows you to create a profile entity where you can add any fields. It also creates tabs on the user page via permissions.

In general to create tabs, you need to create menu local items. Views 3 support this, and it is also possible to create such a tab with hook_menu by setting the type to MENU_LOCAL_TASK. There are some requirements to the path of the url to make this work, but this is all well documented at the drupal API reference, linked to above.


If you have drush installed, you can reset your password from the command line using

drush upwd --password="givememypasswordback" admin

For more information you could see the link.


How can I display multiple taxonomy terms on a node?

If you want a product to show up in multiple categories you simply enter all terms from the category vocabulary in the product edit mode. The hierarchy you need to  build up in the menu system not in the vocabulary.


Override Another module's Template file using my Custom Module (Drupal 7)

I had to use the following snippet to get it to work. I think it may be due to the way I set up the original template.

<?php
//  unset the original template to set yours.

// Implement hook_theme_registry_alter
function MODULENAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['TEMPLATE_TO_OVERRIDE']['template'] = drupal_get_path('module', 'MODULENAME') . '/TEMPLATE_TO_OVERRIDE';
  $theme_registry['TEMPLATE_TO_OVERRIDE']['theme path'] = drupal_get_path('module', 'MODULENAME');

}


Unable to retrieve uploaded file in submit handler

All what '#type' => 'file' form elements do is to provide a bare <input type="file"> element. You get a prompt to select a file from your machine and on form submit the browser sends a request to your server, server forwards it to PHP, PHP extracts the file from the request, PHP stores it to the server's temp dir and when the script ends it deletes it again. Not much Drupal involved.

If you need to handle the file somehow and be it just the filename you need to take care of it yourself. And that's what file_save_upload() is for. It expects the $form_field_name as first parameter. And it will return you the file information. When scanning core for '#type' => 'file' you will often see this function being used in the form validation handler. Where the return value is being passed back to $form_state. For example in \Drupal\system\Form\ThemeSettingsForm::validateForm(). Just this time the function is wrapped from _file_save_upload_from_form() to allow correct error handling in forms.

// Check for a new uploaded logo.
if (isset($form['logo'])) {
  $file = _file_save_upload_from_form($form['logo']['settings']['logo_upload'], $form_state, 0);
  if ($file) {
    // Put the temporary file in form_values so we can save it on submit.
    $form_state->setValue('logo_upload', $file);
  }
}


You have two options:

function spin_menu() {
  $items = array();

  $items['spin/login'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
  );

  $items['spin/login/%'] = array(
    'title' => 'SPIN',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE,
    'page callback' => 'spin_check_access',
    'page arguments' => array(2),
  );

  return $items;
}

Hook menu will not send any wildcard params to the callback function, but it will send params not defined in the url. So in the first example if you go to spin/login type will be '' and spin/login/foo type will be foo. For the second example spin/login will return 404 and for spin/login/foo type will be foo.


While you could technically do this by implementing a hook_form_alter, to capture and overwrite the submit handler, if you're already using the Apache Solr Views module, you'd be better off creating an exposed filter, setting the exposed filters to display in a block, and then using that instead of the default search form block. You can do that without custom code.


custom search in drupal for custom content type page

As far as I understand you made 80% of the way.
I think you can do the following:

Add contextual filter to your view so you will be able to filter to results according to the zip code
Use your custom module (if you don't have one, this will be a good time to create one) to define a custom block (use the following hooks - hook_block_info and hook_block_view)
Create a custom form that will contain the search box and the submit button
Make a custom submit handler that takes the field value (the zip code inserted by the user) and loads the views page with the inserted zip code (the contextual filter we defined in step 1 will allow it)
Place the form in your custom block and place that sweet block in your homepage

References:
Create custom form

Edit:
By the way, the first comment is exactly what you need.

   function my_module_my_form_submit($form, &$form_state) {
    $first_name = $form_state['values']['first'];
    $last_name = $form_state['values']['last'];
    drupal_goto("/my_view/".$first_name."/".$last_name);
}

Hope that helps..
Rotem


Rules sends email to mailto link instead of email address

Click the button that says "Switch to Data Selection" and choose the Data Selector corresponding to your email field, not the Replacement Pattern.

That way the Rules module will send the email to the actual email address, instead of to the 'mailto:'-link.


Can't get url from internal uri in twig template file

You can try to do like this

{{ content.field_link.0['#url'] }}

That should do it.

This is another possible way of diong it

{{paragraph.field_link.uri }}


How to make custom content type as product in ubercart drupal 7?

Go to http://mysite.com/admin/store/products/classes
Enter the machine name of your content type in the 'Class ID' text field.
Enter a human-readable name for your new product class (and optional description)
Click save

Ubercart will now register the content type with the machine name that you added in the above steps as a product. Next time you add/edit content of that type you will see all of the Ubercart fields in the edit form.


Bootstrap.inc error appearing on website

The problem seems to be that views_handler_filter_node_language.inc was moved from views/modules/translation to views/modules/locale. I guess you have updated the views module but not rebuilt you registry.
You should be able to solve this by flushing the cache. Here's a issue, addressing the same problem.

Notice that whenever you update a module you should also call the update script located at example.com/update.php.

To flush the cache using drush use the following syntax: drush cc all.

You could also try to clear the cache_bootstrap table using:

mysql -uusername -ppassword -hhostname database -e"DELETE FROM cache_bootstrap WHERE cid='system_list';"`

or

drush sql-query "DELETE FROM cache_bootstrap WHERE cid='system_list';"

Backup your database before trying the above

If you still have trouble, you could also try to disable the views module using something like this:

mysql -uusername -ppassword -hhostname database -e"UPDATE system SET status='0' WHERE name='views';"

or

drush dis views

You might need to clear the cache as in the previous step for this to take effect.

Here you can find more information about disabling a module manually: Disabling modules manually in the database


Hide comments on a node type for standard users

You could make a module that uses hook_comment_load() to do that user role check.

https://api.drupal.org/api/drupal/modules%21comment%21comment.api.php/function/hook_comment_load/7


Show a block if the page content has a specific taxonomy term

You need to add two contextual filters to your view block:

Important: Use this block (override) for all these settings.

Content: Nid

Provide default value: Content ID from URL

More:check: exclude.

This contextual filter will exclude Brand X from the list if you're visiting Brand X page.

Content: Has taxonomy term ID

Provide default value: Taxonomy term ID from URL

check:  Load default filter from node page, that's good for related taxonomy blocks.

When the filter value IS available or a default is provided:

Override title: Type here your block title using %1 for the first argument, %2 for the second, etc.

This contextual filter will list all your brands from current visited Product type


With the BinaryFileResponse class, you can return the content of a file in the response. The FileDownloadController class is an example of controller returning the content of a file. It's the controller for /system/files/{scheme}, /system/files/{filepath}, and /system/temporary.
See its FileDownloadController::download() method.

public function download(Request $request, $scheme = 'private') {
  $target = $request->query
    ->get('file');

  // Merge remaining path arguments into relative file path.
  $uri = $scheme . '://' . $target;
  if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {

    // Let other modules provide headers and controls access to the file.
    $headers = $this
      ->moduleHandler()
      ->invokeAll('file_download', [
      $uri,
    ]);
    foreach ($headers as $result) {
      if ($result == -1) {
        throw new AccessDeniedHttpException();
      }
    }
    if (count($headers)) {

      // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
      // sets response as not cacheable if the Cache-Control header is not
      // already modified. We pass in FALSE for non-private schemes for the
      // $public parameter to make sure we don't change the headers.
      return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
    }
    throw new AccessDeniedHttpException();
  }
  throw new NotFoundHttpException();
}

The ExportForm class is another example of how to return a file, even if it's a form class. What changes is how the response is used, but how the BinaryFileResponse class is used is still relevant for a controller.
The relevant code is the following one, in ExportForm::submitForm().

$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);


REST API POST: User is not authorized despite being admin

My problem was that the Basic Auth module was not enabled. I only found that out by chance as I was scrolling through the enabled modules, as the error message above didn't indicate how authentication was being done.


How do I give a user limited access to theme settings?

You could do that with hook_menu_alter to change the access callback on your theme settings page.

e.g,

/**
 * Implements hook_menu_alter
 */
function mymodule_menu_alter(&$items){
  $items['admin/appearance/settings/my_theme']['access callback'] = 'user_access';
  $items['admin/appearance/settings/my_theme']['access arguments'] = array('administer nodes');
}

You can also add your own access callback and return TRUE or FALSE depending on more custom user access rights access there.

See system_menu for the core 'admin/appearance/settings/' . $theme->name menu definition


How to configure list page/detail page view?

You don't need a URL argument for this. You can make the View path 'articles' and give it the following:

Filter by content type = article
Filter by status = published
Sort by created date, descending
Enable pager

That will give you a basic View listing articles, paged out, in descending order, on the url "articles".


If you add a relationship in the View definition (Third column of the view input form), and select the Content:author from the dialog, you have created a link in the view that exposes data regarding the author. This will give you access to more fields that can be displayed in your view.

Check out the video series, "Taming the Beast" at nodeone.se to get a better understanding of what Views can do.


try to change '#type' => 'button' to '#type' =>'submit' and then implement hook_form_submit()


Since views are dynamic lists of content, you don't directly translate the view. Rather, you make the view select content of the current user's language. This can be done using the i18n module, and the i18n views module.

Once you have these installed, you add a filter to your view, under the node translation group.


Is site safe after a failed module installation?

Generally, it isn't. It may be, but it depends what's in module's hook_install.

First, most modules provide schema. The code of drupal_install_schema in 7 is currently:

function drupal_install_schema($module) {
  $schema = drupal_get_schema_unprocessed($module);
  _drupal_schema_initialize($schema, $module, FALSE);

  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
}

As you can see, no call to db_translation, and each table is created one at a time. Now, if module only provides own schema, you are left with some garbage in database, but it's a well isolated garbage. But if it implements hook_schema_alter it's pretty possible you are left with some tables already altered, bu no code to handle these alterations. Now, in theory installing schema should never fail with PDO error, but due to RDBMS configuration for example, it may happen.

Second problem is that module's author can write pretty much anything in it's install code, and you are not guaranteed it will get rolled back at failed install. If he decides his module needs to change variables provided by core or other modules (for example to allow apparent conditional content, like with translated variables), or if it redefines some fields to provide additional functionality, you may end up with some of your data converted to module's format, and no longer accessible without it, or without running code meant to uninstall it.

Note: Situations above from experience. Even if I miss some theoretical part that should make them impossible to happen, they both did happened to me in real life. With -dev versions, but module version depends solely on it's author, so there is no guarantee that it will not happen in stable versions some day, too.


Views REST Export and Multi-Value Fields

This looks like it's a plain bug. Please report it to the views.module issue queue in Drupal core: https://drupal.org/project/issues/drupal?component=views.module.


I have found, that the problem was caused, that in the setUp() method of the test class, was at first used the $this->drupalCreateNode([...]) method and then were created the settings. After moving the $config->set(...) method at the beginning of the setUp() method, works everything perfect.

See:

The test class
Test results


You can replace the default cache backend to one which does not actually do anything.
Simply add this to your settings.php file:

if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
// Default to throwing away cache data.
$conf['cache_default_class'] = 'DrupalFakeCache';
// Rely on the DB cache for form caching - otherwise forms fail.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

Just to be sure, set the cache expiration time to none on the Performance page.

I actually use this in a settings.local.php file which, if it exists, gets included at the bottom of my settings.php file so I can sync settings.php from the live or staging environments to my dev environment without having to worry about using the wrong database settings, accidentally pushing dev settings to live, etc.

settings.php:

if (file_exists(__DIR__ . '/settings.local.php')) {
  require_once __DIR__ . '/settings.local.php';
}


drush/drush dev-master requires codegyre/robo ~1.0.0-beta1

The dev/master branch of Drush is a development release, so it depends on non-stable components such as Robo 1.0.0-beta1. Composer will reject this component unless you have "minimum-stability": "beta" in your composer.json file.  Note that Drush itself has this setting, but if you include Drush from some other project (e.g. your Drupal site), then you will also need to set your minimum-stability in your project's top-level composer.json file.

Perhaps a more reasonable solution would be to run composer require drush/drush:~8, and use the stable release of Drush.

UPDATE

Drush master is now using the stable release of Robo ~1, so it should be easier to install Drush via composer require, at least for the time being. It is always possible that at some point in the future, though, the dev version of Drush may become dependent on features only available in some non-stable release of one of its dependencies, so you should always be prepared to set your minimum stability when requiring a dev version of Drush -- or any other Composer project.