What is the intended use of drupal_static?

The code in drupal_is_front_page() makes the page rendering faster because it calls drupal_static() once for each page request; how much faster it makes it depends from how many times drupal_is_front_page() is called. The fact it is using that code means the core maintainers know the function is called enough times to need that code.
The drupal_static() documentation explains this with the following paragraph:

  In a few cases, a function needs a resettable static variable, but the function is called many times (100+) during a single page request, so every microsecond of execution time that can be removed from the function counts. These functions can use a more cumbersome, but faster variant of calling drupal_static(). It works by storing the reference returned by drupal_static() in the calling function's own static variable, thereby removing the need to call drupal_static() for each iteration of the function. Conceptually, it replaces:

$foo = &drupal_static(__FUNCTION__);

  with:

// Unfortunately, this does not work.
static $foo = &drupal_static(__FUNCTION__);

  However, the above line of code does not work, because PHP only allows static variables to be initialized by literal values, and does not allow static variables to be assigned to references.

  http://php.net/manual/language.variables.scope.php#language.variables.scope.static
  http://php.net/manual/language.variables.scope.php#language.variables.scope.references

  The example below shows the syntax needed to work around both limitations. For benchmarks and more information, see http://drupal.org/node/619666.

function user_access($string, $account = NULL) {
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
  }
  $perm = &$drupal_static_fast['perm'];
  // ...
}

Your code calls drupal_static() every time, and essentially is the same code as the following one, which in Drupal documentation is not considered the fast version.

  $added = &drupal_static(__FUNCTION__);

  // User-uploaded files cannot set any response headers, so a custom header is
  // used to indicate to ajax.js that this response is safe. Note that most
  // Ajax requests bound using the Form API will be protected by having the URL
  // flagged as trusted in Drupal.settings, so this header is used only for
  // things like custom markup that gets Ajax behaviors attached.
  if (empty($added)) {
    drupal_add_http_header('X-Drupal-Ajax-Token', '1');
    // Avoid sending the header twice.
    $added = TRUE;
  }

@Clive explained the reason drupal_static() was added to Drupal: The idea behind its implementation was to use a static variable that at the same time could be reset (or changed) from other functions as well. In fact, the drupal_static() documentation says:

  All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables.


Can I add pagination to individual blog posts in my twig file?

That is the exact feature of the Book module.
Book module overview
You can configure which types are allowed to be added as book pages. There is a Block you can place on Book pages to show Book navigation and Previous/Next links (it obeys the Book pages order).

Regular Views don't have a feature to center the Pager around a pagination placement.
A custom solution can be created to add that, but there are also modules you can check out that may help:

Pager
Pagerer


Rules - Set language of message notification

Consider investigating if the patch in comment #3 of issue # 1472316 might be of any help. Even though it is not the exact same question here, it may help to find inspiration about how to answer your question.

For more details about this issue, visit the question about  "Rule condition to check which language is used by the visitor?".


There are 2 solutions:

use title as the text and it will automatically redirects you to the content page when you click on it.
in your views add the path field to your fields,

apply it and now check the exclude from display checkbox in its setting. go to Rewrite Results and set these settings:

click ok and move the path field at the top of the fields.

Now click on the field that displays your text on the image and set these settings:

Now that field will be a link to your content.


How do I create a multisite with  shared users and nodes?

You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);


Found this module Colorbox Node which allowed me to view Location Map Block in colorbox.

Follow this simple steps (to show only map block).

Enable Colorbox Node module. (Make sure colorbox module is already installed)
Create a Basic page and render Location Map Block in content region.
In this page display only Location Map Block.
Create a Global:Custom text or any custom link and add below code as a
text in it.

Map

By this you can render any block which you want to.


How to programmatically set node alias on node save

Path alias could be set using the path module in the core. Just call path_save the following from a function (or hook) of your choice. In your case I'd recommend you to implement the following code in hook_node_insert, because it is called after a node has been saved, and the node will have a valid nid.

// Assuming you have a $node object already.
$path = array(
  'source' => "node/{$node->nid}",
  'alias' => $alias,  // Any alias that you want to set.
  'language' => $lang_code,  // Optional, if you are working on a multilingual site.
);
path_save($path);

If you have global redirect set, the node page will be redirected to the alias.


I think too that the easier way is using simplytest.me, which allows to install more than one module and apply patches. (Click on Advanced options, which at first sight could not seem clickable.)

Consider that:

As of July, 2017, simplytest.me runs on Ubuntu and PHP 5.5.12-2ubuntu4.4
Some PHP extensions aren't installed, so some Drupal modules cannot be installed (e.g. the LDAP module)
As of March, 2017, it uses the Composer Manager module, so it can install any Composer requirements a module has
Some distributions, like OpenChurch, fail to install

If you don't need to have a fine control over the environment, simplytest.me is perfect for testing modules and combination of modules. It is surely faster to test modules on simplytest.me than using a virtual machine on your computer. The second option has the pro of allowing you to better control what you install at server level, and it helps if you need to reproduce more accurately the production server you are using.

The site is being ported to Drupal 8. You can see the progress on https://new.simplytest.me/. I am not sure it can be used for extended test of modules.

Reference

The project issue queue


Redirect to login page if login block fails

I guess altering the user login form and override the user_login_final_validate() with a custom custom_user_login_final_validate() with all codes copy from existing to custom and adding redirecting codes to login page with a check that current page is not user login page, should work.


drush up fails with Unknown archive format

I had the same issue.
I'm on PHP 7.4.5
The issue is fixed by upgrading drush from 8.1.15 to 8.3.3:

Change (update to 8.3.3) Drush-Version in

~/.composer/composer.json

and

composer update


How do I display a custom field from taxonomy term in user list in rewritten field

I solved my problem by fixing my field formatter (in its own module).


Including template footer.tpl.php within another template page.tpl.php

The way to include another .tpl.php file is the include function.

Another idea is to add your footer as a region in the page.tpl.php and assign a region wise theme as defined in Drupal 7 Template (Theme Hook) Suggestions

  region--[region].tpl.php
  The region template is used when a page region has content, either from the Block
  system or a function like hook_page_build(). Possible region names are determined by the  > theme's .info file.


Maybe you can add role. Admin menu --> People ---> Permissions --> Roles

example : "Editor" created

At the views's filter criteria choose: Show campaign for specific roles (field_bcc_specific_user_roles) and select Is equal to "Editor"


How to get field label from a field machine name

The label is not stored in the field storage configuration. You'll find the label in the bundle specific field definition:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
foreach (array_keys($definitions) as $key) {
  // get label for field machine name $key:
  $label = $definitions[$key]->getLabel();
}

Reference: EntityFieldManager::getFieldDefinitions


How to customize default add content page

You can use the Renderable Elements module. If you've ever had any experience with Display Suite, it works exactly like that, but for forms like Add Content. You can change up the display, remove the vertical tabs below, etc.

For the explanation, each field comes with a description/help field that you can fill out. Now it depends on the admin theme you're using on how that text is displayed.


How do I prevent a Node from being deleted?

Using hook_node_access() is one option:

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;

...

function MYMODULE_node_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'delete') {
    if (some_access_function($entity, $account)) {
      return AccessResult::allowed();
    }
    else {
      return AccessResult::forbidden();
    }
  }

  return AccessResult::neutral();
}

This method has the advantage of preventing deletion through other methods (e.g. REST) at the same time, and will automatically remove the delete link and tab from the node form anyway.


My Aquia Dev Desktop is insanely slow. What could be the problem?

I experienced the same thing when I tried using the Acquia Dev Desktop.

I now use c9.io (clould 9) and do all my development in the cloud :)

Here is a nice overview video of the IDE.


The correct code is using the following line.

$another_theme = array(
  '#theme' => 'another_theme_for_test',
  '#arg1'  => 'value'
);

That is similar to the following code you find in rdf_preprocess_comment(). The only difference are the theme applied, and the arguments that theme requires; the way you pass the theme name or its arguments is the same.

$variables['author'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['author'],
  '#attributes' => $author_attributes,
];
$variables['submitted'] = [
  '#theme' => 'rdf_wrapper',
  '#content' => $variables['submitted'],
  '#attributes' => $author_attributes,
];

Keep in mind that in most contexts you can just return a render array, which in your case is the following one.

[
  '#theme' => 'another_theme_for_test',
  '#arg1' => 'value',
];

The necessity to call drupal_render() is limited to very specific cases, so most likely you don't need it. If you do, you should use \Drupal::service('renderer')->render() instead.


There are two types of ajax in Drupal. Traditional AJAX, and the Drupal Form API #ajax api. You are mixing the two, by using #ajax in your form, but returning and AJAX response, rather than an #ajax callback response.

To understand #ajax, you need to understand the process by which the Form API works. This is how a standard non-Ajax Form API form works in Drupal:

Some function is called which builds a render array representing the form.
Form alter hooks are called, allowing other modules/theme to alter the form.
Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
The form is rendered into HTML and sent to the browser.
The user submits the form.
Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

When #ajax is implemented, the process is the same as above, but with some additional steps in the middle.

Some function is called which builds a render array representing the form.
Form alter hooks are called, allowing other modules/theme to alter the form.
Drupal caches the render array in the database, to be used for comparison on submission, as a security measure to ensure that the submitted data matches the type of data expected to be submitted.
The form is rendered into HTML and sent to the browser.

---------- #ajax behavior start --------------

The user does something that triggers #ajax
The browser sends all the data in the form back to Drupal, as if the form were submitted.
Drupal retrieves the form from the database, and confirms that the submitted data is allowed, and sanitizes it.
Validation and submit handlers for the form are called. The form must be set to be rebuilt in the submit handler for the ajax to work.
The form is rebuilt from the original form definition, passing it the #ajax submitted values.
Form alter hooks are called, allowing other modules to alter the form, using the #ajax submitted values.
Drupal caches the new render array in the database, to be used for comparison on submission.
The ajax built form is passed to the #ajax callback handler. The handler then returns the part of the form to be injected back into the DOM on the browser. This can be part or all of the form.
The new content is inserted into the DOM.

---------- #ajax behavior end --------------

The user submits the form.
Drupal retrieves the form from the database, confirms that the submitted data is allowed, and sanitizes it.
Drupal validates the form, runs submission hooks, and redirects the user to whatever page they are supposed to be on after form submission.

Referring back to your code, your ajax callback will receive two arguments, $form and $form_state, and needs to return a section of your form. So it should look something like:

function ajax_callback($form, $form_state) {
  return $form['some_element']['of_the_form'];
}

In your form, this is likely $form['field_car_company']['und'][0]['value']. You will build the options of that form element when the form is initially rendered the way you are now, and if the form has been submitted using ajax, use the submitted values to determine the new options to show.


In solrconfig.xml

<requestHandler name="drupal" class="solr.SearchHandler" default="true">
<str name="defType">dismax</str>

so the request handler was "default" hence query was parsed with deftype:dismax and dismax does not parse BOOLEAN operators in the query string.

I created a new HANDLER in solrconfig.xml

<requestHandler name="sohail" class="solr.SearchHandler" >
    <lst name="defaults">
     <str name="echoParams">explicit</str>
     <bool name="omitHeader">true</bool>

Set $params[qt] = "sohail"; in the MYMODULE_apachesolr_modify_query()

Now it works perfectly!


theme style.css is not loading for custom theme

Try adjusting your spacing. 2 spaces are required.

.info.yml:

name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
  - contra/global-styling

.libraries.yml:

global-styling:
  version: 1.0
  css:
    theme:
      css/style.css: {}

Also, take a look at https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme


Generating Views Block to list Taxonomy Terms of nodes curently visible in a Views Page

Offhand i'm not sure how Context will help you do this ... off the top of my head this solution came to mind.

In your 1st view make the Tag field a hidden field the view so the View knows about it.
Use hook_views_pre_render to loop through the results (and maybe respect page offset and # of items per page -- you can get that from the $view object) and grab your view field Tag values and store them into an array.
Still in hook_views_pre_render you can set $view->attachment_after = $some_string; where $some_string is like the list of your Tags.

In code it will look something like this:

function MYMODULE_views_pre_render(&$view) {
  if ($view->current_display == 'VIEW_ID') {
    $tags_on_page = array();
    // $_GET['page'] has page number.
    // $views->items_per_page has items per page count.

    $page_offset = intval($_GET['page']);
    // this is somewhat wasteful, but easier than a loop at the moment.
    $paged_results = array_chunk($view->result, $view->items_per_page, TRUE);

    // Build up the Tag list for X page of the results.
    foreach ($paged_results[$page_offset] as $i => $result) {
      $tags_on_page[] = $result->value; // save the taxonomy term name to the tags list.
    }

    // Take our tags and build a block of HTML to embed after the view.
    // Alternatively, maybe take these tag values and pass them as parameters
    // to a new view we attach after programmatically -- thats more work.

    // if you know the url prefix you've given these taxonomy terms use it here, or use something like entity_uri().
    $num_tags = count($tags_on_page);
    if ($num_tags) {
      for ($i=0;$i<$num_tags; $i++) {
        $term = $tags_on_page[$i];
        $tags_on_page[$i] = l($term, '/URL/ALIAS/BASE/PATH/TO/TERM' . $term);
        // or, ... $term may have a path value already ... I cant remember :).
        // $term = taxonomy_get_term_by_name($tags_on_page[$i]);
        // $term_path = entity_uri('taxonomy_term', $term[0]);
        // $tags_on_page[$i] = l($term[0]->name, $term_path);
      }
      $links = implode('
', $tags_on_page);
      $view->attachment_after = '

Related Tags
' . $links . '
';
    }

  }
}


Views Slideshow - How to add link on Pager that can link to original page?

Having a look at the views slideshow code it seems that all the sections of the views slideshow are easily themed.

In the views slideshow module there is a themes folder with template files that can be overridden.

Though there is not a template file for the pager, instead there is a function in the file views_slideshow.theme.inc. The function you are interested in is probably theme_views_slideshow_pager_widget_render($vars) and this can be overwritten.

In your themes template.php copy and paste this function and rename it to MYTHEME_views_slideshow_pager_widget_render($vars), (replacing MYTHEME with the name of your theme).

You should then be able to modify it in any way you like.


How can I look up the number of items in a Drupal View?

You can get the amount of results in a view using their API calls.

<?php
$views = view::load("viewname");
$view->set_display('default'); //optional, could be default, OR the name of a specific display
$views->execute();
echo count($views->result);
?>

I tested this on views 3 (the current version). For further reading, check out http://groups.drupal.org/node/10129. It's written for views 2, but still relevant.


Create a view that shows a list of templates.
Add a relationship to the actions content type (Entity Reference: Referenced Entity via field_related_action).
Add a relationship to the files content type (Entity Reference: Referencing entity via field_related_action).
Create a contextual filter based on the current nodes nid. When you create the filter then When the filter value is NOT available select Provide default value and choose content ID from URL. Also this filter should be for the second join to the file node type.
Set that view to show in a block on each files page.


How to easily alter an entity's base field definition per bundle

Bundle specific labels for base fields are stored in label of a BaseFieldOverride config entity:

  Defines the base field override entity.

  Allows base fields to be overridden on the bundle level.

  Plugin annotation

@ConfigEntityType(
  id = "base_field_override",
  label = @Translation("Base field override"),
  handlers = {
    "storage" = "Drupal\Core\Field\BaseFieldOverrideStorage",
    "access" = "Drupal\Core\Field\BaseFieldOverrideAccessControlHandler",
  },
  config_prefix = "base_field_override",
  entity_keys = {
    "id" = "id",
    "label" = "label"
  },
  config_export = {
    "id",
    "field_name",
    "entity_type",
    "bundle",
    "label",
    "description",
    "required",
    "translatable",
    "default_value",
    "default_value_callback",
    "settings",
    "field_type",
  }
)

When you get a base field from EntityFieldManager::getFieldDefinitions($entity_type_id, $bundle), set a new label for the field and save the field definition, then this label is not stored in the entity type (which would not be possible, because this is in code and the same for all bundles), but in the mentioned base field override.


Render values directly in a twig paragraph template

I'm new to Drupal also and was trying to do the exact same thing. I simply put the machine name of the input I was trying to show in to the twig template i.e - {{ field_image_caption }} - flsuhed the cache and it magically appeared. Hope that helps.

                {{ field_image }}

                    PHOTO CREDIT: {{ field_image_caption }}


No.

'controller class' => 'ExampleTaskController',

  controller class: The name of the class that is used to load the
  objects. The class has to implement the
  DrupalEntityControllerInterface interface. Leave blank to use the
  DrupalDefaultEntityController implementation.

Says nothing about where the class code actually lives in Drupal. The easiest place to put it is in the same file your declaring hook_entity_info. Because since it's in the same file it will be found by PHP because the class will have the same file scope as your hook_entity_info implementation, and likely the other hook functions needed for your entity.

In PHP there are only 3 scopes: file scope, function scope and global scope.

So how can it live outside of say YOURMODULE.module. You declare where this class can be found in your YOURMODULE.info file with the files[] directive.

Such as:

name = my custom module
package = other
files[]= EntityClassController.inc

Files defined by the files[] entries are scanned for class definitions and included automatically by Drupal in its bootstrap phase to be available as-needed by running code. So your class would live in the file location of DRUPAL_ROOT\sites\all\modules\mymodule\EntityConroller.inc as an example.

Alot of times to organize code better developers add subfolders, or submodules to their modules you could for instance declare the class to live in an includes folder in your modules folder with:

files[]= includes/ExampleTaskContoller.inc

Some hook functions such as hook_views_api and hook_menu allow you to define a file location where the page callback function can be found (in the case of hook_menu) or where your views implementation classes/handlers/etc may be found in the case of views.

For instance hook_menu allows for the following 2 keys to better organize where page callback functions live in your source code:

  "file": A file that will be included before the page callback is
  called; this allows page callback functions to be in separate files.
  The file should be relative to the implementing module's directory
  unless otherwise specified by the "file path" option. Does not apply
  to other callbacks (only page callback).

  "file path": The path to the directory containing the file specified
  in "file". This defaults to the path to the module implementing the
  hook.

Views allows 1 to define where views includes lives via hook_views_api:

  path: (optional) If includes are stored somewhere other than within
  the root module directory, specify its path here.

  template path: (optional) A path where the module has stored it's
  views template files. When you have specificed this key views
  automatically uses the template files for the views. You can use the
  same naming conventions like for normal views template files.


Is there a way to use grouping settings for Bootstrap Tabs in Views?

There isn't a way at the moment to use the built in views group by function, but luckily there is a way to accomplish similar behavior if you install a contrib module called views field view.

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

The premise being, tabs separate a listing of entities into multiple groups based on a common term.

Not like this: https://monosnap.com/file/K4W6m63A1jsy7frYdL8P0LfcFQPj29

But like this: https://monosnap.com/file/Q8WsRSgJU7f8AYFMMomDmcIjyOAXZE

In order to make this work, you need two views, One with the tab output, and another contextually filtered as a field within the first.

View 1 (list of taxonomy terms) would look like this to create the labels for the tabs: https://monosnap.com/file/h3fDlfgy2HwlHT2Y3Lywe8IroagDyE

View 2 (Use a relationship to call the nodes that are referencing each term and a contexual filter to limit the nodes per term id): The view field here is the key: https://monosnap.com/file/NtIumKYmsws62o4kTAnU72mt1LPZZq

Once you have the two views you can set the argument on view 1
The view field here is the key: https://monosnap.com/file/EzgRlcjLgr0au7TIWnTLbWEosCHwcP


Remove tabledrag statuses on Ajax submit and display status message after Ajax submit

I managed to solve this finally. My answer to both questions was Ajax Commands.

To anyone looking for the solution, here's what I did:

Question 1:

Instead of messing around with Dragtable, it's easier to just re-create the form and pass it back so it replaces the original form. I had to rebuild the form in my ajax callback function, then return it with an ajax command. To rebuild the form, you needed to create a new form_state variable and use drupal_rebuild_form function like so:

function my_ajax_form_callback($form, &$form_state) {
  $new_state = array();
  $new_state['build_info'] = $form_state['build_info'];
  $new_state['rebuild'] = TRUE;
  $new_state['values'] = array();
  $new_state += form_state_defaults();

  $new_form_array = drupal_rebuild_form('my_ajax_form_id', $new_state);
  $new_form = drupal_render($new_form_array);

  $commands = array();
  $commands[] = ajax_command_html('#form-container-element-id', $new_form);

  return array('#type' => 'ajax', '#commands' => $commands);
}

The original form button that submits to this callback also should have the form-container-element-id in the wrapper element of the #ajax array (it should always be a CSS ID so it shouldn't have the # to indicate it's an ID):

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Submit',
  '#ajax' => array(
    'callback' => 'my_ajax_form_callback',
    'wrapper' => 'form-container-element-id',
    'method' => 'html',
    'event' => 'click',
  ),
);

Here's the API documentation link for ajax commands: Ajax framework commands (Drupal 7)

Question 2:

The best way to display status messages after an ajax callback is to use theme_status_messages() function. The snippet below also goes in the my_ajax_form_callback function before returning from the function:

drupal_set_message('This is a status message', 'status', FALSE);
$messages = theme_status_messages(array('display' => 'status'));
$commands[] = ajax_command_html('#status-message-container', $messages);


Display register form to logged in users

The access check is made in the user_register_form() function itself:

$admin = user_access('administer users');

...

// If we aren't admin but already logged on, go to the user page instead.
if (!$admin && $user->uid) {
  drupal_goto('user/' . $user->uid);
}

As you can see the check for the administer users permission is hard-coded. That said, I think you've got 2 options:

Grant the appropriate permission to that user role (obviously undesirable as you've mentioned).
Re-implement the user registration form in a custom module, changing the access check to a more appropriate one for your situation. You should be able to use pretty much all of the code from user_register_form() and piggyback off the validation/submit handlers, so there shouldn't be much coding involved at all really.


Usually it's better if you use EntityFieldQuery instead of db_select. See EntityFieldQuery vs Db_select()

From EntityFieldQuery use page:

  The EntityFieldQuery API lets you fetch information about entities
  (nodes, users, taxonomy terms et cetera) from Drupal without actually
  building SQL queries.
  EntityFieldQuery is a class that allows retrieval of a set of entities
  based on specified conditions. It allows finding of entities based on
  entity properties, field values, and other generic entity metadata.
  The syntax is really compact and easy to follow, as well. And, best of
  all, it's core Drupal; no additional modules are necessary to use it.

In your case:

$nodeQuery = new EntityFieldQuery();
$query = $nodeQuery->entityCondition('entity_type', 'node')
  // get only nodes that are 'published'
  ->propertyCondition('status', 1)
  // replace field_food_menu with field_TAXONOMY_NAME
  // replace 2 with the taxonomy ID (tid) you're wanting
  ->fieldCondition('YOUR_TAXONOMY_FIELD_NAME', 'tid', $SEARCHED_TID)
  // SOrt by creation date.
  ->propertyOrderBy('changed', 'DESC')
  // Retrieve only last item.
  ->range(0,1)
  // USe user 1 to query all nodes, not only those that current use can access.
  ->addMetaData('account', user_load(1));

// Get a list of nids that match given criteria (because if the use of range() a list of 1 elem, at most.
$result = $query->execute();

(Code it's not tested, probably you have to tweak it a little).

I should add that this method also checks if user is allowd to access to the nodes that returns. That's the reason for the last line, it makes all nodes available, not just those the current user can access. If you want to see only nodes for that user just remove that line.


Node taxonomy now appears vertically in Drupal 7

If you mean you want display terms in node view horizontally, then:

if your node-type is xxxx and you vocabulary name is yyyy, add this to your CSS files:

.node-xxxx .field-name-field-yyyy .field-item {
  display: inline;
}


How to share content and files with other users within the site (not in facebook or other social media)?

Besides the custom approach identified above, you may also want to look into using the Forward module.

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

It includes some basic tracking for reports as well.


How do I alter certain module form output

The form elements for fields (or "Field Widgets" as Drupal calls them) are defined using hook_field_widget_form(), e.g.

function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return array('value' => $element);
}

They use the form API, and don't have associated templates/themes unless one is explicitly set on a contained element.

You can use hook_field_widget_form_alter() to manipulate the elements; the simplest example (from the docs) would add a class to a particular element:

function hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  if ($context['field']['type'] == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

But obviously you're only limited by what the form API can do. So if you wanted to provide a specific theme for an element:

function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['type'] == 'mytype') {
    $element['#theme'] = 'MYMODULE_some_theme';
  }
}

Then it would just be a matter of implementing hook_theme() and creating the template file to do what you need.

Just for posterity (and because I accidentally answered the question with this first time round); the following relates to formatting the output of a field when its parent entity is displayed:

As listed in Drupal 7 Template (Theme Hook) Suggestions, and originally defined in template_preprocess_field(), these are the built-in patterns you can use to override specific field templates:

field--field-name--content-type.tpl.php
field--content-type.tpl.php
field--field-name.tpl.php
field--field-type.tpl.php

You could also add your own using a template preprocess hook:

function MYTHEME_preprocess_field(&$vars) {
  // This will let you use field--foo.tpl.php as the template name for any fields that pass the condition.
  if (some_condition()) {
    $vars['theme_hook_suggestions'][] = 'field__foo';
  }
}

As far as changing the order of field output goes, that's usually done through the UI in the "Manage Display" forms available for the various view modes for each entity type.


How about the modules -

Comment Notify

  Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

or

Notify

  The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.

and see Email notification for new comments


Are there any contributed/commercial themes available for Open Atrium?

Here's a bunch of them (scraped from Google cache, it seems the original page is no longer available):

Miro
Trapeze
Sandy
Scene
Mobile Gingko
Atrium Simple
UNL
Crystal

If memory serves I've had Miro installed before with good results.


adding javascript to tpl file from template.php

This is what I'm using. I don't know if this will have any gotchas in future where the template file I want is in the array but not actually used. So far it's working flawlessly.

function yourthemename_preprocess_page(&$vars) {
    $templates = $vars['template_files'];
    if (in_array('page-node-add-discipline', $templates)) {
        drupal_add_js(path_to_theme() . '/js/create_discipline.js');
        $vars['scripts'] = drupal_get_js();
    }
}

Put that in your template.php


How can I render a field inside a tpl.php that is hidden on the UI

You can add any markup or additional fields to the node teaser view or node full view using hook_node_view().
The following example is adding a taxonomy name to the teaser view.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'teaser'){
     $tname = db_query('SELECT name FROM {taxonomy_term_data} t WHERE tid = :tid', array(':tid'=>$node->field_category['und'][0]['tid']))->fetchField();
     $node->content['my_taxonomy'] = array(
        '#markup' => '<div>'.$tname.'</div>',
        '#weight' => 10,
      );
    }
}

You would not need to update node.tpl.php.


Set Views page title based on content being viewed via contextual filter

Add Title as field

☑ Checkmark exclude from display

For view title, put {{ title }}


How do I redirect to www and https in settings.php?

The caveat to the settings.php approach is 2 issues:

Your redirect requires that Drupal be bootstrapped to work. If there's a resource that bypasses Drupal (e.g. any hosted files), you're not going to see the www redirect occur.
It's arguably bad practice. settings.php is for Drupal settings; depending on your intent this might be considered a web server setting. A developer working on your project in a local environment might have trouble understanding where the redirect is coming from as standard Drupal configurations use the .htaccess file for this.

An alternative to prevent .htaccess overwriting would to be place the rewrite directive in an Apache configuration (e.g. vhost.conf if you're using virtual hosts) that defines your host.


get file path of image style as replacement patterns in views

You can get file path of image style in view.tpl

Example:

/**
 * field with image: "field_image"
 * uri:  (image from field_image) File: Path
 */

$style_name = $view->field['field_image']->options['settings']['image_style'];
$thumb_path = image_style_url($style_name, $uri);

I didn't wrote how to get $uri because it depends on type of template file. The general idea is to get a file path of image style by using image_style_url($style_name, $uri) in view.tpl file.


Drupal already ships with jQuery, you don't need to add it yourself.

Drupal 6 comes with v1.2 (can be upgraded to 1.3.2 with jQuery Update)
Drupal 7 comes with v1.4 (can be upgraded to 1.5.2 with jQuery Update, higher with the dev version).


Does creating multiple tpl files affect site performance?

It won't make a noticeable difference as long as you disable rebuilding the theme registry on production, enable caching, and follow best practices (e.g. don't execute logic or queries in your templates, and never ever save PHP code in the database). There are quite a few other, more noticeable things you can tweak to improve performance and load time before you get to the level of worrying about the number of templates.


Is it good idea to install modules, which require server config, locally? How?

The problem is having different configuration in in different environments (production, staging, local dev, etc).

Usually you have production. This is the main site. You have to move it to staging or development environment. Moving implies usually to get the production database with all new added content. But in dev environments you need some changes:

Enable development modules like devel, https://www.drupal.org/project/reroute_email, etc.
Change settings. For example, if your site uses a webservice you may change the endpoint URL to a dev webservice URL. Those settings sometimes are jsut Druipal variables but they may be custom settings stored in a module's custom tables.
Clean sensible data: user emails, user personal data like medical data, confidential content that should not be leaked, etc.

You can:

Override variable in settings.php

As @Jaypan said in comments override $conf['VARNAME'] in settings.php. This allows to easy variable override per environment.

To have more flexibility you can use Drupa 8 strategy: have  acommon settings.php in source code control  with all common config for all environments and at the end of the settings.php file load a settings.local.php wuth the per environment settings. Typically here you can a have BD config, config to access other service like your node.js, etc.

To do this add this code in your settigns.php.

# Load environment managed conf.
$conf_path = conf_path();
if (file_exists(DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php')) {
  include DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php';
}

Modify environment

Previous solution works but sometimes you need to change more than internal Drupal variables. In that case you should set up a mechanism to execute setup code in your environment. For example you may want to make sure that in your staging or local environment Stage File Proxy is enabled. You can't enable a module directly in settings.php. Also, you may need to execute a query to sanitize data.

In this case there are several options to change things according to environment:

Using hook_init implementation

hook_init is a Drupal hook that is called on every non-cached request. Here you can place code that checks some condition in your environment and changes it if needed. This solution is simple to implement, but because the hook implementation is called on every non-cached request the checks performed should be very also simple or you may hit a performance penalty.

Also, you can use hook_boot, that's executed on every request, cached or not. You have to be very carefully with this hook because of performance and because is called during Drupal bootstrap and before the theme, modules, or most include files are loaded into memory.

Creating a custom drush command

Drush allows to create custom commands. At the end, they are just PHP code executed in the Drupal context, so all Drupal functions are available. You can create a custom drush commands that performs the environment check. From here you can enable modules, perform sql queries or any other action Drupal allows.

This command should be executed when the database is loaded into the dev environment, just once. Because of this, there's no problem if the command is resource intensive as it's only executed once.

Extending drush sql-sanitize

This drush command sanitizes the database, setting same password for all users and modifying their address. You can extend it to make more tasks like executing SQL queries.

Script with drush commands

Write a custom sfript with drush commands that modifies the environment. This soltuions is simple but alloww you to make any modification done by a drush command.

For example:

drush en devel -y
drush vset myconf my_dev_value
drush sql-query "MY AWESOME QUERY"


This is the snippet I wrote for  region--login.tpl.php try this once. Hope it meets your requirements.
in template.php

 <?php
 function yourthemeName_theme() {
   $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'yourthemeName') . '/templates',
  'template' => 'region--login',
   'preprocess functions' => array(
   'yourthemeName_preprocess_user_login'
   ),
   );
   return $items;
  }
  ?>


get rid of dropdown list on views exposed filter

the 2 general options in the view are autocomplete and dropdown.  the autocomplete will give you a list of matching queries as you type.  keep in mind that if you remove that and somebody spells something incorrectly they will not get any results from the exposed filter.

if you have to get rid of the dropdown feature, use CSS to hide it.


determine custom templates in custom module hook_preprocess_page function

function my_module_preprocess_page(&$vars) {
$header = drupal_get_http_header('status');
if ($header == '404 Not Found') {
  $vars['theme_hook_suggestions'][] = 'page__404';
}
}

function my_module_theme() {
  return array(
    'page__404' => array(
      'template' => 'page__404',
      'variables' => array('xxx' => null),
      'path' => drupal_get_path('module', 'my_module')
    ),
  );
}

thanks to sareed, drush vset theme_debug 1 allowed me to see :

<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--404.tpl.php
   * page--psnmssss.tpl.php
   * page.tpl.php
-->
<!-- BEGIN OUTPUT from 'my_module/page__404.tpl.php' -->

<!-- END OUTPUT from 'my_module/page__404.tpl.php' -->

so i changed page--404 to page__404 and it worked

how could i restrict the template suggestion only for the content region of the page ?


External javascript that contains jQuery

One way to circumvent this would be by installing the jQuery Dollar module.

This would allow you to avoid $ conflicts.


Security issues after authenticated user has been logged out

Once page is stored in browser's cache, there is nothing you can do about it. It's responsibility of an user who logs in and views confidential information to remove it from device he was reading it on.

You could try to prevent caching (as described in this question), but all you send to browsers and proxies in that regard is just an suggestion, not an order. It's a good idea to do this, but sadly you can't be sure of it.

You could use javascript to go to another page if logged out user tries to go back to page with sensitive data.

And you can and should use Secure Pages to enforce encryption and thus prevent proxies from reading you data.

At the end of the day once user will get that data, data security is his problem.


I was thoroughly mistaken about the installation of the charts. After installation, I was editing the repositories section in composer.json  and running the composer command to install the specific library (eg: composer require --prefer-dist highcharts/highcharts:6.0.4) from the particular sub-module. But it has to be done from the Drupal project root directory. Appreciate your valuable time and expecting this will help others.


Redirecting %20 Based URL to Non %20 based URL

I would check the alias on the page to see if two trailing spaces exist. That's where the %20 typically comes from. %20 is an HTML encoded space character.

In the meantime, you can handle multiple links to one page using Global Redirect.

Best to get that in so your site is not penalized by search engines.


Is it possible to use Views for listing data created in a custom module?

I know link-only answers are generally frowned upon, but this series of blog posts are unlikely to ever go anywhere and are WELL worth a read:

Building Views Query Plugins: Part 1 - Mapping web service data to the Views model

Building Views Query Plugins: Part 2 - Writing and testing the plugin itself

Building Views Query Plugins: Part 3 - Exposing options and configuration

Building Views Query Plugins: Part 4 - Building custom pager plugins

Note: In the unlikely event that someone gets here and the links are dead, please comment and let me know so I can address it :-)


Strange question pertaining views as forms?

I'm not sure Views would be the way I'd go with this. It's for getting data displayed from the database and this just seems like you're stretching the scope of what it's designed to do.

Is there any reason each question has to be on a different node? That seems to be adding even more complexity.

My suggestion would be to use webform to a the form for each different quiz. Especially if site administrators will have to create the quizzes regularly as webform offers the best UI for doing this. The difficult bit then is to write some sort of add on to webform (I don't know how much of an API webform has) that changes how the form is submitted and validated to be more 'quiz like'.


global $language not working in custom module

drupal has a function that return default language language_default with the below code

    function language_default($property = NULL) {
  $language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
  return $property ? $language->$property : $language;
}

I suggest you in hook_init(maybe your fuction not called or problem realated to your fuction)  call this function

function yourmodulename_init() {
  dsm(language_default());
  global $language;
  dsm($language);
}

According drupal documentation , $language is global variable , you problem is some strange .

I thnik problem is in your function and method of calling function. by default if you put a function in module and your module enabled(after clear cache) ,the function globaly exist and you can use it everywhere (even in views on anywhere you think).

If dsm in hook_init return $language value  I suggest you test your function

function my_language_code(){
  global $language;
  return $language->language;

}

in very where you want

$lang=my_language_code();
dsm($lang);

test this please


Enable the Simplenews Rules module within the Simplenews project. It will add 2 events A user has been subscribed & A user has been unsubscribed.

Use the subscribe event combined with your Send mail action to send a message on user subscription.


How can I leave empty values in gmap field?

If you want to have an option to leave field blank, simply don't make it required. Go to /admin/structure/types/manage/your_content_type/fields/field_name and clear the "required" checkbox.


How to use Drupal Commerce subscription products?

Most probably you have got issue with your rule set. Best way to use(configure) commerce_sp or even commerce product for membership is to put proper condition & then fire the event.

Simple Config :

Create new products (using Subscription Products).
Create product displays for those products.
Go to Configuration>Rules.
Find the Rule called "Subscription Started (update)" and clone it.
Rename the cloned rule.
Make the Event "Completing the Checkout Process". Add some more like "user of type" etc.
Make the Elements "Order contains a particular product" and specify the SKUs of your subscription products.
For Actions, use "rule set: Subscription start" with parameter as "User:[commerce-order:owner] and "Schedule component evaluation" as is and added "Add user role" with Parameter: User:[commerce-order:owner] and Roles: my subscriber role.
Set the low weight for this rule set.

You can modify rule as per your requirement & it will work accordingly.


How to add other types of dynamic attributes in the BODY tag?

I think, i found the right solution below:

  if ($node) {
    $variables['attributes']['class'][] = 'page-node';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page';
}

  if ($tid) {
    $variables['attributes']['class'][] = 'term-page-' . $tid->id();
}


How to move node contents from local to server environments?

Consider using module Backup and Migrate. From the modules project page:

Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.
With Backup and Migrate you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.


I'm not sure about one module to do it all, but Enabled Modules will show you the list of modules and their versions.

To view a sites status, and Drupal version, you can log in and visit admin/reports/status


how to tell which book node is the root node programatically

You can try to build the menu tree for your book. Book nodes do not have direct parents. The relationship is defined by the menu structure.

This will give you the structure of the book menu.

$book = $node->book;
$tree = menu_tree_all_data(book_menu_name($book['bid']));


Add a div at end of the form so that i can display data over there

Try this:

$form['my_markup'] = array(
  '#markup' => '
Lorem ipsum
'
);

Check the documentation at
http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#markup


How do I set up a More Link in a View's Pager?

You need to make display as page then only more will work. For more details https://www.drupal.org/node/450736.

You can also create block and activate ajax for better functionality. Show more/load more modules implements this sort of functionality. You can follow that.


How to pass Get parameter to url when url has "?" mark

If you are redirecting from the form submission handler, you need to use code similar to the following one.

$form_state['redirect'] = array(
  'listings',
   array(
     'query' => array(
     'field_list' => '3',
   ),
);

That code is equivalent to calling drupal_goto('listings, array('query' => array('field_list' => '3')) which should never be used inside a form submission handler. In both the cases, the function that is called to build the URL is url(), which works when clean URLs are enabled, or not.

  // With Clean URLs.
  if (!empty($GLOBALS['conf']['clean_url'])) {
    $path = drupal_encode_path($prefix . $path);
    if ($options['query']) {
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
    }
    else {
      return $base . $path . $options['fragment'];
    }
  }
  // Without Clean URLs.
  else {
    $path = $prefix . $path;
    $query = array();
    if (!empty($path)) {
      $query['q'] = $path;
    }
    if ($options['query']) {
      // We do not use array_merge() here to prevent overriding $path via query
      // parameters.
      $query += $options['query'];
    }
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
    $script = isset($options['script']) ? $options['script'] : '';
    return $base . $script . $query . $options['fragment'];
  }


How to add a dynamic select field to a content type form?

You can probably do that using the field API and setting an allowed_values_function for the list field.

e.g:

/**
 * Implements hook_form_alter
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

  if ($form_id == 'field_ui_field_settings_form') {
    // Make the allowed_values_function editable as a textfield
    // Possible to inspect $form or $form_state to vary by field
    if(isset($form['field']['settings']['allowed_values_function'])) {
      $form['field']['settings']['allowed_values_function'] = array(
        '#type' => 'textfield',
        '#title' => t('Allowed value function'),
        '#description' => t('Returns an array of allowed values'),
        '#default_value' => $form['field']['settings']['allowed_values']['#field']['allowed_values_function']
      );
    }
  }

}

The allowed_values_function then returns an array of values for the field.

e.g:

/**
 * Allowed values callback
 */
function MYMODULE_custom_field_allowed_values($field){

  if(CONDITION){
    return drupal_map_assoc(array('A1','B1','C1'));
  }elseif(OTHER_CONDITION){
    return drupal_map_assoc(array('A2','B2','C2'));
  }

}


How to disable "all" option from contextual filter?

Ok, found it. In the contextual filter there is an "Exception" option that you can expand. "all" seems to be added by default for all contextual filters.


How to apply one AJAX to all form elements?

I don't believe there's anything 'built in' for that, but a small recursive function would handle it:

function _MYMODULE_apply_ajax(&$element, $ajax) {
  $element['#ajax'] = $ajax;
  foreach (element_children($element) as $key) {
    _MYMODULE_apply_ajax($element[$key], $ajax);
  }
}

Where you apply this kind of depends what you need. You could add it at the end of the form function itself, but if there's a chance your form could be altered it would be best in hook_form_alter(). Either way just call

_MYMODULE_apply_ajax($form, $ajax_array);


You can use code similar to the following one, used by the Node module in node_filter_form().

  // Build the 'Update options' form.
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#attributes' => array('class' => array('container-inline')),
    '#access' => $admin_access,
  );

  // ...

  $form['options']['operation'] = array(
    '#type' => 'select',
    '#title' => t('Operation'),
    '#title_display' => 'invisible',
    '#options' => $options,
    '#default_value' => 'approve',
  );

The key is the line settings the "#attributes" attribute to "container-inline."

That code is for Drupal 7; the equivalent code for Drupal 6 starts with the following code:

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('Update options'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

Supposing you are using Drupal 6, then your code should be changed to something similar to the following one:

function contact_register_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('Sign up to be notified when your community launches:'),
  );

  $form['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email'),
    '#prefix' => '
',
  );

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

  return $form;
}

I didn't put the description inline, as it would not be correctly rendered because it is using a "item" form field. I also find that inlining the description would cause the form to take too much space. (Imagine what would happen if the inlined description would be longer, and placed in a single line.)

The CSS styles that Drupal 7 adds to container-inline elements are the following.

/**
 * Inline items.
 */
.container-inline div,
.container-inline label {
  display: inline;
}
/* Fieldset contents always need to be rendered as block. */
.container-inline .fieldset-wrapper {
  display: block;
}

They are added from system.base.css.


Get the user id for triggers when deleting a user

Sounds like a job for hook_user_delete():

  Respond to user deletion.

  This hook is invoked from user_delete_multiple() before field_attach_delete() is called and before users are actually removed from the database.

  Modules should additionally implement hook_user_cancel() to process stored user data for other account cancellation methods.

e.g.

function hook_user_delete($account) {
  db_delete('mytable')->condition('uid', $account->uid)->execute();
}


Views : Use a custom template field even if it's excluded from display

To use the custom template for a particular field you should use the template suggestion from Theme:Information from advance section of your view, Select the suggestion template form the them info as the screenshot for field NID
 . Create that template inside the your_theme/template folder. Don't forgot to clear the drupal cache.


Create a Views that displays all unused taxonomy terms

This can be achieved by View relationships and aggregation

1) Add a new view of view type "term"

2) Add Field Taxonomy: Term Name

3) Add Relationship "Taxonomy term: Content with term"

4) In the View : Advanced section , Enable Aggregation

5) Add new Filter nid, Aggregation type = Count DISTINCT , Select Relationship = node , Operator= equal to , Value= 0


How do I disable the "Continue to payment" button before the shipping method is selected?

I would've assumed form states would do the trick, but without seeing the code you've tried, it's hard to say what the issue might be. That said, we did just get the patch into Commerce Shipping that automatically calculates shipping upon full address entry and recalculates it on address change. I believe that may resolve the issue that led you to look into this in the first place. You can upgrade to Commerce Shipping 2.x-dev or apply this patch: https://www.drupal.org/project/commerce_shipping/issues/2849756#comment-14030351


Ajax form works on page but not on block

Did you create the form in a separate file?  If you did, then it makes a big difference where in the main .module file you put the module_load_include() function to bring in the form.  I had this problem because my form definition was in a .inc file, but when I moved module_load_include() from hook_node_view() to hook_init(), it worked fine.

Edit:  Wait, better answer:  hook_init() isn't called on cached pages, so may not be the way to go.  Instead, call module_load_include() wherever it makes sense (e.g., hook_node_view() or hook_block_view()), but use form_load_include() within your form definition, like this:

function my_ajax_test_node_form($form, &$form_state) {
  form_load_include($form_state, 'inc', 'my_ajax_test', 'my_ajax_test.forms');
  $form['my_ajax_test_div'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
  );
  return $form;
}

Once the file has been loaded with form_load_include(), it will be loaded anytime the form is called.


How to get the real sql query of a view?

The query displayed in the administration UI contains database prefixing brackets. You can remove those brackets to have valid SQL that can be executed by any SQL client.


Found the problem, i use the More buttons module and there seems to be something wrong with way the hook_form_alter is handled in the module, fortunately there is a fix.


Order style-sheet list when adding custom one via template_preprocess_page()

OK, of course, a few moments after adding the question I saw what was wrong. Since I did not specify the type it added my style-sheets it added it to the end of the modules. I now added the theme type and it was added at the end of the list.


I want to implement this dragging functionality in Drupal 8,
may i know how you achieve draggable functionality in that or can you share the code


Is the theme on the test site and the live site the same theme with the same regions defined. The drupal theme() function is complaining that regions are not defined which the body (node) content is trying to be placed in.


Is there a way to set the active menu's text as page title?

I found the answer with this link http://sivaji.drupalgardens.com/how-set-custom-page-title-drupal-7.

There exists no way to dynamically set the active menu as the page title, but with the Classes_array from the vars, we can check the page's id and then set the page title as per our need.

In my case I used a if check to check the page id (Page-contact's page title to Contact) and so. It worked for me though, but still found no way to dynamically set the title from the active menu !


Rewrite taxonomy_term_reference urls to read /taxonomy/term/(name)

You should be able to set URL aliases for your taxonomy terms using the Path module that comes with Drupal core. (EDIT: As mentioned by jordojuice, you'll also need the Pathauto module to automatically generate these patterns in the manner I instruct below).

Go to the Configuration menu and select "Url Aliases" in the "Search and Metadata" section. (admin/config/search/path)
In the upper tab of the URL Aliases menu, select "Patterns." Here you can set the path to your taxonomy terms to whatever you'd like.

The only problem is that I don't think Views overwrites the URLs generated. There was a module for this in Drupal 6, but I don't think there is anything similar for D7.

There is a View that comes default in Views that should overwrite the default taxonomy paths; you could see what it does and try to tweak it.


Google indexes the page using the domain alias

It really depends on what page Google finds first, I guess. So, I do now know.

  Why is the alias shown in Google search results, and not the root domain?

However in order to overcome this, you would have used the global redirect in Drupal 7, which has been merged with Redirect. I have not tried it, but if it an exact port it should still be able to.

  Checks if the current URL is the same as the site_frontpage and
  redirects to the frontpage if there is a match.


Is there any template debugging technique similar to Twig debugging?

As reported in Working with template suggestions, yes.

  As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments). To enable it, add this line to your settings.php:

$conf['theme_debug'] = TRUE;

As said in that page, you can use Drush to enable/disable it, respectively with drush vset theme_debug 1 and drush vset theme_debug 0.

After you set theme_debug to TRUE, the source of the page will appear as follows.

<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.tpl.php
   * page--node.tpl.php
   x page.tpl.php
-->
<!-- BEGIN OUTPUT from 'modules/system/page.tpl.php' -->

<!-- END OUTPUT from 'modules/system/page.tpl.php' -->


fields.title.content in views-view-fields--n--block.html.twig won't display

Just found out that my title fields' name is title_1.

this is what brought the solution:

    {% for key, field in fields %}

key: {{ key }}

    {% endfor %}

This shows all fields from the view in the template file.


Restrict the node local tabs access to specific content types

Yes, routing is correct. Routes specify access rules, if you want your route to only be accessible for a certain node type, implement custom access callback and check for that.

The local task will then automatically respect that.

Example from core:

comment.reply:
  path: '/comment/reply/{entity_type}/{entity}/{field_name}/{pid}'
  defaults:
    _controller: '\Drupal\comment\Controller\CommentController::getReplyForm'
    _title: 'Add new comment'
    pid: ~
  requirements:
    _custom_access: '\Drupal\comment\Controller\CommentController::replyFormAccess'

That method then can receive the same arguments as the controller/form, in your case the node (just add NodeInterface $node) and you can check the type there and everything else you want (like permissions)


How to hide views UI reaching number of limits of searches

You can Set a configuration variable for each user (it's equal variables on drupal 7 ) and for each search increase it,reset it each day,But another and simple method is  implement it by cookie , create a cookie for user, set expire to 24 hours, and every time user search, first check it's cookie and if not do it more that three times  show results for him/her else  there is nothing to him/her.I think cookie solution is good for you.


Custom form multiple file upload with different extension

You can use '#type' => 'managed_file' instead of    '#type' => 'file'

managed_file types is powerful tools support any kind of files format with ajax upload.

example :
$form['file'] = array(
        '#type' => 'managed_file',
        '#name' => 'files[]',
        '#title' => t('Upload some photos'),
        '#attributes' => array('multiple' => 'multiple'),
    );

you can also add upload location of files like

'#upload_location' => 'public://myfiles/'

for more info.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#managed_file


Unfortunately, the short answer is: No, you cannot use other wildcards.

The reason is the use of preg_quote inside drupal_match_path, any regex wildcards you add to your pattern will be escaped.

P.S.: Very cool question, had to take a good look at this.


If you can display the Full & Teaser view modes, then you can display any custom view modes, too.

Install the Display Suite module and create a new 'view mode' - let's call it "body" - and on the same screen, make sure it's applied to nodes. Then go to Structure -> Content Types -> Article (or whatever your content type is called) -> Manage Display, and you will see three tabs: Default, Teaser and Body (the view mode you just created). Scroll to the bottom of the page and choose a layout (single column should do the trick), and then drag the body field into the appropriate region. Don't forget to save the form after rearranging fields.

At this point you can go into your view, and select the new 'Body' view mode where the options for 'Full' and 'Teaser' were showing up earlier.


Markup being stripped from form element title

In Drupal, strings need to be passed through the t() function for translation. This function uses string replacement to sanitize text. When passing links, the HTML should be put in the string, and the URL passed as a variable prefixed with a colon:

$tc_link_label = t('You agree to the terms and conditions', [':url' => Url::fromRoute('<front>')->toString()]);
$form['field_terms_and_conditions']['#title'] = $tc_link_label;


How to get change event working of a taxonomy select box on a node form?

This isn't really a Drupal question, but at a guess I'd say the problem is that you're binding the event to an element before the DOM has loaded...so the element doesn't exist yet. You should use one of the standard jQuery methods to run your code when the document is ready, e.g.:

$(document).ready(function() {
  $('#taxonomy-select-box-id').change(function(){
    alert('change');
  });
});


REST resource for specified content type

I mean if let users post data to Content type, they can Post data to
  all of my content types and I didn't find any option to restrict to
  specified content type.

Doesn't /admin/people/permissions stop them?

Permission

Basic page: Create new content
Article:  Create new content

  and for some content type GET exists

Don't you have to create a views rest export first before data is available to GET?

You can restrict here by adding a filter of type to your view.


theme_blocks() was only available for Drupal 5 & 6, which is why your code isn't working.

The D7 equivalent is block_get_blocks_by_region(), e.g.:

$variables['above_comments'] = drupal_render(block_get_blocks_by_region('above_comments'));


how to print sql query of view in runtime

The Devel module provides a SQL query log for debugging/performance testing. You can enable this under Configuration > Development > Devel settings (/admin/config/development/devel) and by setting Display query log option.

Once enabled, the bottom of the page will contain all SQL queries executed in page rendering. For your needs, you'll need to look for views_plugin_query_default::execute function calls (the where column) to see the SQL query executed for your view.


How do I customize node.tpl to print an entity reference field in a specific format

I think your information architecture in inverted. It sounds more like Book is in Collection rather than Collection has Book. In other words Collection is an attribute of Book, not the other way around. It would be easier to put the reference field on the Book content type, and create a view of all Book s referencing a Collection to display on the Collection content type, using a Contextual filter to limit the list. No changes required to template files!

Then using the Prepopulate module, you can use the $_REQUEST variable to set your field_book value in the new node, and it is a simple matter to add  the Content:Nid to the view and rewrite the field to create the link.

First, install and activate the Prepopulate module. Then put your Entity Reference field on the Book content type and limit it to the Collection content type. Then add an Entity reference field to the Annotation content type and limit it to Book. In other words, you are identifying the Book the annotation belongs to.

Then create a view of Content (Book) with a display type of Block. In the views configuration, create a Contextual filter on Content: Collection (field_collection) and configure it to Provide default value and select Entity ID from URL.

Add the field Content:NID and configure the field. Select Rewrite results  and check Rewrite the output of this field. In the text box enter something like:

Annotate this book

(%5B = "[" and %5D = "]"). The actual link code may vary depending on how you have implemented the Entity reference field in your content type. The module has good documentation.

Save your view and under /admin/structure/block find the block created by the view and set it to display only on pages of type Collection.

The block will then display a list of book titles (linked to their content) and the custom link to add an Annotation page with field_book prepopulated, and limited to those books which reference the Collection being viewed.


Redirect beating out URL path and creating redirect loop

This has since been corrected with an update to the redirect module.

There's now an "enabled" field on redirects, and when a conflict occurs (e.g. a new active alias is entered when that path is already a redirect), the redirect becomes disabled.


Is there a way to programatically create a commerce coupon fixed amount?

Using this tutorial and the above modules/code It makes making a commerce coupon fixed amount (or in this case, a gift card) easier to see.
The only difference between making a regular coupon and one with a fixed amount is that the product (gift card product) price needs to be loaded before hand and the amount of the coupon being created upon gift card purchase needs to load the price from that gift card:

$coupon->commerce_coupon_fixed_amount[LANGUAGE_NONE][0] = array(
'amount'  => $product->commerce_price[LANGUAGE_NONE][0]['amount'],
'currency_code' => $product->commerce_price[LANGUAGE_NONE][0]['currency_code'],
);


Checking for custom view mode inside twig template!

Assuming that's the node template, you have a view_mode variable available:

{% if view_mode == 'foo' %}

{% endif %}


How do I change the "Access Denied" message?

For Drupal 7 & 8, you can set your access denied page and your page not found page easily. Go to /admin/config/system/site-information and review the error page section.


See https://drushcommands.com/drush-7x/registry-rebuild/registry-rebuild

drush rr has the option:
--no-cache-clear : Rebuild the registry only, do not clear caches.

drush rr rebuild the registry + clear the caches.
drush cc clear the caches only.


How do I customize the html of each field in a view?

If you are create any content type and select any content type name ex : your created a "news" is content type and many field as a 'id','name' etc.

after you have add a one php file name as a 'node--news.tpl.php'

and clear caches

this file always call a news content data


I created a test site with Flag and Views module enabled and so far, I could create a view to display users who have poked me.

Create a new Flag to flag users. This don't have to be a global flag. Flag text could be "Poke" and unflag text could be "remove".

  Users are presented with a list view of other users
  Users click the "poke" flag link on a single user

Create a view on users table
Add a new relationship: Flags: User.
Uncheck "Include only flagged content "; Choose the poke flag; By: Current user.

You will see a new field "Flags: Flag link". Add it.

You will now get a view that shows users and a flag link to flag them. Modify the View as you wish.
http://paste2.org/CGZshUFN

  Users then browse to /pokes/ and view all other people that have poked
  them

This is a really tricky part.

Create a new View on users table.
Add a new relationship: Flags: User flag.
Uncheck "Include only flagged content "; Choose the poke flag; By: Any user.

Add a new contextual filter: Flags: Content ID
Under contextual filter settings, choose the just-added relationship and set to user the current logged in user ID.

Now we have access to a list of user IDs that has flagged the currently logged in user.
Add a new relationship: Flags: User
Under this relationship's settings, check "require this relationship".
Add a new field: User: name and choose the relationship created in step #7.
Add a new relationship: Flags: User flag (yes, you are added one already in step 2 but go ahead).
Under this relationship's settings, choose the the user relationship created at step #7. Uncheck "include only flagged content"; By: current user.

Add a new field: Flags: Flag link and choose the relationship created at step #10.
http://paste2.org/tkWg99vp

Above step 12 will add the "flag back" type link that the user can see a list of users who have flagged the current user and a link to flag them back.
You will need many Views template tweaks to adjust the wording of the View to suit your need.

Good luck!


What's the correct way to include JavaScript dependencies into modules?

There are a couple of ways you can do it. One way is to define a remote JS resource in your libraries.yml.

See the "CDN/Externally hosted" section here: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

I do this for AddThis (which can be done at the theme or module level) and Fontkit. This is an approach you can take with jQuery plugins that are available via CDN. As long as that resource is available, all you have to do is attach it when needed.

For Javascript that has no external hosting, like CKEditor plugins, I write in the README to download the plugin to libraries/(plugin name) of the docroot. There is no way, that I know of yet, to automate that process. This also requires writing into hook_requirements in the install file of the module to check that the file exists on the server before installing.

Another way, you could have composer do a bower install or npm install:

https://stackoverflow.com/questions/25122187/using-composer-to-install-npm-and-bower-packages-on-production-i-e-no-devdepen

Though, it would require the user to have all of those tools installed, and to be a composer user. One gap for that right now is if someone grabs the tarball off drupal.org or uses drush to get your module, none of that would work and they'd still be missing packages. Pathing could also be a headache when trying to write these commands to work for everyone, as well. Composer usage hasn't gained as much traction yet as it needs to beyond developers, but it will become more important moving forward. For example, modules requiring PHP packages (like Search API) simply cannot be drush installed or downloaded from drupal.org and manually placed - a method many, many site builders still use.

Others would say to just stick it in your module, but unless you wrote the plugin, that is against the Drupal licensing/contrib guidelines regarding third party code.


How to grant access to anonymous users to submit contact form in webform module

You understood wrongly, the image you posted is for webform submission results, meaning permission to access the results of the webform after submitted.

You need to give permission in the webform itself, simply go to that webform and then click the form setting tab and then give permission for anonymous user.


db_fetch_array() fetches only one row from data table, even though I am expecting multiple results

Every time I have to take results outs of a database query result resource I'm scratching my head wondering why we don't have a way to return all rows without having to iterate over the object.  Perhaps there's a method out there in cTools or Drupal 7 but until a better answer is presented:

$results = db_query("SELECT nid from {og}");
while($row = db_fetch_array($results)) {
  $group_node_nids[] = $row['nid'];
}


how to automatically fill in an entity reference field using rules in Drupal 7?

All is well. It works. (finally) I had to recreate my sandbox site and it worked. I installed only the necessary modules.
So beneath the steps in my rule.

After saving new content of type 'story'
Create a new entity
Parameter: Entity type: Node, Content type: article, Title: article related to nid..., Author: 2
Provides variables: Created article (article_created)
Save entity
Parameter: Entity: [article-created], Force saving immediately: true
Set a data value
Parameter: Data: [node:field-myref], Value: [article-created]

(if I didn't have the action 'save entity' it would override the node that was originally used as the default setting in the reference field on the management of the story content type, just so you'd know)

So what was the problem?
I'm not sure, it was probably a conflict with a certain module. I was thinking of the 'clone module'.


Multi-language with domain name specific doesn't work

I found the answer for this.

I have installed global redirect module and now it's working.

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

But Now I am having another one problem.My language Switcher block is not working.When I switching from one language to another language the recently switched language url displaying for all languages...


Date time formats: October not correctly written in German

The name of the month can be change via interface translation - see comment of Drupaler


Can I change the post's created date format?

Yes you can. As an admin you can access "Administration » Configuration » Regional and language » Date and time", where you can define date formats and and display types. The latter you can then use in the "Manage display" part of an entities field configuration, or in the view display options of date fields.

Edit: If that doesn't work (which it doesn't for default node displays) and adding preprocess code is not an option (as the OP declares), another option is to hide the "created by" output (content type settings) and adding an own date field that you can fully control. This one will not, out of itself, be set to the current date when creating a node. Though, that might be an option in the field settings, have to look.

Anyway, code level change would be trivial, but without touching code, this is one of those Drupal WTF moments.


What is $delta for in Field API hook_field_widget_form?

See the answer to my question re; delta field in views.  I got an answer for $delta as well.


How to attach a CSV file with the Google Chart API?

To my knowledge there is no way using Google Chart API to "* to upload a csv file and the data comes accordingly*" (as in your question).

However, you may want to have a look at the Easychart module as a possible alternative (which already has an official release for both Drupal 7 and Drupal 8).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
It supports pasting of CSV data to create charts from it.
overheid.vlaanderen.be contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

Especially the bullet about "It supports pasting of CSV data to create charts from it." seems close to what you're looking for.

Resources:

Module documentation.
Video demonstration.


How to add another option to promote an article content to?

form_alter will allow you to add another option

eg

hook_form_alter(&$form, &$form_state, $form_id){

     $form['my_field]['#options'][] = array('id' => 'value');

}

however, that in itself will not promote it, just allow you to set a value that can be picked up by a view or other means


How to create multi level subgroups in organic groups?

Apparently, there is a module for this: Subgroups for Organic groups

According to the module description,

  This module enables a user with the proper permissions to build group
  hierarchies (or tree) by nesting groups under other groups. Simple or
  complex group hierarchies can be easily created.


If I understand well your question, you can use theme_menu_item_link() function to your template.php of your theme.

This is an example that I have tested (in this example Garland is the theme used, so you must replace the name of the function with the respective name):

Here is the example menu:

This is the function to remove the items:

function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] != 'item 1') {
    $link['localized_options'] += array('html' => TRUE);
    return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
  }
  else {
    unset($link);
  }
}

Please note that I have added if($link['title'] != 'item 1'){.. to detect the menu item, and remove it (with unset($link)).

This is the code for changing the text:

function garland_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if ($link['title'] == 'item 1') {
    $link['title'] = 'new text';
  }

  $link['localized_options'] += array('html' => TRUE);
  return l('' . $link['title'] . '', $link['href'], $link['localized_options']);
}

Remember to clear the cache to see the changes.

I found these other resources related with theme_menu_item_link(): http://drupal.org/node/245156, http://drupal.org/node/249864, http://drupal.org/node/417482.


Like Countzero said, regions is the Drupal way. If we have a look at the seven.info file of the Drupal theme Seven:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

You could simply add your banner here.

regions[content] = Content
regions[banner] = Banner
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

page.tpl.php would be the best place to print your banner, again we have a look at the Seven theme.

  <?php print $breadcrumb; ?>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>

<?php print $title; ?>

  <?php endif; ?>
  <?php print render($title_suffix); ?>
  <?php print render($primary_local_tasks); ?>

<?php if ($page['banner']): ?>

<?php echo $page['banner']; /* echo is faster then print */ ?>

<?php endif; ?>

  <?php if ($secondary_local_tasks): ?>

<?php print render($secondary_local_tasks); ?>

  <?php endif; ?>

    <?php if ($messages): ?>

<?php print $messages; ?>

    <?php endif; ?>
    <?php if ($page['help']): ?>

        <?php print render($page['help']); ?>

    <?php endif; ?>
    <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
    <?php print render($page['content']); ?>

    <?php print $feed_icons; ?>

Hope this helps. Of course this is absolutely basic stuff and should only help you getting started.


warning message after uprgraded to drupal 6.38

system_requirements will raise this warning if the core Update status  module is not installed.

To 'fix', enable the core Update status module.


Replacing a 'Teaser'-themed node in a View its it's 'Full Content'-theme using ajax in Drupal 7

You can try using the jQuery load method.

$('#teaser').load('node/exampleid #node-container');

Replace your teaser data with full-text.

The second method is to load hidden full-text with teaser in view; then, via jQuery on click method, just replace teaser by hidden-text.


Should I call my function in Drupal custom modules?

Do not get confused with drupal hooks and functions.

Drupal Hooks:

They allow you to interact with core functionality without hacking it. In our custom module we implement hooks which are invoked by drupal at the event the hook is exposed for automatically. So consider the hook_init(), so when drupal is initialized the system will look inside each contributed, custom module if any of the module has implemented hook_init(), and if so, drupal will invoke functionality written inside the hook implementation for every single module in the order of their module weight.Basically all we do is implement the hook in custom module and clear the caches (clearing the caches is important step as drupal caches all hook implementations so that it doesn't have to look inside every enabled module files to find if there is a matching hook implementation in order to be executed, but since a new hook is added to system we have to clear the cache so that drupal can rebuild information about implemented hooks.), we never explicitly call the hooks, as they are invoked by drupal system itself.
So hooks are kind of functions invoked by drupal itself.

functions:

Set of code which gets executed when called explicitly.

About your code

  /**
    * Implements hook_init()
    */
    function myregistration_init(){
      global $user;
      if ($user->uid == 0  && $_GET['q'] == 'order_translaton' ) {
        drupal_goto('user/register');
      }
    }

About your code:

function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
  function myregistration_submit(&$form,&$form_state) {
    $form_state['redirect']= 'order_translaton';
  }
}

I am not sure why this code is working, it should be rather like following.

/**
  * Implements hook_form_alter()
  */
function myregistration_form_user_register_form_alter(&$form,&$form_state){
  $form['#submit'][] = 'myregistration_submit';
}

/**
  * Custom submit hanlder.
  */
function myregistration_submit(&$form,&$form_state) {
  $form_state['redirect']= 'order_translaton';
}

Both hook implementation codes above should work, but you might need to clear your caches after implementing the code. But do not call it explicitly anywhere in code.


Commerce: How to skip checkout cart and redirect to PayPal

It's not possible without custom code. The customer either initiates the Express Checkout payment by clicking the button form on the cart page, or the Commerce PayPal module does it on a form submission when the customer chooses PayPal as a payment option on the checkout form. That requires sending an API request to initiate the payment and get the tokens that must be passed with the customer to PayPal to submit payment. With custom code you could simulate the customer choosing PayPal as a payment option on the checkout form and initiate the redirect, but there's nothing that exists to do that that I've seen.


CKeditor not showing for authorized users

it would be helpful if you could share a screenshot.
However, if you have not yet done so, verify that the CKEditor's permissions are enabled for that role and be sure to also verify the permissions of the directory where the module is located.


Add captcha to last step of multi-step form

use this code in your template.php, you need to know what the ID of the last form is,

<?php
function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
    if ($form_id == "YOUR_FORM_ID") {
            $form['my_captcha_element'] = array(
                '#type' => 'captcha',
                '#captcha_type' => 'Math',
            );
        }
}
?>

you can also replace the Math with image


Redirect to a custom page after a node has been added or edited

function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

The code redirects the form independently from the button clicked to submit the form. If you want to redirect a form only when a specific submission button is clicked, then you should used the following code.

function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

The form ID doesn't contain hyphens. The form ID is the name of the PHP function that generates the form (a.k.a. the form builder), and a PHP function cannot contain hyphens in its name.
The form ID is passed to the implementations of hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and hook_form_FORM_ID_alter(). hook_form_FORM_ID_alter() doesn't really need it, as it is called for a specific form, while the other two hooks are invoked for more than one form.
The first function is the implementation of hook_form_BASE_FORM_ID_alter(); in this case, the base form ID is "node_form" that is the base form for the node edit form.
The node edit form contains $form['#node'], which is the node object for the object being edited; "custom" is the short ID for the content type you want to redirect the users once they edit a node.
Altering $form_state['redirect'] from hook_form_alter() doesn't have any effect; it needs to be set from a submission handler.


Using FormState::setError() in Form::submitForm()

The Drupal form system, isn't really built for what you are trying to do. I see two ways of going about this:

Webservice validation

If the webservice can do a validation of the data or such a method can be added, you can use the form system as is, and use ::validateForm to validate via webservice.
Rebuild form

What you can do, instead of doing a "validation" is to delete your ::validateForm method entirely and just send the data to the webservice in the ::submitForm. If the operation fails, you can rebuild the form and display a message to the user. You can make it appear as a validation error even though it technically isn't. Drupal does something like this as well. Fx in NodeForm::save

public function save(array $form, FormStateInterface $form_state) {
  ...
  $node->save();
  ...
  if ($node->id()) {
    ...
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
    $form_state->setRebuild();
  }
}

So basically, you can use $form_state->setRebuild() and drupal_set_message to make something that mimics validation in the submit handler. You can also save data in the store ($form_state->setStorate($data)) which you can use the form method to display error message or something else to the user.


Try

 return empty($data->_field_data['nid']['entity']->field_poloha_obce_pol['und'][0]);


You didn't deserve the downvote: this is a perfectly good question, one that has simply no answer anywhere on the web yet. All of them only speak about dependent dropdowns in forms, not custom fields where we have two extra problems: first, being out of real form context when setting up ourselves, second, potentially being multivalued.
It took me some time to figure it out but here it is. We're extending a FieldItemBase:
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $id = $this->fieldDefinition->getUniqueIdentifier();
  $wrapper_id = "XXX-$id-$delta-replace";

  $selected_value1 = $items[$delta]->value1 ?? 0;
  $element['value1'] = $element + [
    '#type' => 'select',
    '#options' => $value1_options,
    '#empty_option' => '---',
    '#default_value' => $selected_value1,
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'method' => 'html',
      'callback' => [$this, 'getValues'],
      'wrapper' => $wrapper_id,
      'progress' => [
        'type' => 'throbber',
        'message' => NULL,
      ],
    ],
  ];

  $selected_value2 = $items[$delta]->value2 ?? 0;
  $element['value2'] = [
    '#type' => 'select',
    '#empty_option' => '---',
    '#default_value' => $selected_value2,
    '#options' => $this->loadOptions($selected_value1),
    '#prefix' => "
",
    '#suffix' => '
',
    '#validated' => TRUE,
    '#weight' => 2,
  ];

  $element += [
    '#type' => 'container',
    '#attributes' => ['class' => ['container-inline']],
  ];

  return $element;
}

Fill value1_options with the options of your first dropdown. Change wrapper_id as you please but we don't know the actual ID the select will receive, so we have to make sure we make it unique in some other way (note that there might be more than one of the same custom field type in the final form, so using the name and the delta only will not suffice).
Using '#validated' => TRUE is usually frowned upon but this is the only easy way to make sure the second select will not result in an "Illegal choice" validation error after we replace the options without the form being aware of the possible values. One standard advice is to pre-fill the second dropdown with the union of all possible values, making sure that later dependent lists always use a subset of that full list but this wasn't really feasible in my case (or any other really dynamic case). Dependent lists in custom forms can simply return the original form element, so this doesn't apply to them, but custom fields can't locate the actual corresponding $form[] element, so this is the best I could come up with. It works.
Next, the function that loads the options of the dependent dropdown, depending on the value selected in the master one:
private function loadOptions($id) {
  $options = [];
  if ($id) {
    // load whatever options belong to the value of $id
    $options = ...;
  }
  return $options;
}

And finally, the Ajax glue to hold it together:
public function getValues(array &$form, FormStateInterface $form_state) {
  $triggeringElement = $form_state->getTriggeringElement();
  $selected_value = $triggeringElement['#value'];
  $html = '';
  $options = $this->loadOptions($selected_value);
  foreach ($options as $key => $value) {
    $html .= "<option value='$key'>$value</option>";
  }

  $ajax_response = new AjaxResponse();
  $wrapper_id = $triggeringElement['#ajax']['wrapper'];
  $ajax_response->addCommand(new HtmlCommand("#{$wrapper_id} select", $html));
  return $ajax_response;
}

If you compare the whole lot to the custom form solution, it's mostly the same but there are small differences in how to identify the correct element and how to actually replace the options of the dependent list that make this work in the field case.


Can I delete nodes of a given content type with Drush?

Install the devel module, and use drush to delete all the nodes,

$  drush genc --kill 0 0

You can also give a type option,

$  drush genc --kill --types=article 0 0