How to display a Views block based on the current page?

Suppose there are two views

views 1 url is - http://example.com/my-rooms

views 2 url is - http://example.com/my-activities

There are two blocks -

a) banner-rooms

b) banner-activities

On the block configuration page, You need to set the visibility setting of the block for specific pages.

=>Under Visibility setting, Select the tab "Pages"

=>Select the option - "only on the listed pages"

In the text-area, fill the urls e.g- banner-rooms


hook alter normally works on contrib modules. I can see the reason why it has not been working is due to fact that the module needs to be altered got more priority than the altering module.

To overcome such scenario you need to manually change the priority of your custom module, this can be done by changing the value of weight column in system table.


Concept of services, tags, and arguments

1. Database

redirect.repository communicates with the database through its usage of the class represented by the database service injected into its initialize method (__construct). However the RedirectRepository class does not itself use PDO to connect to the database.

The redirect module has chosen not to implement an entity to store its data, and is an example of using Drupal's database abstraction layer (DBAL) from the database service.

// Load redirects by hash. A direct query is used to improve performance.
$rid = $this->connection
  ->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])
  ->fetchField();

2. Entity Manager

The entity.manager service provides a deprecated helper class to make it easier to get information about entities only. If you do not implement an entity, then you cannot use any of the entity-related services such as entity.manager or entity_type.manager.

3. Dependency Injection Tags

  Dependency Injection Tags are little strings that can be applied to a
  service to "flag" it to be used in some special way. For example, if
  you have a service that you would like to register as a listener to
  one of Symfony's core events, you can flag it with the
  kernel.event_listener tag.

Tags are treated specially so that when the service container is "compiled" certain classes may be able to make a second "compiler pass" and act on services that are tagged.

See the Symfony2 documentation for more details about compiler passes: http://symfony.com/doc/current/components/dependency_injection/compilation.html#components-di-separate-compiler-passes


How do I place content in a user-profile.tpl.php, based on whether a boolean field is true?

You shouldn't access data that way, especially in template files as it's the raw data.

You should use the functions field_get_items & field_view_value


How to programmatically create an image style?

You're looking for the image_style_save and image_effect_save functions.
An example from the comments on the image_style_save docs page:
$style = image_style_save(array('name' => 'avatar'));
$effect = array(
  'name' => 'image_scale',
  'data' => array(
    'width' => 64,
    'height' => 64,
    'upscale' => TRUE,
  ),
  'isid' => $style['isid'],
);
image_effect_save($effect);


Is it possible to manage Drupal running on a Windows server using drush on linux via a Samba mount?

In your case, 'os' => 'Linux'.  This variable tells Drush how to do things such as filesystem path escaping.  As you supposed, this variable is primarily used during remote calls, but I believe it may occasionally be referenced when building commands that are used locally.

I have never tried to set up Drush as you describe above; in theory, it should be possible, as long as you can connect to the database, but you might run into some problems.  Post issues in the Drush issue queue if you find bugs.  PRs with fixes would be particularly welcome.


D7 - Commerce Stock - Track products in different unit (e.g. grams?)

One way of achieving this is to let Commerce Stock behave in its usual way, but to override the output on user interface, which should be pretty easy using the right hook. In other words, the custom code could just multiple stock quantity by 10 and, for example, instead of 1 output 10. So total 10 items would become 100 instead, if one item purchased then it would subtract just 1 on backend to output the remaining 9, but your function would just output 90 instead.


Since this is 2014 you're probably looking for the placeholder attribute, and not an old-school javascript solution.

Broad strokes: Implement hook_form_alter() and add the attribute there:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'foo') {
    $form['bar']['#attributes']['placeholder'] = t('Baz');
  }
}


How can i edit a content types taxonomy terms trough the front end

You could take a look at the flag module (not ready for D8 yet)

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

https://www.drupal.org/project/issues/search/flag?project_issue_followers=&status%5B%5D=Open&issue_tags_op=%3D&issue_tags=beta+blocker


Twitter Cards with Metatag module not working

If you´re using the 7.x-1.0-Beta4 version of metatag module (which is the most recent one at the time of writing this answer), you may want to apply the following patch:

http://drupal.org/node/1846978#comment-6764558

(for Unix-like systems only) For applying the patch, just go to a terminal, change the working directory to the directory of the metatag module and try this:

curl http://drupal.org/files/metatag-fix_theme_hook_mismatch-1846978-0.patch | patch -p1


In theblock_contents you are trying to return php code. Don't. Do not echo or print in it. If anything, build a string. It should look about like that:

/**
* custom html block
* @return string
*/
function theblock_contents() {
  $dbserver="serveradress";
  $dblogin="username";
  $dbpass="dbpassword";
  $dbname="databaseserver";

  $result = '';

  mysql_connect($dbserver, $dblogin, $dbpass);
                mysql_select_db($dbname);
                mysql_query("SET NAMES 'utf8'");

  $vypis =  mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') AND (pvpkills > '0') order by pvpkills desc LIMIT 20");
  $result .= '

Nick		Kills
';
  while($row = mysql_fetch_array($vypis))
  {
    $result .= '
';
    $result .= $row["char_name"];
    $result .= '	&nbsp;&nbsp;	';
    $result .= $row["pvpkills"];
    $result .= '
';
  }
  $result .= '
';
  return $result;
}

It's worth to mention that your code was plainly invalid PHP, no matter if it was supposed to run in Drupal or not. You can't simply return PHP code as string and hope it'll be executed. Only the part about not using echo in hooks is really Drupal dependent.

Important note: if you want your modules to work stable, please don't use PHP SQL functions directly. Use db_select to obtain data. Connecting to multiple databases is pretty well documented too.


How to use some code only in the template of selected content types?

Typo:

if ($variables['node']->type = 'home_page'){

change it into:

if ($variables['node']->type == 'home_page'){


Setup on GoDaddy / Addon Domain "403 Forbidden Access Error"

Solved## Successful installation completed :)
When setting the Directory Root for the "multisite" SiteY.com addon domain, I got it wrong.
Incorrect: home/.../public_html/xxxxx.com/sites/siteY.com

Correct: home/.../public_html/xxxxx.com/

With the correct option, you point to the site that contains the code based you want to pull from, as well as the index.php file.
I don't fully get the mechanics at play here, but am thankful to be on the other side.


Combination of AJAX Views and infinite pager

You can try this -

On your page template where you want to load this view use following sample code (with your view specific values such as arguments etc.) which will add all the required JS to your page -

$view = views_get_view('books');
$view->set_display('page');
$view->set_use_ajax(TRUE);
$view->set_arguments(array($tid));
$settings = array(
    'views' => array(
        'ajax_path' => url('views/ajax'),
        'ajaxViews' => array(
            array(
                'view_name' => $view->name,
                'view_display_id' => $view->current_display,
                'view_args' => check_plain(implode('/', $view->args)),
                'view_path' => check_plain($_GET['q']),
                'view_base_path' => $view->get_path(),
                'view_dom_id' => 1,
                'pager_element' => $view->pager['element'],
            ),
        ),
    ),
);
drupal_add_js($settings, 'setting');
views_add_js('ajax_view');

In your JavaScript code use Drupal.attachBehaviors() which will attach Infinite Scroll to your View's HTML -

jQuery.ajax({
    url: Drupal.settings.basePath + "/views/ajax",
    type: "post",
    data: {
        view_name: "books",
        view_display_id: "page", //your display id
        view_args: identifier, // your views arguments
    },
    dataType: "json",
    success: function (response) {
        if (response[1] !== undefined) {
            jQuery("#bloque-" + identifier).html(response[1].data);
        }
        Drupal.attachBehaviors();
    }
});


Restrict users to view custom form(s) without complete other formalities

Check the referring page using $_SERVER['HTTP_REFERER'] if it doesn't match the previous page either throw an error or redirect him to the first page.


Is there a node hook that runs AFTER a node is fully inserted into the database?

There isn't a hook that is called after the transaction is completed, as the code node_save() executes is executed during the transaction.

function node_save($node) {
  $transaction = db_transaction();

  try {

    // ...

  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('node', $e);
    throw $e;
  }
}

If node_save() is called from node_form_submit() (the form submission handler for the node form), you can add a form submission handler that is called after that. It would be executed after the node is saved in the database.

What the documentation for hook_node_insert() means is that, since the data are not still saved in the database table, you cannot query a table making a join with the "node" table, as that table still contains the old data; in the same way, you should not call a function that queries the "node" table.


Why doesn't my custom OutboundPathProcessorInterface work anymore?

That's the right code of the processOutbound method
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

if (isset($options['entity']) && is_object($options['entity']) && method_exists($options['entity'], 'hasField')) {
  $node = $options['entity'];

  if ($node->hasField('field_project_url') && !$node->field_project_url->isEmpty()) {
    $project_url = $node->field_project_url->getValue();

    if (preg_match("/^\/node\/[0-9]+\/(edit|translate|delete|translations)$/i", $path)) {
      // dont alter operational paths
    }
    else {
      $path = ''; //Don't use $path variable at all

      dpm($project_url[0]['uri']); // 'http://url.com'
      $options['base_url'] = $project_url[0]['uri']; //Add your url as base_url

    }

    if ($bubbleable_metadata) {
      $bubbleable_metadata->addCacheableDependency($node);
    }
  }
}
return $path;

}


How do I add taxonomy to my custom entity?

As Clive said, you use an entity reference field for that, just like articles have a tags reference field to terms.

If you want to define it in code, it's really the same as the node.uid field, which is an entity reference to a user. Or the user.roles field, which is a multivalue reference to user roles. Entities reference others using an entity reference field, it's always the same pattern.


If you switch to 'donation' module and 'simple_paypal'
You can create a block with the content:

<?php
require_once(drupal_get_path('module', 'donation') .'/donation.module');
print donation_form();
?>

Make sure to set input format to PHP code


Aggregate uploaded files for simplified download

Take a look at the pclzip suite of modules ZipCart.


The reliable way to add and see menu options on admin pages is through [PHP] code, using hook_menu(). Be sure each URL is prefixed with admin/... (for example, admin/sub-section/page-1, admin/sub-section/page-2).

Here's a quick snippet paraphrased from the hook_menu() Drupal API docs:

  function mymodule_menu() {
    $items['admin/sub-section/page-1'] = array(
      'page callback' => 'mymodule_page1_view',
    );
    return $items;
  }

  function mymodule_page1_view() {
    // ...
  }

I haven't tried tricking the admin screen by adding custom links with "admin/*" at the front, which may or may not work - but the code option will definitely work, I've used that hook more than a thousand times.


recursive entity reference in a view (tree view?)

That can be accomplished with a custom module (great question by the way)...

First define a function to handle the whole process:

function make_tree() {

  // This is the nid of the root of our tree - could be passed in as an argument
  // instead of being static.
  $root_nid = 110;

  // First build an array with 3 fields - id, parent_id, title.
  $data = array();

  // We call add row once and then it's called resursivly to fetch each child.
  add_row($root_nid, null, $data);

  // Here we can inspect our data in it's flat form.
  //dpm($data);

  // Now turn the flat data into a multi-dimensional array.
  $tree = build_tree($data);

  // And inspect our tree.
  dpm($tree);

  // Could return the tree here or do anything we want with it...

}

Then define the function to build the flat array of data:

function add_row($nid, $parent_nid, &$data) {

  $node = node_load($nid);

  $data[$node->nid] = array(
    'id' => $node->nid,
    'parent_id' => $parent_nid,
    'title' => $node->title,
  );

  if(isset($node->field_dependent[LANGUAGE_NONE])) {
    // Now loop childeren to add rows for them too.
    // My entity relationship field is called dependent but rename here as
    // necesary.
    foreach($node->field_dependent[LANGUAGE_NONE] as $child) {
      add_row($child['target_id'], $node->nid, $data);
    }
  }

}

Once this step has been completed the $data array will look like this.

And then finally the function to turn the flat array into a multi-dimensional one (credit to this answer for this step):

function build_tree(array $elements, $parentId = 0) {
    $branch = array();
    foreach ($elements as $element) {
        if ($element['parent_id'] == $parentId) {
            $children = build_tree($elements, $element['id']);
            if ($children) {
                $element['children'] = $children;
            }
            $branch[] = $element;
        }
    }
    return $branch;
}

I've just tested this and my final array looks like this.


Trivial Example of a Module that Creates a Content Type

Flex Slider creates a content type for a slider image and a view to make the slider itself, so you could look at that for an example module.


How do I view the author of a comment in a view block?

To place a view block next to each comment use the module:

EVA: Entity Views Attachment

Create a new View for user, add an EVA display, connect it in ENTITY CONTENT SETTINGS to the Entity Type comment, the Bundle default comment and as Arguments provide the token for the user id [comment:author:uid]. Add a contextual filter for the User ID.

Now the EVA views block appears in the Comment Type and you can place it in Manage Display.

You can also use as Argument the comment id and connect it to the View you have in the question which is based on comments and has the author as relationship.


How to add title attribute to views trimmed title field?

you can accomplish this by overriding the field tpl file for the field and view:

assuming a View called 'title_test', and a field named 'title'
under Advanced, Theme, it gives the following option for the field tpl file: views-view-field--title-test--title.tpl.php
copy the modules/views/theme/views-view-field.tpl.php to your themes template folder, and rename it to views-view-field--title-test--title.tpl.php
replace the existing $output code with:

<?php
    $field_output = l($field->last_render_text, $field->options['alter']['path'], array('attributes' => array('title' => $field->original_value)));
    print $field_output;
?>

clear the cache

BE AWARE that this is overriding the default output by manually creating the link, so any special classes, or formatting included in the View must be added to this or you get unexpected behaviour (like missing classes, or field styling, etc). All of the information is available in the $field variable, you just need to extract it, for which Devel and dpm($field); will prove invaluable:

  Devel Helper functions for Drupal developers and inquisitive admins.
  This module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries). Also a dprint_r($array) function is
  provided, which pretty prints arrays. Useful during development.
  Similarly, a ddebug_backtrace() is offerred.


Webform to add row to specific sql table

Sorry, but no, you are on the wrong track.

Webform module is nice and easy, but it uses it's own storage. And whilst you can indeed use hooks to store a copy in your own table, it would take a pretty huge amount of work to do it properly.

It will be easier if you simply write your own module for that. If you don't know where to start, see Examples for Developers.


Adding form elements via ajax; input not stored in $form_state['values']

You should add the $form['#tree'] so that all the values are passed.


#default_value Not Working In Select Field

On Drupal 8 form, I was having an issue with Firefox that was caching the value of a select field, selected by the user before refreshing the page.

It was basically overriding the #default_value of the field.

My solution was to Turn Off Form Autocompletion (https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion).

You can do it at the level on the input if that's an input, but since it was a select in my case I had to do it at the form level :

$form['#attributes']['autocomplete'] = 'off';


Add javascript to views exposed form after ajax submit

You'll need to wrap the JS in a Drupal behaviour, so that it is attached after the ajax refresh.

You should also ensure it only runs once

 Drupal.behaviors.styledSelect = {
   attach: function() {
     $('select').once('ss', function() {
       $(this).styledSelect();
     }
   }
 };

That way it won't get 'styled' on every ajax change.


JavaScript and CSS settings fail unexpectedly: The files were not created

As you already suggested, this is most likely a file permission problem. Make sure the entire directory under sites\default\files is writable by the apache user, often this is called www-data.

To get you going maybe download XAMPP for your platform and get your first Drupal installation working locally.


My thoughts are that you could use views to list various categories of nodes. And to have a similar layout structure, I haven't used it but I think Panels might help.

An alternative to Panels which I have used in the wonderful homebox module


drupal 7 add element after the username input text element on login form

You need to add suffix element to username field in login form. You can do it using hook_form_alter(&$form, &$form_state, $form_id)

Implement above hook in your custom module

function YOURMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['name']['#suffix'] = '@mycompany.com';
  }
}


Can a module install a content type optionally or conditionally?

Don't install a module when its default configuration has unmet dependencies adds a config/optional folder, which silently ignores configuration that already exists.

config/optional can contain configuration that will only be installed if the required dependencies of those config entities are met, for example a default view that would only be installed if views is enabled and is not required for the module.


What's the difference between Drupal 8.0.x and 8.1.x?

The answer is semantic versioning. The "1" in 8.1.x, represents a branch that can contain new features as well as bug fixes. Backwards-compatibility to code written for 8.0.x is inherent in the numbering system. So, if your code requires features in 8.1.x, you should develop against it, but note you won't be able to deploy your code until 8.1.0 releases.


You can enable the memcache_admin module and this will provide a stats page at /admin/reports/memcache, where you can see the number of sets and gets, hits and misses percentages and how much of the allocated memory is in use.

On the server, you can run this from the command line (assuming port 11211):

echo stats | nc 127.0.0.1 11211


The options are the second parameter in url(), then you also have to pass the first parameter, which is by default 'canonical':

$entity->getTranslation($language)->url('canonical', ['absolute' => TRUE]);

url() is deprecated, so better use toUrl():

$entity->getTranslation($language)->toUrl('canonical', ['absolute' => TRUE])->toString();


error_get_last() doesn't show last warning

Use the same PHP's error functions as Drupal to toggle PHP's error handling behavior.

In particular, you can use set_error_handler() / restore_error_handler() to toggle the PHP error code handling while you're debugging:

// Remove _drupal_error_handler() handling
restore_error_handler();

if (@preg_match($regex, NULL) === FALSE) {
  dpm(error_get_last());
}
// Restore _drupal_error_handler() handling
set_error_handler('_drupal_error_handler');

See the PHP doc links for more information on how these error handling functions work.


Relative and broken image with simplenews and mime mail

How are you calling cron?

You need to make sure that the base_url is set.

E.g., when calling cron with drush, you need to provide the --uri http://example.org parameter.


Contextually filtering a view using values from a completely separate table?

Make sure you check mark allow multiple values on your contextual filter's "More" settings.

Use hook_views_pre_view to pass your uid's to the arguments (contextual filter).
/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {

  if ($view->id() == "view_name" && $view->current_display == 'page_1') {
    $uids = [2, 19]; // hard coded example, you would query db here.
    if (is_array($uids)) {
      $uids = implode('+', $uids);
    }
    $args[0] = $uids;
  }

}

You will also need to disable the view's caching or add a cache tag if you created one for your other table query.


How to access a field value in hook_preprocess_eck_entity

I found I can get the value with:

  $myvalue = $vars['eck_entity']->get('field_myfield')->getString();


Using Features with an existing content type?

If you want all your content type to be transferred to another site without any changes you can import all content type from your dev environment and export it in stg environment and remove the validation.


How to identify and target a form element?

You're calling the explicit hook_form_FORM_ID_alter for a start so $form_id will never be anything except question_node_form.

However the problem is you are trying to target a child of the form array. The top level array is already question_node_form. Your code should look like this:

function custom2_form_question_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_points']['und']['0']['value']['#default_value'] = 164;
}

Debugging removed for clarity. Noticed we removed ['question_node_form'].

Also note you can't pass $form_id by reference (not that it matters) as it can't be changed.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


You'll need to add a hook_form_alter(), check the form ID matches one of those that you're interested in, then add a validation handler to the form. The validation handler will perform your validation against the form fields. Something like

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form_ids = array(
    'article_node_form',
    'page_node_form'
  );

  if (in_array($form_id, $form_ids)) {
    $form['#validate'][] = 'MYMODULE_field_validate_callback';
  }
}

function MYMODULE_field_validate_callback($form, &$form_state) {
  if (empty($form_state['values']['field_x'][LANGUAGE_NONE][0]['value'])) {
    form_set_error('', 'Field X cannot be empty.');
  }
}

I don't know of another way to do this as hook_field_validate() is only called for the module that implements the field type.


Yes that makes perfect sense - you've merged changes from the core repo, so your working copy is one commit ahead of your site's dev repo on Pantheon. Note that origin/master refers to the remote representing your repo, not drops-7.git

git push

to send the changes up to your dev site when you're ready to test, then pull them through the dashboard as normal.


Can I use Rules Transform to remove text from a returned value?

You can try applying this Rules Data Transforms replace text patch which adds the ability to replace text. Flush cache after applying patch.

So now simply replace grams with nothing (empty).


Fatal error: Call to undefined function quiz_type_access_load()

Try to find and delete records in "menu_links" and "menu_router" tables of your database which have "quiz_type_access_load" occurrences.

Be careful: backup the database first!


$GLOBALS['user']->uid returns same uid for different logged in users?

Hook menu is not for non-menu functionality.

Using %user in the menu item will call user_load() with whatever is in that part of the url (in this case the uid) and then when that part of the url is used in callback or access arguments it will pass in the loaded user object instead of the user id.

See wildcard loader arguments for more info on that.

To control who sees the tab, do your database check in the access control callback and deny access if there is no result. This way the tab will only show if there is a node.

Callbacks like the access control call back and the title callback run every time, not just when the cache is refreshed, so it is ok to use them in this way.

Try

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();

  $items['user/%user/alumni-spotlight'] = array(
    'title' => t('Alumni spotlight'),
    'page callback' => 'MYMODULE_user_tab_page',
    'page arguments' => array(1),
    'access callback' => 'MYMODULE_user_tab_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Access callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_access($user) {
  // Do something here to check access & return TRUE or FALSE to grant access or not.
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'profile')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $user->id)
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1)
    ->execute();

  // If there is a node, allow the user to access the page.
  if (isset($result['node'])) {
    return TRUE;
  }

  // If there is no node, deny access.
  return FALSE;
}

/**
 * Page callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_page($user) {
  // Return the content of the page.
}


Allowing file-transfer to use sftp or ssh?

I would still like to be able to use sftp, but for now, I was able to set up ssh here's how I did it:

user$ sudo apt-get install libssh2-php
user$ sudo /etc/init.d/apache2 restart

And now I can use the update manger with ssh, which works, for now......


Migrate import with authentication onto external site

Can you provide a little more detail? What sort of authentication do you need? The migrate_plus module has three authentication plugins - basic, digest, and oauth2. The first two take 'username' and 'password' in their configuration - oauth2, naturally, is quite a bit more complex.


Enable CKEditor on a field with a custom widget

I was extending the wrong class from my field widget. The proper class to extend if you're looking to use CKEditor is TextareaWidget


How to remove a views template file in theme folder?

It looks like my problem is related with APC or some sort of caching. After removing the file, I run

  $ httpd restart

from the command window on the server, then the errors are gone. Probably it cleared the APC cache.


Keep less files of Bootstrap in productions site after compiling?

Technically you will not need the less files on your production unless you need to Drupal to modify your theme. For instance, if you are integrating the color module that with your theme to allow administrators user to change the colors of the theme using the color module. You need the less files and you need to use less module. Otherwise you don't need them less files on your production site.


For this my_module.services.yml file:
services:
  my_module.obj:
    class: Drupal\my_module\ClassA
    arguments: ['@http.client']

You can discard the create() method from your A class, because you declared it as a service for which the arguments get resolved by the services YAML file parameters ie. '@http_client':
class A implements AInterface {

  /**
   * @var \GuzzleHttp\ClientInterface
   */
  private $httpClient;

  /**
   * @param \GuzzleHttp\ClientInterface $http_client
   *   A Guzzle client object.
   */
  public function __construct(ClientInterface $http_client) {
    $this->httpClient = $http_client;
  }

argument 1 passed to Drupal\my_module\ClassB::__construct() must be an instance of Drupal\my_module\ClassA, string given

Fix this by correcting your B class create() method to pass your service A name being 'my_module.obj', which would then in turn correctly pass an instance to the constructor of class B:
class B implements ContainerInjectionInterface {

  /**
   * @var \Drupal\my_module\AInterface
   */
  private $a;

  /**
   * @var \Drupal\Core\Logger\LoggerChannelFactory
   */
  private $logger;

  /**
   * @param \Drupal\my_module\AInterface
   *   Your module A class.
   */
  public function __construct(AInterface $a, LoggerChannelFactory $logger, ConfigFactoryInterface $config) {
    $this->a = $a;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_module.obj'),
      $container->get('logger.factory')->get('my_module'),
      $container->get('config.factory')
    );
  }


How can i add a span element within the search form using hook_form_alter?

For the placeholder just add this line to the hook_form_alter

$form['FIELD_I_WANT_TO_ALTER']['#attributes']['placeholder'] = 'placeholder text';

The span can be done in a few ways but the shortest is

$form['hover_toggle']['#markup'] = '';


Mobile website translation problem (losing language prefix)

We've come across a similar problem in our site on a desktop platform. So far, we've discovered the following about links in Drupal (for example, the href on an <a> tag in a Block Body):

If you use a link without a preceding /, Drupal will replace the last url element with your link name (i.e. mysite.com/en/area1/thing1 will become mysite.com/en/area1/thing2 when a user clicks a link configured as href="thing2" on a page in area1).
If you use a preceding / in your link, Drupal appends it to the domain directly (i.e. href="/thing2" directs to mysite.com/thing2).

We leveraged this to make language prefixes work, with limited success. As long as all our links are within the same uri path (i.e. all links on pages within area1 go to area1 pages), the language prefix is preserved. Once you try to leave that path, though (i.e. href = "/area2/thing3" on a page in area1), you must use the / and lose the language prefix. For those pages, you'll need to add URL aliases. We're still looking for a module/solution that saves us the time and effort of aliasing our menu system and cross links.

Note that in any case the base url (mysite.com) is preserved, so you should get the same results regardless of your platform (mobile or desktop).


How to create a contextual filter using a current user multivalue field as the default value

In your contextual filter go to bottom and in tab "more" check "allow multiple value" checkbox and return value 1+2+3 (OR) or 1,2,3 (AND).


I would recommend using this sandbox (Twitter Pull) for retrieving tweets instead. I've set it up before and it works quite well. You can see the relevant discussion below.

Errors occured while trying to retrieve tweets


Glossary input filter saving to node_revisions

Resolved, somehow the Glossary filter got enabled in the CKeditor's security settings "Please choose carefully all filters that protect your content (probably not all filters listed below are security filters)."

Disabled this and now the Glossary works as it should.


Search API Solr fulltext search improve results

You're looking to enable 'partial word' search which would allow for matching w800 with w800a. As described in this blog post, Apache Solr has this capacity built in, it just needs to be enabled by adding this line to the Solr Schema that comes with Search API

<filter class="solr.NGramFilterFactory" mingramsize="3" maxgramsize="25"/>

However, pay attention to their caution about performance issues - you want to only enable this capability on a limited field (ex. the title field) rather than a longtext field as it will greatly increase the size of your index and reduce performance.


CSS changes to .menu .leaf affect main-menu AND admin shortcut menu in Drupal 7

You need to make your CSS more specific so that it only applies to menu items on your main menu. You can do this by prefixing the CSS rule with the class of its container e.g.

.block--system-main-menu .menu .leaf. {
    width: 30px;
}


Plugin to make selecting a page on a menu easier

Content menu module improves Drupal's default menu management interface for tighter intergation of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created)
You can create a new menu item as

URL – With the traditional menu item form

Dummy – As a dummy menu item (with simple dummy link target)

New NODETYPE – directly create a new content for the new item

Existing content – selecting an existing content via a nice filterable view (if views is enabled)

Menu position rule (if the Menu Position module is enabled)


It seems you read not complete article :(. before this method getting call we should tell hey views we want use your hooks

something like in your .module file

/**
* Implements hook_views_api().
*/
function yourmodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'yourmodule') . '/views',
  );
}

Then create a views directory, create yourmodule..views.inc file there and put your code there ( please be sure your code getting execution with some dsm or die() ).

I know your change your way but I think it help you in another task.

take a look  at : this article


Trying to enter an argument with multiple words into a Views argument

If the arguments are not in a taxonomy term then add a vocabulary to contain them
Under the contextual filter section for When the filter value is in the URL check validation, set it to a Taxonomy term  and pick the vocabulary.
Select the Filter type or term name from the term ID
Check the box for Transform Dashes.

The view should now read the name from the URL and access the term id.


What about doing this using views.

You can create a view that lists all nodes of your event type, and then add a filter that sorts on the excluded field.

If you are not familiar with views in D7 there is a great guide here.

I hope it helps you out.


How to 'inject' the "read more" link into a textfield / paragraph (inline)

If the goal is simply to get the read more link to appear visually inline with your last paragraph, I think you can do that with pure CSS.  As you noted, formatting all your
 tags as inline elements will break the paragraph structure.  You can avoid this simply by using a :last-child selector, e.g. http://jsfiddle.net/hdys6w2j/

That said, if you are set on having the readmore link injected into your last p tag, I guess you could throw some code like this in your custom module:

function mymodule_preprocess_node(&$vars) {

  //Programmatically generate the readmore link
  $read_more_link = l('Read more', 'node' . $vars['node']->nid);

  if (!empty($vars['content']['my_field'][0]['#markup'])) {

    //Replace the last
 tag with Read More

    $vars['content']['my_field'][0]['#markup'] = preg_replace(
       '/\<\/p\>$/',
       $read_more_link . '
',
       $vars['content']['my_field'][0]['#markup']
    );
  }

}


Drush pm-disable needs a higher bootstrap level to run

You're using drush 7.0-dev on php 5.5.14.

Do you have php5-json package? That is required for php 5.5.
Did you follow the extra instructions on github.com/drush-ops/drush related to MAMP? There's one about socket that seems relevant


How to pass arguments from views to node.tpl.php

I finally got it. There's the Build modes module that does exactly what I want and only that.


How do I make computed fields visible when other fields are presented?

No reason why it shouldn't show up just because there are other fields in that content type. Are you sure there is data to show?


The return property of exclamation in front of array

t() uses format_string(), which uses strtr(). For this reason, your second example snippet works. Since format_str() is using the following code, any token that starts with a character different from !, %, or @ is treated as if the token started with %.

  foreach ($args as $key => $value) {
    switch ($key[0]) {
      case '@':
        // Escaped only.
        $args[$key] = check_plain($value);
        break;

      case '%':
      default:
        // Escaped and placeholder.
        $args[$key] = drupal_placeholder($value);
        break;

      case '!':
        // Pass-through.
    }
  }

drupa_placeholder() is the responsible for escaping some characters, since it calls check_plain().

function drupal_placeholder($text) {
  return '' . check_plain($text) . '';
}

As side note, since $arrays is inside a single-quote string, PHP doesn't replace it with the value of the $arrays string. If you wanted to put the content of a string into the string passed to t(), you should use a t()-placeholder, which starts with !, %, or @.


Apparently there is an issue with the way Drupal bootstraps when doing a fresh install. I solved the issue by adding a call to:

module_invoke_all('boot');

Hope it helps you if you come up with the same issue.


To answer my own question:

So in my case the route entity.node.canonical is not defined by my own module and although I want to use it in my module with an extra parameter, I don't want to mess with it.

I have chosen to use a query parameter (using ?) instead.

http://example.com/node/{nid}?id={id}

if you need the id you can get it from the request object:

$id = \Drupal::request()->query->get('id')


Passing parameters from Panel to View (contextual filter)

General solution:

Your View should have a "Content pane" display
Your pane should be configured to require an argument that matches the one your contextual filter wants.
Add the pane to your page.

For your specific question, I don't understand how you pass a string at all to Views, so I need more info about your setup to be more specific.


I'm not sure about overriding the <img> tag itself, but for your approach I would recommend overriding the field template. Assuming your field is named field_afbeeldingen, you can create a template called field--field-afbeeldingen.html.twig.

Within there, you could manually render your <img> tag as needed, with whatever additional classes required.


Colorbox not working in new content type

This problem might occur because the path to library is incorrectly set. It is typically like so:

libraries\colorbox\jquery.colorbox-min.js

Though via /admin/config/media/colorbox it is possible to set some other path for it (within 'advanced settings').

There was a time (some older version in colorbox) that the solution was to correct the path to the Colorbox plugin directory, so that after unpacking it looked like so:

sites/all/libraries/colorbox/colorbox/jquery.colorbox-min.js

Refer to issue #1906156 for more details on this.

If that doesn't help, then check if there are any other modules that use Colorbox that are trying to find it on this path.

Of course, make sure also that the "permissions" to the plugin are set correctly (if no read access is granted, then that is probably what is causing the problem).


How to run custom sql commands to database programatically

I haven't found a way to run this commands from Drupal 8 database connection object. I can only do selects, updates, inserts or deletes

That's not true, you can also run arbitrary queries, e.g.:
\Drupal::database()->query('TRUNCATE TABLE foo');


As this file is public the HTTP request is not served by Drupal. You need to
configure your web server to send correct CORS headers. If you are using Apache and have mod_headers installed you can set these HTTP headers in .htaccess file.

http://enable-cors.org/server_apache.html


drupal_render() is deprecated. What replaces it?

It was replaced with the renderer service.

$render_service = \Drupal::service('renderer');

As mpdonadio and 4k4 have pointed out in the comments, to prevent metadata from bubbling up to the main request, you should execute this in a new render context. You can do so by using the renderPlain method, rather than the usual render method (unless you're returning this from a controller, in which case use renderRoot instead).

$rendered = $render_service->renderPlain($build);


In a page view, add all of the fields you wish to display. Then add a filter in the Filter Criteria area that includes this field, then set the Operator to once specific selection (e.g. cars). Clone each page and override this filter for each page to filter for the other selections. (You could also just create on page view and expose the filter for users to change it on the fly.)


How to use custom code to change the node form layout and group fields while maintaining values?

$form_state is an object, not an array. You should be able to get the values like $my_value = $form_state->getValue('custom_group'). Or get all values like $values = $form_state->getValues().

See: Introduction to Form API


Given a field for Content Profile for a user, how can I extract that field via code?

You'll have to load the content profile node into a variable first using content_profile_load.

This should work:

$user_profile = content_profile_load('profile', $user->uid);

That will return an object ($user_profile) that you can call the fields which you've set up.
Use

echo '<pre>'.print_r($user_profile,1).'</pre>';

to see which fields are available.


Menu links and content to appear in different languages

The site is using the Internationalization module, but the different alignment, and layout is caused from a core feature Drupal has: When the language is one that is written from right to left, and a module adds a CSS file to the HTML output, e.g. using drupal_add_css(drupal_get_path('module', 'system') . '/system.admin.css');, Drupal search a file named system.admin-rtl.css, and uses it when that file is present; otherwise, it just uses system.admin.css.

In that site, the files having that "extension" are the following ones:

/modules/cck/theme/content-module-rtl.css
/modules/filefield/filefield-rtl.css?
/modules/nice_menus/nice_menus_default-rtl.css
/modules/node/node-rtl.css
/modules/poll/poll-rtl.css
/modules/system/defaults-rtl.css
/modules/system/system-rtl.css
/modules/system/system-menus-rtl.css
/modules/user/user-rtl.css
/modules/views/css/views-rtl.css
/themes/basic/css/style-rtl.css

To notice that, for example, /modules/poll/poll-rtl.css is not used instead of /modules/poll/poll.css, but together; /modules/poll/poll-rtl.css should then just contains the CSS styles that are specific for a right-to-left language.

The same is done for a left-to-right language; the difference is that Drupal looks for a file named, e.g., /modules/views/css/views-ltr.css, instead of /modules/views/css/views-rtl.css.


Disable pre-emptive validation of empty textfield

The 'fill in this field' message is browser specific HTML5 error handling.
Which is triggered before the form is submitted.
Only modern browsers show this, and it may currently not be consistent between browsers.

About this behaviour is an interesting discussion here: https://www.drupal.org/node/1797438.

If you have your own logic in place to assist the user with problems in the form you can disable HTML5 validation altogether by setting the novalidate attribute on the <form>. More specific is setting the formnovalidate attribute on a submit button.

In a hook_form_alter you can add the following line:

$form['#attributes'] += ['novalidate' => TRUE];


Show title of referenced node in node template

For example, if I remember node structure right:

Load node by id into $node
Put title to $node_title

$node = node_load(og_group_ref[0][target_id]);

$node_title = $node->title;

All you need is to get og_group_ref object/element


How to disable and enable all contributed modules in Mysql?

It is not necessary to disable all contrib modules during a minor update of Drupal.  If you are planning on exporting and importing your database anyway, I would recommend using Drush to do the update on a local development copy of your site.  That way, you can test the result of the update before moving it back to the live site.  It is not advisable to update your live site directly.

You might also want to give serious consideration to finding a better hosting service.  If you had ssh access, you could migrate your database from live to dev with drush sql-sync, which is a great time-saver.

Edit: If you do want to disable all of your modules via Drush, here is a shell alias that will do it (from examples/example.drushrc.php in Drush-5):

# $options['shell-aliases']['dis-all'] = '!drush -y dis $(drush pml --status=enabled --type=module --no-core --pipe)';

If you want to enable all of the contrib modules from the live site on the dev site, you could do something like this:

drush @dev -y en $(drush @live pml --status=enabled --type=module --no-core --pipe)

I don't recommend disabling modules by manipulating the SQL directly; it's much more reliable to use Drush.


How do I run drush migrate for specific path site

To use Drush to more effectively migrate sites from one VPS to another, to manage more than one site and to synchronize easily between them. It assumes that you are running your own cloud server, have Drush on it, and have already installed a Drupal site.

Drush Aliases

Drush aliases are a simple set of configuration that allows you to reference Drupal sites from anywhere in your server's folder structure by using a shortcut of the following format @site. Before being able to use these shortcuts though, you'll need to configure the respective alias. To do this, and if you don't have one already, create a file called aliases.drushrc.php in the .drush folder that resides in your server's root folder:

nano /root/.drush/aliases.drushrc.php

Here, you have to create a php opening tag, <?php, for the file and below copy the following array declaration:

$aliases['site1'] = array(
 'root' => '/var/www/drupal_folder',
 'uri' => '88.88.88.88/drupal_folder',
);

Save the file, exit, and the alias is set. To test it out, navigate to a folder that is outside of your Drupal site and run the following command:

drush @site1 status

Now you should get the regular status information about the site you just referenced in the alias. And you can use this shortcut also with other commands.

Migrating sites

Now that you know how to reference sites, we can look at migrating (copying) a site from one folder to another using Drush. Let's say you want to move @site1 from /var/www/drupal_folder to /var/www/drupal_folder2.

First, you need to create a new alias for this future installation. For this, like always, edit the aliases.drushrc.php file:

nano /root/.drush/aliases.drushrc.php

Here, you need to create below two aliases, both with the same format. Just copy-paste the old one and make the appropriate changes:

$aliases['site2'] = array(
 'root' => '/var/www/drupal_folder2',
 'uri' => '88.88.88.88/drupal_folder2',
 );

Save the file and exit. If you run drush @site2 status, it will not work because obviously the folder not only does not contain a Drupal installation, but it doesn't even exist. So let's create it:

mkdir /var/www/drupal_folder2

In order to prepare for the new Drupal installation, you'll need to create a new database as well. So login to your MySQL through your preferred way and create a new database, making a note of the access username and password. If you are unsure how to do this, read the tutorial that shows how to deploy a Drupal site with Drush.

Now that your database is set up, you can proceed to migrate the site. To copy all the codebase from the first folder to the other, run the following command:

drush core-rsync @site1 @site2 --include-conf

Now, edit this newly copied settings.php file in the drupal_folder2 copy and change the database information to reflect the new database you just created.

nano /var/www/drupal_folder2/sites/default/settings.php

In this file, you need to make changes to the following block of code to reflect your own database information:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'your_db',
      'username' => 'your_username',
      'password' => 'your_password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Save the file and exit. Now you can also migrate the database using Drush because it knows that the site in the drupal_folder2 now uses this database, even if it's currently empty. All you need to do is run the following command:

drush sql-sync @site1 @site2 --create-db

This will drop the tables in the database associated with @site2 (the one that is currently empty) due to the --create-db option and insert the ones from the database associated with @site1 - your original Drupal installation. So now you have 2 exact replicas of the same site.

You may run into the following error message (with the applicable credentials):

ERROR 1044 (42000) at line 1: Access denied for user 'your_username'@'localhost' to database 'your_db'

If this is the case, make sure that your user has the required privileges.

Log into MySQL (mysql -u root -p).

Grant the following privileges:

grant all privileges on your_db.* to your_username@localhost with grant option;
grant reload  on *.* to druser2@localhost;
flush privileges;

Synchronizing Drupal Sites

Now that you have a duplicate of your original site (@site2), you can use it for development work. If you make codebase modifications to it, you can use the core-rsync command to sync the files with the original (@site1):

drush core-rsync @site2 @site1

Obviously, you would not want to copy the settings.php file again, which prevents making database changes again. Next, to sync the database as well, run the same sql-sync command:

drush sql-sync @site2 @site1 --create-db

In most cases, it's recommended that the receiving database is emptied before the copy (using the --create-db option) to avoid conflicting configuration saved in the database that will then cause problems.

Remote sites

nano /root/.drush/aliases.drushrc.php

And let's create a new alias for a site on a remote server. Copy the following code below and replace appropriately with your information:

$aliases['site3'] = array(
   'root' => '/var/www/drupal_folder3',
   'uri' => '99.99.99.99/drupal_folder3',
   'remote-host' => '99.99.99.99'
 );

So, what does this mean? The site with the alias @site3 is located in the folder drupal_folder3 on the remote server and has that URI pointing to it on the remote server. This is to be expected. Additionally, you have to specify the remote host (which is the IP address of the remote host). Given that you have set up SSH keys, you will not be required to enter a password unless of course you have a password protecting your private SSH key itself, which I recommend if you are creating keys between two remote hosts (none being your personal computer).

And that's it. Now when you run the commands we've be talking about, you can perform the same actions remotely, as well as migrating and keeping sites synchronized. But just to test out the alias, run:

drush @site3 status


Explanation of Content Types, Modules, and Views

Reading the Drupal documentation might be your best bet to get an in-depth explanation, but let me try to summarize each in my own words so you can hopefully get a basic foundation so you can understand better.

Content types - Content types are how you add any of your content to a website. For most of your general pages that have just regular text on them, nothing special, you would use the Basic Page content type to just create a basic web page, or node. However, say you were going to have an events feed on your website - you would want different fields for information that you would want to display. In this case, you would make a content type called Events (or whatever you would like), and then add fields to it (e.g., Event Title, Date, Time, Location, etc.). Now, Events would be listed as a content type you can use to add content. When you add content and choose Event to add, your fields will show up and you can add the information for an event, save that event, and repeat. Saving an event will bring you to the page for that event with all of that event's information (the formatting of which can be changed in the content type settings for that content type. Every event entry now has its own page displaying its information.

Views - Now, you have pages for events, but say you wanted to have a feed or list of events on a specific page. You would do this using a View. A view aggregates content (from one or more content types) into a display. So you would create a view, specify which fields from earlier you want to display (like maybe just event name and date) and then filter the content to just show content of type events. This view can be created as its own page, or you can create a block which you can then place in a region on another page. There is a lot of customization that Views allow you to do that isn't obvious in the beginning, but this is the gist of what views do.

Modules - Modules are jus "extras" for Drupal. Really, most of what you would need to create a basic site is already included. However, say you wanted to add some sort of fancy menu that Drupal can't already do. People have made modules to give you that capability. Say you wanted to create forms for people to fill out. There are modules for that.

If you want me to explain anything in more detail or if anything is not clear to you, feel free to ask and I can clarify or elaborate.


After importing a content type from Features, What's the correct way to manage it?

Once the content type is created, is it part of the db as if I had created it normally through the UI?
Yes
Can I safely delete the Feature generated content type code?
No- See this Q/A for a more complete answer.
Can I manage fields through the UI...
Yes - once you have the content type set the way you want it, you should regenerate the feature module so that you have an up-to-date representation of your content type in code.
...or would I have to fiddle with the Feature generated code?
Definitely no

What's the correct workflow to work with the content type from that point?

First, make sure you have a clean starting point by ensuring that all of your features in all of your environments have the "Default" status (this just means that the loaded database configuration of the Feature matches the configuration defined in code in the Features module).

Make changes to the content type through the UI on dev as you normally would.
Once the content type has been modified to your liking, Recreate the Feature by clicking on the "Recreate button". That will generate a tar file. Extract that file in the same directory as the existing Feature module - overwriting the previous version.
Revisit the Features page on dev. The feature that was previously overridden should now be "default".
Assuming you are using git or subversion or similar, commit the changes to the Feature module and pull them to staging. (If you're not using source control, just FTP the changes to the Staging server).
Visit the Features page on staging. The Feature in question should now have a status of overridden. Click on the "Overridden" link, tick the checkboxes on the resulting page and click "Revert". This will update the database settings to match what is defined in the new Features module. The status of the Feature should now be "Default". (Note: sometimes the Features module automatically pulls in the new settings when you visit the Features page, but honestly, I'm not sure what triggers that or when - perhaps someone can add to that).
If all goes well on staging, repeat the same steps on prod.


This is just how out of the box drupal styles the tags fields.

You can fix it by overriding the themeing of your tags in your theme, but the easiest way I have seen to fix it is by using the Text list formatter module.

Install that then go to the display settings for your content type and there will be a new option "List", which then has further configuration options that can give you the output you desire.


You can use feeds module to import User. It can handle external fields also.
For more information go through the module documentation.


How to install an existing Drupal profile with drush?

To build on what Patrick said, if the profile is not already in your profile directory, you can download it with Drush dl:

drush dl drupal --drupal-project-rename=drupal
cd drupal
drush dl commons
drush site-install commons --db-url=mysql://user:pwd@localhost/db_name --site-name=Example --account-name=admin --account-pass=pwd

You do not need to run drush make, because drupal.org runs it prior to making the profile available for download.  Thus, when you run drush dl commons, you get all of the components that the Drupal Commons distribution needs to install.


How do I stop content overlap with Display Suite on mobile/narrow screens?

Found the solution when I discovered a difference between this site and the other that did not register fully when I posted the question.

The Content Types on this site and the Paragraphs on the other both use Display Suite, but this site was using one of the default Display Suite layouts. I built the other one later and used the more flexible Adaptivetheme bootstrap-style layouts.

Turns out the layout is the reason that items were stacking vertically on one site and stubbornly staying side-by-side on the other. When I switched this site to an Adaptivetheme layout like the other, things were much improved:

In case anyone else has a similar issue and is stuck with a default Display Suite layout, I also found that the email field was the only field causing problems. You apparently cannot truncate an Email field, but I found that switching the content regions so the taxonomy tags were on the left and the location, contact, and links were on the right was better than the original layout because the email address could stretch its box without running into the box on the other side.


First of all, you need to add the correct cache context when rendering cookie/session values. See https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts. Then you should no longer need to completely turn off caching and sessions should work fine, anonymous and logged in.
Using non-session cookies server-side can be a problem with reverse proxies in general and the built-in Internal Page Cache in specific. Disable it by triggering the kill switch on pages depending on cookies without a session:
\Drupal::service('page_cache_kill_switch')->trigger();

Don't use this trigger too often, it disables all page caching. If you need it on the majority of your pages then uninstall the Internal Page Cache, but keep the Internal Dynamic Page Cache enabled. If the dynamic page cache is too slow then put a third-party page cache in front which has the options you need to manage your cookies.


Re Dan Mantyla's comment, if your date field is not a Date (UNIX timestamp) or Date (ISO) field but just a normal Date field, the following code works for me:

$thedate = $data['components']['date']['value'][0].' 00:00:00';

// set the date
$entity_created->field_date[LANGUAGE_NONE][0] = array(
    'value' => $thedate,
  );


Yes: drupal_render()

Renders HTML given a structured array tree.
Recursively iterates over each of the array elements, generating HTML code.

There's much more explanation, and examples, on the docs page.
I'd advise also reading through Render Arrays in Drupal 7 to get a better idea of what that array represents.


Don't think this is to do with core. Do you have the "File entity" module installed by any chance?

There's a permission of "View files" that anonymous users will have ticked in. If you untick that any of those /files/* will get access denied for annon users


OK, I have found out, you have to create a libraries folder under web root.


That behavior is not inclued in core. You can try this two modules:

Sub-pathauto (Sub-path URL Aliases): The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias.
Extended Path Aliases: SImilar to previous module, but includes more functionlaity. The drawback is that it needs core patching (adding a line to nclude/path.inc) or installing PECL runkit library.


Virtual Directory for "sites" folder in IIS 7

After some research and some help from a co-worker the answer has been discovered. It looks like Windows actually lets you create Symlinks, it is just not obvious.

http://technet.microsoft.com/en-us/library/cc753194(WS.10).aspx


You can use the Drupal core Contact module to do exactly that.

EDIT: In conjuction with Menu Tokens, you will be able to add a menu entry that pulls in the current user id. Add this to your path when creating a menu link:

user/[user:uid]/contact

You'll need to enable "Use tokens" and select "User from context" in the Methods for Users dropdown. See screenshot:


How can I customize the way my taxonomy terms are displaying?

Indeed a preprocess function is what you're looking for, I suspect in D7 this will help:

function MYTHEME_preprocess_html(&$variables) {
if(arg(0)=='node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $results = taxonomy_node_get_terms($node);
    if(is_array($results)) {
        foreach ($results as $item) {

In terms of D6, node-taxonomy.tpl.php and page-taxonomy-term.tpl.php should put you on the right path.


Programmatically impersonating another user without causing the currently logged-in user to log out

The drupal_cron_run() function gives a perfect example for exactly this, since it changes the current user to anonymous whenever cron is run, then switches back after it is done.

// Prevent session information from being saved while doing funky stuff.
$original_session_state = drupal_save_session();
drupal_save_session(FALSE);

// Force the current user to anonymous to ensure consistent permissions on
// funky stuff runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user(); // Or use user_load() for a non-anonymous user.

// Do funky stuff here...

// Restore the user.
$GLOBALS['user'] = $original_user;
drupal_save_session($original_session_state);


Hiding the site domain name from the content writers

As long as you have your server configured properly (ie, have your ServerName and ServerAlias directives set right for Apache), then this should work our of the box as long as you don't explicitly set the cookie domain or base URL in your settings.php.  A potential complication is if you have any rewrites for canonical URLs on your site.

However, I think your best approach is to use the Domain Access module to run two sites out of the same installation.  Have one affiliate be for the live domain, and the other affiliate be for the authoring domain.  Then separate the content / themes as needed.  When content is OK, just move it from the authoring affiliate to the live affiliate.


How do I invalidate the cache of an entity?

But you know the entity ID that you want to have invalidated?

Then use \Drupal::entityTypeManager()->getStorage($entity_type_id)->resetCache([$id]);


PHP to show if content has new comments in taxonomy-term.tpl.php?

Yes you can but it will it performance without proper caching. Don't do that in tpl because you can cache it, even with page cache.
Code look something like that using drupal api.

<?php
$has_comment = false;
$nids taxonomy_select_nodes($term->tid);
foreach($nids as $nid){
$node = node_load();
  if($node->comment_count > 0){
    $has_comment = true;
  }
}


How to change theme template for the same block that is loaded twice on the page?

This is usually done at the theme level, not the in a module. Unless you want to create your own implementation of a menu.
First of all, enable Twig Debugging then in locate in DOM the templates you want to override.
In your active theme, create a file with the same name as the twig template you want to override. Copy the code from the original template and customize it as you like


Upload file and fill in fields in one step; or trigger a rule when a file is uploaded

So I believe that uploading and editing files works correctly with the latest dev release of the media module when using a file field or image field.

Like you said when you go to file/add it is using the file_entity module which I believe they are discussing adding upload and editing here http://drupal.org/node/1553114.


I don't have a Drupal 7 dev environment handy to try this on, but I think you are looking for fetchAllAssoc(), as you mentioned. This page has some query examples that are helpful.

When you call fetchAllAssoc(), you need to specify a field name as the primary key of the array, like:

 $result->fetchAllAssoc($field);

It also appears that fetchAll() will work (but apparently it is not the recommended solution).


Display content by specific groups of users

The simple solution would be to add Term Reference field to the user's profile fields. Then for each user assigned them a taxonomy (in this case the taxonomy term name would be the group name).

Use Field Permissions module to control who can edit and change the user's tax reference field.

Use Views and filter by taxonomy term to display the "group's" content. You  will need to make a View of Users then under Advanced (far right) add a Relationship of Content authored.


How can I change an image field programatically?

function top_node_update($node) {
      $top = views_get_view_result('top_3');
      $first = $top[0]->nid;
      $second = $top[1]->nid;
      $third = $top[2]->nid;

  if ($first == $node->nid) {
    $image = file_get_contents('public://images/badges/gouden rozet.png');
    $file  = file_save_data($image, 'public://images/gouden rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($second == $node->nid) {
    $image = file_get_contents('public://images/badges/zilveren rozet.png');
    $file  = file_save_data($image, 'public://images/zilveren rozet.png',FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }

  if ($third == $node->nid) {
    $image = file_get_contents('public://images/badges/bronzen rozet.png');
    $file  = file_save_data($image, 'public://images/bronzen rozet.png', FILE_EXISTS_REPLACE);
    $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
    field_attach_update('node', $node);
  }
}

You should also try to prevent using functionality twice. So instead of the code above you can also write something like:

function top_node_update($node) {

  $top = views_get_view_result('top_3');
  $first = $top[0]->nid;
  $second = $top[1]->nid;
  $third = $top[2]->nid;

  if ($first == $node->nid) {
    $img_name = 'gouden rozet.png';
  }

  if ($second == $node->nid) {
    $img_name = 'zilveren rozet.png';
  }

  if ($third == $node->nid) {
    $img_name = 'bronzen rozet.png';
  }

  $image = file_get_contents('public://images/badges/' . $img_name);
  $file  = file_save_data($image, 'public://images/' . $img_name, FILE_EXISTS_REPLACE);
  $node->field_badge[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  field_attach_update('node', $node);

}


Set your views display style to unformatted and add preprocess function into your template.php, smthng like

function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

foreach ($vars['view']->result as $id => $row) {

    if ( in this place add your if statement ) {
      $vars['classes_array'][$id] .= ' added_extra_class';
    }
  }
}

You can check for every row needed condition


One account, one email, two different usernames

Due to drupal architecture you should go with a custom solution that create a second account for the user when he register by adding a global known prefix for unique fields that would be used when switching the user account.

Say user registered with mail someuser@somedomain.com you will make another account using that mail someuser.{global_key}@somedomain.com having {global_key} set in code you will use it for logging the user when he needs to switch accounts.

Scenario:

user registered
in custom module implement hook_user_register() and create another account for the user by using the {global_key}
if user needs to switch account do login by adding the prefix {global_key} to username (you could add to password or let password be the same) let switch account be a hook_menu implementation reading the

  global $user object and create a new account using {global_key}

-user forget password send the reset password link with a query parameter identifies the account will be reset by implementing hook_mail_alter

Hope that helps!


If you need the form elements you are adding to appear before the other ones, you should use the #weight property, and give them a negative value, since the default value is zero. Differently, the form elements you add to a form via hook_form_alter() are normally appended to the form, with the exception of when there is a form element with a positive #weight value higher than the #weight value you assigned to your form element.

user_login() doesn't set the weight of its form elements. The following code should work.

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
  $form['bigletters'] = array(
    '#type' => 'item',
    '#markup' => 'Big letters',
    '#weight' => -10,
  );

  $form['smallletters'] = array(
    '#type' => 'item',
    '#markup' => 'Small letters',
    '#weight' => -8,
  );

  $form['links'] = array(
    '#type' => 'item',
    '#markup' => '',
    '#weight' => -6,
  );
}

If the code doesn't work, then there is probably another module that alters the weight of the other form elements.


Check that the sites/default/files directory and any directory inside that are writeable from the account used to run Apache. After that, force Drupal to clear its cache.
It happened to me too, and all the times it was because Drupal was not able to write the files it uses for rendering the page in that directory.


Drupal 7: Add markup to form during validation

In your validate you can set a variable in the $form_state that tells if the validation failed or not:

function webform_validate_handler(&$form, &$form_state) {
  if ($mail_invalid) {
    $form_state['mail_invalid'] = TRUE;
  }
  else {
    $form_state['mail_invalid'] = FALSE;
  }
}

Then in your form, you can check for empty($form_state['mail_invalid']) and show the markup when the empty check returns false.

function hook_form_alter(&$form, &$form_state, $form_id) {
  ...
  if (!empty($form_state['mail_invalid']) {
    $form['markup'] = ...;
  }
}


How can I change the precision in the decimal field of CCK?

yeah, _node_validate is a flexible way. an alternative to a custom module, can be use a Rules module and integration with Rules Forms support module. Also will be useful use a more flexible CCK field, then, this will allow to validate whatever number with the model that you want.
.1. install the modules.
.2. then we need now is indicate to rules in what form must work. You must go to Rules > Form events and enable the option Enable event activation messages on forms. then go to the respective form and click in the Activate events for.. (the name of the form)
.3. go to rules and add a new rule and select in the Event: the respective event on which you want to evaluate this rule. (to this case Rules Forms modules will include the name of your form in the Rules Forms section on the Event select list.
.4. In a condition of rule add a numeric comparison (or whatever other condition that you want, for example a custom php code):
example with numeric comparison:
field Number 1 (php code): $number= $form_state['values']['number'][0]['value']; if ($number < 10 || $number > 100) { echo 1; }
Field Comparison: Equal to
Field Number 2: 1
.5. in the action option, of your rule, add an action like a form error message to warn about change the syntax of the number. in Form element ID add the ID of the field, for example field_color (you can review the name in the list of fields CCK of the content/node type).
.6. Create a new rule if is necessary, like $number= $form_state['values']['number'][0]['value']; if (...) { echo 1; } and add the respective error message.
do not forget enable the rule, to see working your rule!.
(I hope that this information be useful)


How can I prevent text areas from being resizable?

It's JS that makes the text areas resizable, not CSS. I think the simplest way to disable this behaviour for all textareas is to implement THEMENAME_textarea() in your theme and remove it there:

function THEMENAME_textarea($element) {
  $element['element']['#resizable'] = false ;
  return theme_textarea($element) ;
}


I think you can do anything you could do in my_theme_item_list in a preprocess function. You can do this in your template.php file with a function like:

function mythemename_preprocess_item_list(&$vars) {
  // Change things here
}


Webform template suggestion doesn't work

Apply the latest patch from here: https://www.drupal.org/node/1891220
In your theme's template.php, in YOURTHEME_preprocess_webform_form(), add:

$path_parts = explode('/', drupal_get_path_alias());

$path = implode('__', str_replace(array('-', ' ', '+', '.'), '_', $path_parts));

$hook = $vars['theme_hook_original'];

$vars['theme_hook_suggestions'][] = "{$hook}__{$path}";


Many modules provide add-on functionality for Views. Chaos tools suite (ctools) provides the Content Pane display, which is a way to embed views in other areas of your site using advanced context passing. The views are not treated as pages and you can therefore embed them multiple times, just as you can with blocks, but with blocks your context handling is very limited.

For one good example of where and how to use it you may look at Panels module.

Some tutorial here:

Drupal Tutorial - Panels #6 : Related Content With Views Content Panes | WDTutorials.com


Data export view gives error if 0 records

This has been transitioned to https://www.drupal.org/node/2576429 per the request of Mołot.


Embedding a custom form in node.tpl.php does not trigger validation

$form_state['values']['sample_field'] this value is set after submit, so you validate the old result instead of your actual form.

maybe this workflow helps you


Writing functional tests for a controller that makes call to external service?

Depending on what exactly you want to do, what we've done multiple times is make the domain/URL to which you redirect to configurable, and then configure it to redirect back to your site.

Then implement dummy routes there in a test module, do whatever you want and redirect back.

This was already possible in 7.x and hasn't really changed. It is sometimes more complicated to set up, but has the advantage that you are testing much more of your actual code and integration.

if you use @larowlan's approach, you could also just write unit tests for your service but I like to have most code covered with functional tests (too). I've seen it in core already many times that unit tests and their mocks get out of sync with how things really work, and then they are testing something that no longer exists. The more you have to mock, the bigger that risk becomes.

Note that, no matter which approach you chose, moving as much logic as possible into a service or even multiple services makes sense anyway and allows you to use unit tests for things that they are good at. Testing all possible cases, error handling/conditions and so on.


Filter taxonomy term view by referenced taxonomy term

To answer you question: No, it shouldn't need to be configured differently; it should work the way you describe.
Here is a screenshot of my configuration (following your description) that works as you would expect (you can see the contextual filter in the background set to 'yellow'):

Perhaps you can spot some tiny deviation from your config here.
Good luck in any case!


Rules Custom Condition for registration capacity

Looking at your function, I believe you need to rename it to something like mymodule_rules_condition_info. The hook you are trying to implement is hook_rules_condition_info(). Did you find that your custom condition was showing up when you were editing a rule?

function MYMODULE_rules_condition_info() {
   $conditions = array(
     'mymodule_event_is_at_capacity' => array(
       'label' => t('Event has reached maximum registrations'),
       'group' => t('MY MODULE'),
       'parameters' => array(
         'registration' => array(
            'type' => 'registration',
            'label' => t('The registration event'),
           ),
         ),
       ),
     );
     return $conditions;
 }

Semantically you may want to call your condition 'mymodule_event_is_at_capacity' and it should only need one parameter which is the capacity that you will provide in the Rules UI.

The function you will be writing mymodule_event_is_at_capacity($capacity) will query for the number of (active) users in Drupal, and if it is greater than or equal to $capacity, it will return TRUE.

All of this can be kicked off by add a new Rule that reacts on the "After saving a new user account" event.


The request sanitization is an important part of Drupal security. Probably you can find the most important code in the DrupalRequestSanitizer class.
Here you have the sanitize method:
 /**
   * Modifies the request to strip dangerous keys from user input.
   */
  public static function sanitize() {
    if (!self::$sanitized) {
      $whitelist = variable_get('sanitize_input_whitelist', array());
      $log_sanitized_keys = variable_get('sanitize_input_logging', FALSE);

      // Process query string parameters.
      $get_sanitized_keys = array();
      $_GET = self::stripDangerousValues($_GET, $whitelist, $get_sanitized_keys);
      if ($log_sanitized_keys && $get_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from query string parameters (GET): @keys', array('@keys' => implode(', ', $get_sanitized_keys))), E_USER_NOTICE);
      }

      // Process request body parameters.
      $post_sanitized_keys = array();
      $_POST = self::stripDangerousValues($_POST, $whitelist, $post_sanitized_keys);
      if ($log_sanitized_keys && $post_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from request body parameters (POST): @keys', array('@keys' => implode(', ', $post_sanitized_keys))), E_USER_NOTICE);
      }

      // Process cookie parameters.
      $cookie_sanitized_keys = array();
      $_COOKIE = self::stripDangerousValues($_COOKIE, $whitelist, $cookie_sanitized_keys);
      if ($log_sanitized_keys && $cookie_sanitized_keys) {
        _drupal_trigger_error_with_delayed_logging(format_string('Potentially unsafe keys removed from cookie parameters (COOKIE): @keys', array('@keys' => implode(', ', $cookie_sanitized_keys))), E_USER_NOTICE);
      }

      $request_sanitized_keys = array();
      $_REQUEST = self::stripDangerousValues($_REQUEST, $whitelist, $request_sanitized_keys);

      self::$sanitized = TRUE;
    }
  }

There a few more functions but this one is the most important.
As you think sanitizing request input is very important. One of the worst Drupal core issues were related to this (in fact, this file was patched, if I'm not wrong). See "Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002" security report.
Implications
Given Drupal has a Security Team you don't have to worry about request sanitization unless you develop your own code that deals directly with the request.


Create a multi-value Field Group, with one taxonomy term reference (tag), and one image. Field group values can be used in views via Field group views module.

Alternatively you can do the same using Field collection module - younger, without 6.x roots, written to utilize entity api (and it means native views integration).

For bulk uploading, there is Field Collection Bulkupload, it seems to work, if with issues (as to be expected for alpha module). If you need bulk upload capabilities and equivalent of collections, joining efforts with it's team should be your best bet.


WHERE MySQL clause not working in Drupal 6

Try

$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", 19);

this is the proper way to handle variables in the db_query, as it prevents sql injection.

//grab the current user
global $user;
$query3 = db_query("SELECT nid FROM {node} WHERE uid = '%d'", $user->uid);


How to implement quotation replies on Commerce orders by multiple users?

Use the Flag module to allow those users of a specific role to flag orders.

When configuring the (non-global) flag(s), attach appropriate fields to them, as described in Attaching fields to flags. These fields could perfectly match with the "multiple fields data to reply like price, qty, destination, etc." (as in your question).

If needed, use the Rules module to add all sorts of additional (custom) logic to the mix, eg:

only allow such flagging to happen within selected timeframes.
send (eMail) notifications to appropriate users.
perform field level validations (whatever may seem to be needed).
...


How to remove the Destination parameter from an URL in Drupal 7?

Finally I got the solution by using hook_url_outbound_alter in my theme template. I tested it successfully.

function moon_url_outbound_alter(&$path, &$options, $original_path) {
 // here "moon" is my theme, use your own.
  switch ($path) {
  case 'user/login':
  unset( $options['query']['destination'] );
  break;
 }
}


Architectural - How to setup content types for very unique editable pages

Option 1: Panels
Maybe you should check to what extend your unique and complicated design of each page" could be implemented using the Panels module. Some details from its project page:

The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

Learn Page manager! is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. Here is a summary of the entire set of videos about this topic (quote from the link above):

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Refer to Explaining Panels: An Overview for Drupal Developers for another great explanation about the Panels module.
Option 2: Display Suite
Another approach is to use the Display Suite module. Some details from its project page:

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!
By defining custom view modes (build modes in D6), you can define how one piece of content should be displayed in different places such as teaser lists, search results, the full node, views etc.

Screencasts & articles about Display Suite has numerous screencasts with more details about it.


Why can't I modify my comment form using hook_form_alter

It looks like the label "Comment*" is not from comment_body container wrapper, then again comment_body shouldnt be of type container.

Most likely the actual comment field is somewhere not visible of your debug screenshot. This is because drupal core comment module form doesnt use normal form api structure where containers only reference children and reverse. Instead the actual field is placed directly to container. Luckily drupal_render has no problem with neither structure.

Removing the label should not require specifying language on the actual field. It should be as easy as

$form['comment_body']['#title']='';

Instead with funky comment form render array you need to specify language of the containers sub items, hence the path transforms to

$form['comment_body'][LANGUAGE_NONE][0]['#title']=''


Well, I found the answer after trying many things. I just cleared the cache and it worked!

I hope this helps somebody else.

Thanks,
Kunal


Display Google Map after entering address?

I think you are looking for geofield gmap module, it have the option same like your requirement. See the below screenshot and also easy to configure.

Geofield Gmap allow to use a google map v3 map to input a location.

A quick text input + geocode allow you to specify an address.

You can also drag and drop the marker to narrow the position.

Geofield Gmap require geofield.

Geofield is a module for storing geographic data in Drupal 7. It supports all geo-types (points, lines, polygons, multitypes etc.)


Correct way to access field values? field_view_value after field_get_items?

If you are worried about bloat, just write your own field processor and keep it all on the level. That way you are using safe values, your site won't trip over if the language settings wiggle about and you can reuse your code in your next site.

You would call it wherever you like and because you know what you're expecting to get back, you could work with it immediately.

Something like:

<?php
/* get the values out of a field */
function magic_field_values($node, $field_name, $delta = null){
  $field_items = field_get_items('node', $node, $field_name);
  /* if a delta value is supplied, render that item otherwise, send the lot
  back. */
  if ($delta){
    return field_view_value('node', $node, $field_name, $field_items[$delta]);
  } else
  return $field_items;
}
?>

Then call it with:

<?php
$cheese_samples = magic_field_values($node, 'field_cheese_samples');
foreach $cheese_samples as $sample {
//do stuff
}
?>


Create "suggest an edit" functionality for anonymous users on nodes

I think you may want to check out the Workbench Moderation module. Basically, you'd configure a workflow that allows anonymous users to 'edit' a node, but their edits would trigger the workflow. From an admin experience perspective, you may want to configure it to trigger an email notice whenever updates have been made, or otherwise alert content admins that suggestions have been made.

One potential gotcha is the way that Workbench handles revisions -- it doesn't fork. Meaning that if you publish a node, that becomes revision 1. If someone comes along and edits it, they suggest revision 2. If a third person comes along, they'll see that the node is on revision 1, but when they go to edit the node, they'll see it's on revision 2. Any changes would be saved as revision 3, and so on. You may need to extend the module with your own custom workflow if you're looking for forking behavior (think pull requests on GitHub).


How to set canonical urls to migrated data

The canonical URL informs websites that the current URL is the authoritative location for the content contained on this page. This is useful if you're sharing content across multiple domains, have content available via feeds on other sites, etc.

With Nodewords (6.x-1.14-beta1 and above) it will automatically assign the canonical URL tag for the current pages using the page alias, so search engines will index e.g. /products/flying-monkey rather than /node/42. Also, with the 1.14-beta1 release I've made a concerted effort to make it "just work" out of the box, so you should get reasonably useful meta tags just by enabling the modules.

Also, if your content is available via multiple domains you can hardcode which domain the content is available from, that way even if the content loads on all of the old URLs the search engines will present the canonical one as the preferred page.

Disclaimer: I am the maintainer of the Nodewords module.


EntityFieldQuery causing column not found PDO exception

At a guess you're using the Email Field module to provide that particular field?

If so, the column name is email, not value, so your code should be:

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mail_entry')
  ->fieldCondition('field_email', 'email', $email);


The theme is broken when I enable the "Optimize CSS files" option

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

try:

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

/*
This is a

multi-line comment.
*/


it depends on the field widget how you submit your values for the service.
For instance when you have a date field (datetime) with a select/dropdown widget, the form of the value should be the following:

"field_date":{"und":[{"value":{"month":"3","year":"2013","day":"6","hour":"0","minute":"0","second":"0"}}]},


How do I install Flysystem and Flysystem S3?

That documentation you referenced is outdated and wrong. You should read the official documentation on https://www.drupal.org/node/2404989.

The easiest way to do this is to install the drupal modules with composer, as documented on https://www.drupal.org/node/2718229. Once you've configured the drupal.org repository, installing a module is as simple as composer require drupal/flysystem. That will download that module, including alll dependencies that it needs for you.

You can manage your whole installation, including core, with composer if you use composer create-project drupal-composer/drupal-project:8.x-dev. You can also add contrib modules if you installed drupal core by hand, but when updating core, you need to be careful to not lose your composer.json changes and run composer update again.


Is it correct to use taxonomy_term_is_page() in this code?

Basing on the documentation of taxonomy_term_is_page(),  the function just checks if the current page is the page of the passed-in term. Looking at the code, the function verifies the path of the current page is "taxonomy/term/%term-id", and "%term-id" is the term ID of the taxonomy term passed as argument.

function taxonomy_term_is_page($term) {
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

You are passing to the function the wrong parameters; you should pass it a taxonomy term object.
The code you reported is calling the function as taxonomy_term_is_page('28').

If you know the term ID for the taxonomy term, then you can use the following code:

<?php
  $page_term = menu_get_object('taxonomy_term', 2);
?>
<?php if (!empty($page_term)): ?>
  <?php if ($page_term->tid != 18): ?>

blah 1 News

  <?php elseif ($page_term->tid != 28): ?>

blah 2 News

  <?php elseif ($page_term->tid != 29)): ?>

blah 3 News

  <?php elseif ($page_term->tid != 30): ?>

blah 4 News

  <?php elseif ($page_term->tid != 81): ?>

blah 5 News

  <?php endif; ?>
<?php endif; ?>


How to default a content type's Language field to the authenticated user's language?

actually, i would create a custom module (i hope, you know how to code a bit)

the code should be something like the following:

    <?php
    function YOUR_CUSTOM_MODULE_node_presave($node){
        global $user; // gets the current user account
        $node->language=$user->language;
    }


How to include a Google font not available in @font-your-face module?

You can add it by using drupal_add_css() in your template.php file's template_preprocess_html() function:

function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Pacifico', array('type' => 'external'));
}


How can I conditionally create a user account based on field in registration?

Create a new field on the user object, field_registration_code.

Set the form field to show on the registration page.

Use hook_form_alter() to hide the field when not registering, if the code is not to be used in the future. Don't hide the form field on the 'manage form' tab, else it will not be rendered on the registration page.

Create a service with the following method:
/**
 * Validates a registration code.
 *
 * This function checks if the submitted  code is a valid
 * registration code, and if it is, invalidates the code, and
 * returns TRUE. If the access code is invalid, it returns FALSE.
 *
 * @param string $registrationCode
 *   The code to be validate.
 *
 * @return bool
 *   TRUE if the code was valid, FALSE otherwise.
 */
 public function validateRegistrationCode(string $registrationCode): bool;

Implement hook_ENTITY_TYPE_insert(), implemented as hook_user_insert(). This is called after the user entity has been saved. You can use that hook to check if the given code is validated, and if not, block the account. It can then be activated by an admin through the admin interface.
function HOOK_user_insert(EntityInterface $user) {
  if ($this->myService->validateRegistrationCode($entity->field_registration_code->value)) {
    // Add roles to user here.
  }
  else {
    $user->block()->save();
  }
}


The action you are looking for is "set a data value". You will find that some values are easy to set with this and some are not. Install devel (if you havent already) and use the page array functionality to get the exact details about fields you want to fill in. Also make sure to have tokens/entity tokens available as that will make your life a lot easier for setting values in rules. If the field is multi value then you will need to start using variables, lists and loops to fill the field with data.


Drupal 7 Migration - redirect old dynamic urls to new domain name

There are three ways to tackle this.

You can make the mod_rewrite rules in you Apache configuration.  The benefit of this is that you can keep your Drupal .htaccess stock, so you don't need to worry about losing changes when you update core.  How/where this goes depends on you have Apache configured.  On my servers, I use virtual hosts, so I add a <IfModule mod_rewrite.c> inside the <Directory> section.
You can edit the stock .htaccess that comes with Drupal.  You need to add them above the main rewrite that punts to index.php, which starts on line 112 in Drupal 7.x HEAD.  When you do this, you need to make sure you back up and restore this file when you update core (or track in RCS and merge changes).
You can use a combination of the Pathologic and  Redirect modules. Pathologic will set up rules that rewrite URLs in your content when they get rendered out.  Redirect can set up 301/302 redirects for inbound requests.

Of the three choices, I try to avoid #2.  I manage a lot of sites, and I don't want to keep track of which have custom .htaccess files.

Between #3 and #1, I tend to prefer #3 because I can have someone else manage this process via the UI.  However, if I have a lot of URLs with common patterns, or for simple domain redirections, I will use #1.  Typically, I end up using a combination of #1 and #3.


Struggling to start a project from scratch

It sounds, what Your problem is not in Drupal.

Check the Done Manifesto, probably it will help.

And let's move to Drupal 7 :)


What are the nfs values seen in the Strongarm seciton of features

Gonna go out on a limb and guess that they come from the Node and Comments Form Module, which uses nfs as a prefix for variables.

Failing that, have a look through your contributed modules and see what you have that can be shortened to NFS - that's probably the culprit.