How can I pass more resource IDs with a single request?

Implement hook_services_resources().
function example_services_resources() {
  $resources = array();
  $resources['einvoice'] = array(
    'actions' => array(
      'search' => array(
        'access callback' => '_example_resource_access',
        'callback'        => '_example_resource_search',
        'help'            => 'E-invoice online checker.',
        'file'            => array(
          'type'   => 'inc',
          'module' => 'exmaple',
          'name'   => 'resources/exmaple.resource',
        ),
        'args'            => array(
          array(
            'name'        => 'input',
            'optional'    => FALSE,
            'source'      => array('data' => 'input'),
            'type'        => 'string',
            'description' => 'Put the query string to get some data.',
          ),
        ),
      ),
    ),
  );
  return $resources;
}

In the example.resource.inc file, you put the functions declared  in that hook.
function _example_resource_access() {
  return TRUE;
}

function _example_resource_search($input) {
  // To do something you want.
}


How to the set permission of content types for a specific user role?

If you want to set permission from admin panel then goto /admin/people/permission after find your content (view/edit) and set the user role (anonymous/ Authenticated/ Administration) permission. but if you want to set it problematically then visit https://docs.drupalcommerce.org/commerce2/developer-guide/products/theme-product  (Drupal 7 - A Simple Content Type: Permissions & Access)


Is it possible to update Drupal page cache right after it is cleared?

Cache Warmer Module is the one you are looking for.

  cache_warmer is a drush command that hits a set of URIs of a drupal
  site based on the freshness of the content.

It is a drush integration for warming the caches using httprl, which means calls can be made parallely as well.

Since it is a drush extension you can tie it up easily with your cron as well.


Posting my comment as answer - Check for HMS (Hours Minutes Seconds) Field module.

  Displays a integer formatted as Hours, Minutes or Seconds.
  The field stores values as integer. Both input and output can be formatted as Hours, Minutes and/or Seconds. Alter functions provides developers a way to add their own format.


HTML after label radio button (depending on radio button)

Hope this will help. please follow the comments.

 function CUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id){
        if($form_id=='YOUR FORM ID'){
           /* uncomment the following code after updating the key variables<field machine name> and check out the option keys.
           */
           // echo '
';
           // print_r($form['<field machine name>']['und']['#options']);
           //exit;
            $form['<field machine name>']['und']['#options']['<key>'] .= '
Hello World
';
            // the above code will add
Hello World
 alone with the existing radio button label
//Remove the comments if it helps.
        }

    }

Let me know if you need any additional clarity.

Thanks


Ordering/ Sorting product displays on the product category page

How about re-making your view so it shows Commerce Products, and add
  the relationship to the product display the other way round to get
  node data? That way you should definitely have SKU available as a sort
  option from the base table (commerce_product)
  - Clive

Thanks Clive - this worked.


Accessing text field with multiple values in a twig file

Both loops iterate field items, so when you name the loop variables accordingly the code should be more understandable:
{% for ref_item in node.field_references %}
  {% for text_item in ref_item.entity.field_name_of_text_field %}
    {{ text_item.value }}
  {% endfor %}
{% endfor %}


Location of data directories under AEgir on Debian

/var/aegir/config and /var/aegir/backups

Or you could just move the entire /var/aegir/ tree


How to only allow a user to edit his/her own users?

The Organic groups module (as already suggested in another answer) is indeed a possible answer to your question. But you should also have a look at the (fairly new) alternative for it, which is the Group module (with it roots close to where Dries started Drupal ...). Some more details about it (from its project page):

Organic Groups allows content itself to be groups, which isn't always what people want. It relies on an entity reference field to keep track of the ties between a group (node, term, ...) and its content (node, term, user, ...).
Groups instead creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Seeing as a group itself is also an entity, creating subgroups is very easy.

Even though it only has a beta release for D7 so far, its Usage statistics seem to indicate it is like a "rising star". And I've heard it mentioned recently in various occasions as a valid alternative for the "heavy" Organic groups module.
The Group module also integrate nicely with the Rules module, as explained in comment #2 of issue 2603136, which states the following:

... you can already use Rules to:

Add a new Group
Create a new GroupMembership and save it (the equivalent of $group->addMember())
Add or remove a GroupRole from a GroupType
React on new GroupMembership or Group entities
…

What hasn't been done yet is custom Rules actions or conditions. Seeing as 90%+ of Group is pure Entity API CRUD-operations, there has been no custom Rules code yet given how much you can already accomplish out-of-the-box.
Useful Rules we may add could be:

E-mail all members of a Group, optionally filtered by GroupRole
Easier-to-understand labels for the above list: "Member joined group" sounds easier than "GroupMembership entity is created"

...

Refer to Integrations with other modules and its "Related issues" about other modules for which integrations already exist, or are in the pipeline.
PS: Refer to How to implement an option for users to limit access to nodes/comments to users with the same role while posting it? for an interesting illustration of how this module can be used.


Store the Logged in Users's Country in the DataBase

Turns out there's a pre-built solution for just that: ip2country

  This module uses a visitor's IP address to identify the geographical location (country) of the user. The module makes this determination and stores the result as an ISO 3166 2-character country code in the Drupal $user object, but otherwise has no effect on the operation of your site. The intent is simply to provide the information for use by other modules. A function is also provided for you to perform your own lookup, to use in your own manner. Features include automatic updates of the IP-country database and admin spoofing of an arbitrary IP or Country for testing purposes.


Seems like 'Comment Field is required' when clicking the Attach is similar (identical?) to the issue you encountered.

That issue has status Closed (fixed), and also contains a patch for it.


I can't add new icons in CKEditor default toolbar

If you have jquery_update installed and using 1.8 you might also run into javascript errors if you are trying to move toolbar elements around. Temporary setting it to 1.5 (doing my changes and setting it back to 1.8) fixed the issue for me.


Replace a word in a custom block or paragraph with a token related to a content type field value

First create your own module.
In mymodule_tokens.module insert below:
<?php

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */

function mymodule_tokens_token_info(): array
{
    $type = array(
        'name' => t('My Module Tokens'),
        'description' => t('Custom tokens to solve use-case problems for the website.'),
    );
    $node['brand'] = array(
        'name' => t("Brand name from node"),
        'description' => t("Brand name to replace in text, custom blocks, paragraphs, ..."),
    );
    return array(
        'types' => array(
            'mymodule_tokens' => $type,
        ),
        'tokens' => array(
            'mymodule_tokens' => $node,
        ),
    );
}

/**
 * Implements hook_tokens().
 */

function mymodule_tokens_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata): array
{
    $replacements = [];

    if ($type == 'mymodule_tokens') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'brand':
                    $node = \Drupal::routeMatch()->getParameter('node');
                    if ($node instanceof \Drupal\node\NodeInterface) {
                        if ($node->hasField('field_brand') && !$node->get('field_brand')->isEmpty()) {
                            $brand_name = $node->field_brand->value;
                            $replacements[$original] = $brand_name;
                        } else {
                            $replacements[$original] = null;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    return $replacements;
}


Use code to automatically fill the form of a content type

You need to do something similar to what you do to set the body of the note for each of your additional field (City, Country, Event Date, Duration, Email Address). The exact data structure for each filed depends on its type.

The general pattern is

$node->{$field_machine_name}[$language][0] = array(...);

The hard part if figuring the content of the array(...) which is the value of the field. The value of a field is actually always an associative array. Its keys (also called columns) depend on the type of the field. A text field, for instance, as only one value key/column. A taxonomy term reference field has also only one key/column, but named tid.

For instance your city and duration field are a simple text fields whose machine names are field_location and field_duration you can set their values with

$node->field_location['und'][0] =  array('value' => 'Oxford');
$node->field_duration['und'][0] =  array('value' => '2');

You country field is a Taxonomy Term Reference field, its value can be set with

$node->field_country['und'][0] = array('tid' => 1);

Where 1 is the ID of a term in the proper taxonomy vocabulary.

If you were using an single address field name field_location to store the location, the code should be something like

$node->field_location['und'][0] = array(
  'country' => 'GB',
  'locality' =>  'Oxford',
);

The structure to set a date field depends on the date format. If the field uses the ISO format, you can set it with something like

$node->field_date['und'][0] =  array(
  // The start date.
  'value' => '2014-04-02T10:00:00',
  // The end date.
  'value2' => '2014-04-02T11:00:00',
);

To discover the structure of a field, I suggest to use the Devel module. It provides a devel tab on node that let you explore the structure of the $node object for an existing node. You can also check the hook_field_schema() implementation of the module defining the field type.


How to have parent taxonomy terms include their children terms' nodes?

Install the module http://drupal.org/project/hierarchical_select and check its configuration and you will find an option to "Save term lineage" select it and all the level of terms will be saved with the node.


Where do I add a new cache context for an entity?

You should indeed use hook_entity_build_defaults_alter(). Its documentation even explicitly states this:

  Alter entity renderable values before cache checking in drupal_render().

  The values in the #cache key of the renderable array are used to determine if a cache entry exists for the entity's rendered output. Ideally only values that pertain to caching should be altered in this hook.

It probably didn't work for you because you forgot to clear the render cache after implementing that hook.

That hook is invoked in https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilder.php/class/EntityViewBuilder/8

Also see https://www.drupal.org/developing/api/8/cache/contexts for an overview of cache contexts (what they are, how to use them, which ones core ships with).


You can do with Taxonomy Term Reference Tree Widget module.

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.


For S3
https://www.drupal.org/project/s3fs

In general
https://www.drupal.org/project/cdn

If you have origin pull then you should only need the CDN module


Taxonomy term page $content is empty but shows up later

I was stuck on this myself and went hunting for the answer.

From my understanding, taxonomy_term_page generates data for a page. Therefore, the $build variable outputs its content to a page template and that's why you see it after the theme template.

The $content variable in the theme template, taxonomy-term.tpl.php, should contain the description or any fields you have created for the term.


How to implement validation of field values?

You could use the Flag module for this. Excerpt from its project page (bold markup added here):

  ... Flag is a flexible flagging system that is completely customizable by the administrator. Using this module, the site administrator can provide any number of flags for nodes, comments, users, and any other type of entity. Some possibilities include bookmarks, marking important, friends, or flag as offensive. With extensive views integration, you can create custom lists of popular content or keep tabs on important content.

  Flags may be per-user, meaning that each user can mark an item individually, or global, meaning that the item is either marked or it is not marked, and any user who changes that changes it for everyone.

  In this way, additional flags (similar to published and sticky) can be put on nodes, or other items, and dealt with by the system however the administration likes.

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module. Refer to Flag's Community documentation for (way) more details.

Specific to your 3 fields here, you'd need 2 flags for each field X (x=1, 2, 3) (so 3*2=6 flags in total) whereas you'd add these flags to the nodes where these fields are used:

1 flag to indicate Field X is Valid.
1 flag to indicate Field X is Not Valid.

And if you'd then use either of the options I described in my answer to "How to add a custom icon or symbol to a flag link?", you can even make its look and feel match with your requirements.

Optionally also using some CSS magic to align 2 of these flags next to the field X that they are related to (as suggested in a comment below this answer, merci!).

But wait, there is even more: by using all sorts of integrations with the Rules module, you could also implement things like:

"Send an eMail" to User B whenever User A does something that waits approval/review from User B.
"Send an eMail" to User A about the result (approve or reject) from User B.
Implement any kind of validations between those fields, such as "If field 1 has value P, then field 3 is not allowed to have a value of Z".

There are tons of other enhancements you could implement (potentially even causing User B to no longer be needed, since Rules becomes the validation engine ...).


I think it cannot be done unless using the module. You can try like this

1) Adding the hook_form_FORM_ID_alter in the module to add placeholders, required and some other form attributes.

2) In the template file you can call that form using drupal_get_form('form-id', args1, args2, etc..)

3) Finally, pass the form to the tpl file.

Example:

1) In .module

function yourModule_form_user_login_alter(&$form, $form_state) {
  $form['name']['#attributes'] = array(
    'placeholder' => array (
       t('Username')
     )
  );
  $form['name']['#required'] = TRUE;
  /* Add other attributes like this*/
}

2) In template.php

$variables['login_form'] = drupal_get_form('user_login');

3) In .tpl.php

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

I hope this will work !!


What else must I do to set up a new custom module?

Check for spelling mistakes, because you seem to have everything you need for it to be listed.


How to change the HTML of the commerce shipping service form on checkout pages?

As suggested by clive, You should try this:

function MYMODULE_form_commerce_checkout_form_alter($form, &$form_state, $form_id) {
  ...
}

or

function MYMODULE_form_alter($form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'commerce_checkout_form':
      ...
    break;
}


Difference between strongarm, field base, and field instance

A Drupal 7 database contains various structural configuration. Some of these are:

Entity bundles, e.g. node types or taxonomy vocabularies.
Field bases: These are definitions of fields that apply across bundles and entity types, wherever the same field is used.
Field instances: These describe how a field is used for a specific entity bundle.
Field display configuration per entity bundle and view mode. This gets even more with Display suite.
General global key/value settings, stored in the variable table, which can be accessed with variable_get() and variable_set(). These are exported to features with strongarm.

Unfortunately, this entire system is a bit "dirty": Some of the structural configuration for fields and entity bundles is stored in the variable system, and not together with the field or entity type.

Therefore, whenever you export an entity bundle (e.g. node type) with features, you will also see some strongarm stuff. This is annoying and messy, but it is not avoidable.

I would recommend to maintain

One feature containing all field bases.
One feature per node type, with all field instances and field display configuration for this node type. This will also contain a lot of strongarm stuff.
Another feature for general strongarm settings, that are not related to anything else.
And more.

As far as I remember, drush features-export myfeature node:mytype already adds all the field instances and strongarm stuff for this node type.

Ideally you also have a naming pattern such as mysite_ft_* for all features, and mysite_ft_ct_* for all content type features. Also organize your sites/all/modules into contrib/, custom/, features/.

So in conclusion: You don't have a choice to pick either field base or field instance or strongarm. Instead, you usually want to export everything that you want to sync between your local environment and the dev, staging or live environments. The only choice is which of those things should live in the same feature, and which parts should live in different features.


Given the code you are showing, which is similar to the code shown in Fields API, create new content type I take you are adding a new field to a content type, not simply creating a new table field for a database table. This explains why the code is using properties like field_name or label that implementations of hook_schema() would not use.

The values you can use for the type property are the ones described from the hook_field_info() implementations. In particular, if you look at the code of text_field_info(), you will see the following descriptions.

text: The field stores varchar text in the database
text_long: The field stores long text in the database

The confirm of what database field type is used for each entity field type comes from the implementations of hook_field_schema(), in particular from text_field_schema().

case 'text':
  $columns = array(
    'value' => array(
      'type' => 'varchar',
      'length' => $field['settings']['max_length'],
      'not null' => FALSE,
    ),
  );
  break;
case 'text_long':
  $columns = array(
    'value' => array(
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
    ),
  );
  break;

So, if you effectively need to use a TEXT database column  type, you need to use the following definition for the field.

array(
  'mymodule_summary' => array(
    'field_name' => 'mymodule_summary',
    'label' => $t('Summary'),
    'type' => 'text_long',
  );
);


Add elements to webform dynamically via hook_form_alter

Adding elements dynamically via hook form alter does not work because the Webform module can't recognize the new elements.  Your best bet is to create a custom webform element.


May be you can try this:

$result = $form_state->getValue('how_many');
$value = array_filter($result);

//print to check the value

print_r($value);


Is it possible to use Google to find Drupal with a specific version of Drupal?

Using Google Search it might be a little difficult for you. This search phrase can give you a few websites.

For better results you need some website profiler like BuiltWith to give you the list. The closest I came across was http://trends.builtwith.com/websitelist/Drupal-7 You have a list of Drupal 7 websites here but not 7.31 in particular. They might give you the details in pro-version but I have never tried.


Unable to save title after hook_form_alter()

Solved.

When I posted my code on here, I realized that I had a typo in Fieldset 2, where I was using '$form['device']['title'] = ...' instead of '$form['device']['field_equipment'] = ...'

After fixing the typo, everything is working as normal.


Logged out when hit home link in drupal 7.19?

Answer is well stated here http://drupal.org/node/110478

Had I spent a little more time reading I would not have had to ask this question.
Also I can see now it is making it so no matter which prefix you use the cookie will stick.


Could you change the field labels and make the field used for the price calculation the actual sale price field? The other one you could possibly call something like "original price" or so.

If this isn't feasible and you're on Drupal 8, it sounds like you want to implement a custom price resolver.


Limit the menu level on node add/edit page

Menu Performance Module does exactly that.

Drupal is already aware of this issue and has a variable menu_override_parent_selector which can be leveraged by other modules to come up with their own implementation of the menu handlers on node edit page.

As the project page reads

  Menuperformance takes advantage of this, and sets the variable when
  installed. It then proceeds to add its own AJAX based parent menu item
  selector widgets for the node edit, node type edit and vocabulary edit
  pages.

How to Use from README.txt

  Enable the module.
  Go to /admin/config/user-interface/menuperformance , and activate the  module. Checking the checkbox sets Drupal variable
  menu_override_parent_selector.
  After the module is activated, the menu item selectors on the above  mentioned pages should have been replaced with a multiple dropdown
  AJAX-powered selector instead of the standard single dropdown.


updatedhow to set default value in a form field got from another page(form)?

Drupal doesn't store the form state between forms, so you will need to do that yourself.

In this case I would use the session variable since you want to save it per user, but not permanently.

To do this you will need to add a custom submit handler to the form if you form is not created by you, this can be done with hook_form_alter

Then you can save the value you want to save in the session variable something like

 $_SESSION['my_value'] = $value;

should do the trick, then you can set the value in the form, either directly if you control it or via form alter.

That the form value is gotten from or is to be set to a field doesn't change things. The form field structure is a little more verbose, but the way to do it is pretty much the same.


Display top level of book, in book navigation block

This looks like a bug in the book module.

I have added a patch for it.

https://www.drupal.org/node/2827910#comment-11780887

You could add that patch, or create a new block that overrides the BookNavigationBlock,

in a custom module add /src/Plugin/Block/CustomBookNavigationBlock.php:

  namespace Drupal\mymodule\Plugin\Block;

  use Drupal\book\Plugin\Block\BookNavigationBlock;

    /**
     * Provides a 'Book navigation' block.
     *
     * @Block(
     *   id = "custom_book_navigation",
     *   admin_label = @Translation("Book navigation - Customized"),
     *   category = @Translation("Menus")
     * )
     */
    class CustomBookNavigationBlock extends BookNavigationBlock {

      /**
       * {@inheritdoc}
       */
      public function build() {
        $current_bid = 0;

        if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
          $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
        }
        if ($this->configuration['block_mode'] == 'all pages') {
          return parent::build();
        }
        elseif ($current_bid) {
          // Only display this block when the user is browsing a book and do
          // not show unpublished books.
          $nid = \Drupal::entityQuery('node')
            ->condition('nid', $node->book['bid'], '=')
            ->condition('status', NODE_PUBLISHED)
            ->execute();

          // Only show the block if the user has view access for the top-level node.
          if ($nid) {
            $tree = $this->bookManager->bookTreeAllData($node->book['bid'], $node->book);
            return $this->bookManager->bookTreeOutput($tree);
          }
        }
        return array();
      }

    }


Trusted Host Patterns Settings Not working with IP

So I figured out what was wrong. I didn't have my apache site config set correctly.
I had:

snip...
<VirtualHost *:8080>
           ServerAdmin webmaster@localhost
           ServerName drupal845.localhost
           ServerAlias www.drupal845.localhost
           end snip...

What I needed:

snip...
<VirtualHost *:8080>
           ServerAdmin webmaster@localhost
           ServerName drupal845.localhost
           ServerAlias www.drupal845.localhost *.drupal845.localhost
           end snip...


How to pass values directly from THEME_NAME.info to THEME_form_system_theme_settings_submit()

You do not need to use a form to save these values.
variable_get() and variable_set() functions will make it much easier to set the value and retrieve it.

However, if you still want to pass the information via the theme's .info file, you can do as follows:

Add your custom variables to the .info file

EX:
my_awesome_theme.info file:

name = my_awesome_theme
core = 7.x
dragons_exists = 1
how_to_catch_a_dragon[] = "Be a dragonlord"
how_to_catch_a_dragon[] = "Tell him to surrender"

Drupal will ignore these extra stuff during normal module/theme scanning.

To get the value, you can it like this:

$data = drupal_parse_info_file('sites/all/themes/my_awesome_theme.info');

You can use functions like drupal_get_path() to get the correct path.
$data will contain the values from the .info file.
For example,  the above .info file will yield

Note that drupal_parse_info_file() doc mentions that you should NOT use this method to store arbitrary data.

  Parses Drupal module and theme .info files.

  Info files are NOT for placing arbitrary theme and module-specific
  settings. Use variable_get() and variable_set() for that.

Update:
If you only need to pass some variable from the form, and not necessarily from the .info file, just store the value in $form_state.
As long as you don't overwrite some existing values, $form_state['values'] for example, it will work just fine.

Also, consider using a form element of #type => value. User will not see anything at all, not even a hidden form element. You can access this value from $form_state['values'] nevertheless.


How do I get the last available hook_update_N() for a module?

They're in key/value storage, which in the database would be the key_value table. Look for entries with a collection of system.schema, and a name matching the machine name of the module you're interested in.

Through the API, it's a bit easier:

$current_version = drupal_get_installed_schema_version('name_of_module');


when your users post new "page" content they can select the associated group. You could make that a required field.


After updating from drupal 6 to 7: No content types under node/add

I finally managed to fix this by accident while trying to fix a different issue.

Following this post: https://drupal.stackexchange.com/a/82222/25238
Similar to https://www.drupal.org/node/997444

I first tried drush eval 'menu_rebuild();' drush cc menu which didn't have an effect, then I found the hint in a comment by nilsun to the above post, that sometimes a complete reset might be necessary. This seems to be caused by a corrupt menu system.

$drush sqlc
Password for user user:
psql (8.4.20)
Type "help" for help.
## if you want to try to keep your own menus you could
## first try:

DELETE FROM menu_links WHERE module = 'system';
# edit: typo, it's module, not menu
## Tested, did keep my custom menus

## D_ELETE FROM menu_links # Don't this will delete your custom menus too!
DELETE 748
d7=# DELETE FROM menu_router;
DELETE 909
d7=# \q
$ drush updb
No database updates required                                                          [success]
'all' cache was cleared.                                                              [success]
Finished performing updates.                                                          [ok]
$ drush cc menu
'menu' cache was cleared.                                                             [success]
$ drush eval 'menu_rebuild();'
$ drush cc menu
'menu' cache was cleared.                                                             [success]

Maybe one or two steps can be omitted, but that brought back the content types under "Add content", Edit Warning: while some of my self defined menu entries disappeared, but this should be easy to fix editing them manually.


session_unset logs out user when viewing the page

I was able to combine two of the responses to solve my problem.  I indeed updated it to use the symfony that is now part of drupal 8.  (Comment #3).  Reading https://www.drupal.org/docs/7/security/safely-impersonating-another-user gave me an idea to test for anonymity.  So I ended up changing the original code to:

if(\Drupal::currentUser()->isAnonymous()) {
    $request = \Drupal::request();
    $session = $request->getSession();
    $session->clear();
    if($session->getId() == '') {
        ini_set('session.gc_maxlifetime','28800');
        $session->start();
    }
}

This seemed to make my problem go away.  Not sure if this is the best solution, or a band-aid, but it worked for me.


You don't need to disable it, because it will automatically skip itself if the payment method does not require an off-site redirect.


When hook_field_load and hook_field_formatter_view are called?

hook_field_load() and hook_field_formatter_view() aren't hooks really. They rather are callbacks which only can be used from a module implementing the field in question by itself. The documentation at api.drupal.org for both hooks is not very clear in that by stating nothing or just a vague:

  Define custom load behavior for this module's field types.

When grepping through the Drupal 7 code you never see this so called hooks invoked by module_invoke_all() which is a clear sign for that functions are not handled like hooks.

hook_field_attach_load() may be used instead of hook_field_load() which is a real hook.

See also the discussion at http://drupal.org/node/702586 for that matter.


Custom migrate source plugin, extends FieldableEntity class, has migrate status of [error] No migrations found. Why?

I resolved my problem when I identified a mistake in my @MigrateSource annotation on my plugin. I had included my own custom migration module in the source_module entry of the plugin annotation. Here is what I did wrong:
/**
 * The 'mymodule_migrate_entityform' source plugin.
 *
 * @MigrateSource(
 *   id = "mymodule_migrate_entityform",
 *   source_module = "mymodule_migrate"
 * )
 */

Well I looked at the api docs on source_module

Identifies the system providing the data the source plugin will read.

The source plugin itself determines how the value is used. For example, Migrate Drupal's source plugins expect source_module to be the name of a module that must be installed and enabled in the source database.

It didn't work because source_module was set to my D9 custom migration module, which is obviously not on the D7 source, so the migration just silently gets removed from the list of migrations.
So I simply deleted the annotation line. My working plugin annotation looks like this now, and the plugin extends FieldableEntity and works as I had hoped it would.
/**
 * The 'mymodule_migrate_entityform' source plugin.
 *
 * @MigrateSource(
 *   id = "mymodule_migrate_entityform"
 * )
 */

I hope my plugin here will prove useful to someone migrating from D7 entityform to D8/9 core contact module (with contact_storage contrib module). It works.


What would be removed from the directory by default sorting, you need to remove from Sort criteria. And leave the possibility of the sort only Filter criteria


Why does the files directory ignore system wide umask?

Yes, if Drupal has permission to write to your doc root then it will certainly create the files folder on your behalf during installation, and attempt to set sensible permissions on it (775 seems perfectly reasonable to me considering the web server itself is creating the folder). This all happens in the /includes/install.inc file.

If your server is secured correctly, though, this should not be able to happen. The web server user should not be able to write to the doc root, only to the public/private filesystems. So you would create the files folder manually, and whatever permissions you decide to grant become part of that process.

See Securing file permissions and ownership for a full set of instructions on properly securing a Drupal site.


How to remove format description in date_popup form field?

Normally, you would just set the #description property of the form element, and it would be rendered. With the date_popup element implemented by the Date module it seems it is not possible: The form element is made of two sub-elements for which the value of the #description property is not taken into consideration.

As there are two branches, I will report what I have noticed in the development snapshot for both the branches.

Branch 7.x-2

The "date_popup" element is defined with the following code.

function date_popup_element_info() {
  $timepicker = date_popup_get_preferred_timepicker();
  $type['date_popup'] = array(
    '#input' => TRUE,
    '#tree' => TRUE,
    '#date_timezone' => date_default_timezone(),
    '#date_flexible' => 0,
    '#date_format' => variable_get('date_format_short', 'm/d/Y - H:i'),
    '#timepicker' => variable_get('date_popup_timepicker', $timepicker),
    '#date_increment' => 1,
    '#date_year_range' => '-3:+3',
    '#date_label_position' => 'above',
    '#process' => array('date_popup_element_process'),
    '#value_callback' => 'date_popup_element_value_callback',
    '#theme_wrappers' => array('date_popup'),
  );
  if (module_exists('ctools')) {
    $type['date_popup']['#pre_render'] = array('ctools_dependent_pre_render');
  }
  return $type;
}

The element has a process function that execute the following code.

  $element['#tree'] = TRUE;
  $element['#theme_wrappers'] = array('date_popup');

  if (!empty($element['#ajax'])) {
    $element['#ajax'] += array(
      'trigger_as' => array('name' =>$element['#name']),
      'event' => 'change',
    );
  }

  $element['date'] = date_popup_process_date_part($element);
  $element['time'] = date_popup_process_time_part($element);

Looking at the code for date_popup_process_date_part(), I notice the following code.

  $sub_element['#value'] = $sub_element['#default_value'];
  // TODO, figure out exactly when we want this description. In many places it is not desired.
  $sub_element['#description'] = ' '. t('E.g., @date', array('@date' => date_format_date(date_now(), 'custom', date_popup_date_format($element))));

As the code that date_popup_element_process() executes before to return the element is the following one, there is still an alternative.

  $context = array(
   'form' => $form,
  );
  drupal_alter('date_popup_process', $element, $form_state, $context);

Implementing hook_date_popup_process_alter() you could remove the description.

function mymodule_date_popup_process_alter(&$element, &$form_state, $context) {
  unset($element['date']['#description']);
  unset($element['time']['#description']);
}

Similar code is present in the branch 6.x-2.

Branch 7.x-1

There are few differences with the branch I previously described. (See the code repository.)

The first is the code that in date_popup_process_date_part() sets the description, which is the following one.

  $sub_element['#value'] = $sub_element['#default_value'];
  // TODO, figure out exactly when we want this description. In many places it is not desired.
  $sub_element['#description'] = ' '. t('Format: @date', array('@date' => date_format_date(date_now(), 'custom', date_popup_date_format($element))));
  return $sub_element;

The second difference is that date_popup_element_process() (the process function for that element) is not invoking hook_date_popup_process_alter().

function date_popup_element_process($element, $form_state, $form) {
  date_popup_add();
  module_load_include('inc', 'date_api', 'date_api_elements');

  $element['#tree'] = TRUE;
  $element['#theme_wrappers'] = array('date_popup');

  $element['date'] = date_popup_process_date($element);
  $element['time'] = date_popup_process_time($element);

  if (isset($element['#element_validate'])) {
    array_push($element['#element_validate'], 'date_popup_validate');
  }
  else {
    $element['#element_validate'] = array('date_popup_validate');
  }
  return $element;
}

The only alternative in this case would be to implement hook_element_info_alter() to add a process function to the element.

function mymodule_element_info_alter(&$type) {
  if (isset($type['date_popup'])) {
    $type['date_popup']['#process'][] = 'mymodule_date_popup_process';
  }
}

function mymodule_date_popup_process($element, $form_state, $complete_form) {
  unset($element['date']['#description']);
  unset($element['time']['#description']);

  return $element;
}

The code for branch 6.x-1 is similar to the code of branch 6.x-2.

In both the cases, the comment reported in the Date module code suggests they will alter the code not to use the description that is now shown. For this reason, I would suggest to implement the necessary code in a custom module, and remove that code once the Date module is changed.


The global $user object is just the bare data received from the users table for the associated user. It doesn't have any field, or other module-added data, attached to it by default.

For example, if you have a field attached to your user accounts called 'field_nickname', and you want to inspect the value of that field for the current user in code, you would need to call user_load() for the data to be available.

// Might work, but it's not guaranteed - depends on the modules
// you have installed and what's happened in the page build so far
$account = $GLOBALS['user'];
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

// Will always work.
$account = user_load($GLOBALS['user']->uid);
if ($items = field_get_items('user', $account, 'field_nickname')) {
  // ...
}

There are situations when other modules will load the field and other module data onto the global $user object, so depending on what modules you have installed you call to user_load() might not strictly be necessary.

However, it's good practice to make sure you load the object yourself; if another module has already run it for the current user then that data is statically cached, so you don't get a performance hit.


The path for your additional pages should be node/%node/abstract and node/%node/cover with something like

$items['node/%node/abstract'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('abstract', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('abstract', 1),
  'type' => MENU_LOCAL_TASK,
);

$items['node/%node/cover'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  'page callback' => 'MODULE_node_view',
  'page arguments' => array('cover', 1),
  'access callback' => 'MODULE_node_view_access',
  'access arguments' => array('cover', 1),
  'type' => MENU_LOCAL_TASK,
);

If you don't want your additional pages to be available as tabs (like View, Edit and Translate), you can probably use 'type' => MENU_CALLBACK. By doing so, you ensure Drupal knows these pages are below the normal node view page.

MODULE_node_view($view_mode, $node) and MODULE_node_view_access($view_mode, $node) are your page and access callbacks. They receive the $node already loaded (thanks to the %node in the menu item path). If you don't have specific access rules (such as restricting access to only certain content type), you can replace the access callback and arguments by node_access and array('view', 1).

Given the question, your likely want to automatically create aliases for your nodes so you can use paths like dossier/node-alias/cover instead of things like use node/1234/cover. You can implement hook_path_insert() and hook_path_delete() to automatically create and delete abstract and cover aliases for any aliased node.

/**
 * Implements hook_path_insert().
 */
function MODULE_path_insert($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Create aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_save($new_path);
    }
  }
}

/**
 * Implements hook_path_delete().
 */
function MODULE_path_delete($path) {
  // If this is an alias to a node view page
  if (preg_match("/^node\/\d+(\/view)?$/", $path['source'], $matches)) {
    // Delete aliases for the supported suffixes.
    foreach (array('/abstract', '/cover') as $suffix) {
      $new_path = array_merge($path, array(
        'source' => $matches[0] . $suffix,
        'alias' => $path['alias'] . $suffix
      ));
      unset($new_path['pid']);
      path_delete($new_path);
    }
  }
}


Few ways to do this:

JavaScript. Not the best one, but fastest:

$('img').addClass('adaptive-image');

For styling field images, see the response by Manoj Bisht.
For styling images added through WYSIWYG you will have to write a custom text filter and add classes. Depending on the WYSIWYG editor you use, you might be able to create a plugin / set configuration so that all images inserted automatically get certain CSS class.
Ultimately, you can just adjust the CSS of .adaptive-image, or clone the styles and apply them for all img tags.
Example source:

.adaptive-image {
  /* Whatever. */
}

Change to, or add this:

img {
  /* Copy styles from .adaptive-image. */
}


since it's not in either of those two file you linked, try node.tpl.php

failing that, see if you have a block defined to show in the content area, or content-top, etc.


7 embed an external website page in a node

An iFrame is the only option that doesn't involve huge amounts of work.

I guess if you really wanted to you you could write an API for the rails app that Drupal could consume and recreate the content off this data.

Technically you could get Drupal to scrape the HTML (file_get_contents or curl) of the ruby app and then cache this locally and embed in the node. This doesn't seem like a good idea as is inefficient and you may have problems with the search action and cache flushing mechanisms.


How do I configure the Block Access module?

This module is an administrative level module. You can use it to configure who can create/administer/view/etc blocks. For instance, what I did to realize what the module does, logged in as admin:

Install and enable the module Block Access
Create a new role, lets say testadmin, and grant to it every permission
Create a new user, lets say testuser, with that role
Log in with user testuser and create a dummy block
Log in again as admin
Edit the permissions of the role testadmin and deselect the permissions "Administer block access settings" and "Create blocks", under the section "Block Access" (these permissions are added by the Block Access module)
Log in again as testuser and try to create another dummy block
End of the exercise, because now the user testuser can't create blocks...

In this exercise I only used two permissions, but the module Block Access implements a lot more!


Oh, I believe I should use "renderRoot()" method of renderer in case where I'm rendering HTML for response just to be send. Please correct me someone if I'm wrong.


You can use Global Redirect module.

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

Every time when mycapecodvacations.com/home is accessed, Global Redirect will redirect to mycapecodvacations.com.


Weird spacing in Views content after unspecified module update

The issue is that the data range between parentheses is now on three
  lines, rather than inline with the title, ie Fall Semester Hours, Fall
  Finals Hours, etc.

looks fine to me...


Drupal 7 site display unexpected symbols

Every time I have encountered this problem, it has been because I have

page level caching enabled on admin/config/development/performance
page compression enabled on admin/config/development/performance
output compression enabled in .htaccess or httpd.conf (eg, mod_deflate)

The cause is that pages are being compressed twice on the server side, but only decompressed once on the client side.  The solution is to disable page compression in Drupal.

You can add an override to your settings.php

$conf['page_compression'] = FALSE;

and alter the performance page

function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}


Need to hide a field for the node author

You are referencing $user without bringing it into scope.

e.g using your current approach you could do this:

function aapka_preprocess_node(&$variables){
  // Bring global user object into scope
  global $user;
  // Assign by reference
  $node =& $variables['node'];
  if ($node->type == 'education'){
    if ($node->uid == $user->uid && $user->uid != 1) {
      unset($variables['content']['field_college']);
    }
  }
}

Keep in mind that won't work if the node is cached and the cache doesn't vary between the author and other regular registered users.


Best approach for creating databases for sub-sites

The option to use table prefixes exists because some hosting providers limit the number of databases. Don't use this feature unless your hosting provider is one of those.


Redirect timer on successful WebForm submition

Add this code in webform-confirmation.tpl.php

$(document).ready(function() {
  var delay = 10 ;
  var url = "http://google.com";
  function countdown() {
  setTimeout(countdown, 1000) ;
  $('.webform-confirmation').html("Redirecting in "  + delay  + " seconds.");
  delay --;
  if (delay < 0 ) {
  window.location = url ;
  delay = 0 ;
  }
 }
countdown() ;
});


Saving file upload destination as private

The upload destination is not saved with the field instance, but with the field base. I was using an existing file field that was public. I needed to create a new field and define it as private and save that field base in my feature.


Enable drupal_add_tabledrag on dynamically added rows

In case anyone else stumbles across this, because of how Drupal handles forms, rows should be added in an AJAX callback, and the table should be replaced with the newly themed table. There are plenty of examples of adding new fields to a form using ajax.

If for some reason you are using the tabledrag feature outside of the form API (I don't know why you would), here is a quick method I wrote to add a row to a table, and make it draggable if the table is:

(function($){
    $.fn.addTableRow = function(row){
        // We can use this later to see if the row has been added to the table yet
        var added = false;

        // Get the ID of the table
        var tid = $(this).attr('id');

        // See if the table is set as a tableDrag table
        if(typeof Drupal.tableDrag[tid] != 'undefined'){

            // initialize order variable
            var order = false;

            // Set some variables for easier access
            var tableDrag = Drupal.tableDrag[tid];
            var settings = tableDrag.tableSettings;

            // Loop through the classes in the settings for the table
            for(var aClass in settings){

                // Loop through the settings for the class
                for(var i in settings[aClass]){

                    // check which action the class uses, we could add the other actions
                    // here if we are worried about heirarchy or matching
                    switch(settings[aClass][i].action){
                        case 'order':

                            // if this class is used for ordering, assign it to order
                            order = aClass;
                            break;
                    }
                }
            }

            if(order){

                // find the max weight currently avaiable in the table
                var max = $(this).find('td.'+order).sort(function (a, b) {
                    return +a.value - +b.value;
                }).last().val();

                // Make sure the row has the draggable class
                row.addClass('draggable');

                // Add the row to the table, we don't do this earlier so that if
                // there is a value set in the weight field it is not included in the max
                // This could be done earlier, and setting the value could be ommitted
                // if you wanted to add the row to a specific locaiton in the table
                added = $(this).append(row);

                // Set the value of the order field to max+1
                $('.'+order, row).val(max+1);

                // Add the row so that tableDrag knows about it and can run it's
                // own hooks accordingly
                tableDrag.rowObject = new tableDrag.row(row);
                tableDrag.makeDraggable(row);
            }
        }

        // If the row wasn't added, order handling isn't used, just add it to the table.
        if(!added) $(this).append(row);
    }
})(jQuery);

Pretty straight forward usage:

var newRow = $('
'+
                'Column 1	'+
                'Column 2<input class="sort-order" type="hidden" value="1"/>	'+
                '
');

$('#my_table').addTableRow(newRow);


What is the difference between using hook_views_pre_render() or preprocess functions?

Behind the scenes they're pretty different (one is a hook provided by Views, the other part of the theme system). Practically speaking, as a module/theme developer you'll see very little difference. What you can do in one you can do in the other, and hook_views_pre_render() can even be implemented in a theme.

I'd say just pick the one which offers you the most intuitive/simple way to make the changes you need to. If the theme preprocess requires more complex logic/code use the pre_render hook, and vice versa.


If you have set panel title like this

you can use the class "pane-title" to write the css.


You just need to go to the "Manage Display" admin page for your content type (e.g. http://mysite.com/admin/structure/types/manage/article/fields for the 'article' content type).

There you can hide/reorder all of the fields in your content type.

I would guess that currently you have a display field that's aggregating the "Image" field inside of it, and that you also have the "Image" field itself set to display. This would account for the same image being displayed twice.


You can just edit the Rule that controls that admin email and there is a From field for you to enter in the token or data selector for the customers billing email.


Is there module to generate form and save into content type?

Entity form creates entity instances called "Entity form submissions". So the answer to your question is "Entityform module."


Ok actually this was a stupid question...
I was trying to add the node tabs on my custom page without adding a tab to this custom page on the node view itself (entity.node.canonical)
Simply adding the new local task on the node view automatically displays other tabs when viewing any of the tabs
my_module.links.task.yml :
my_module.my_custom_tab:
  route_name: my_module.custom_page
  title: 'Custom'
  base_route: entity.node.canonical


After preview node is not saving the content.

This is an error that comes from the node module.

The error occurs when you submit the node form and the node has been changed by something since you loaded the form.

The change could be caused by another user editing the content, you editing it in a different tab/browser, some background task editing it, etc.

How it happens is:

You load the node edit form. The node object is pulled from the database at this time.
You make the changes.
You save the node.
The system checks the last changed date of the node object that was loaded when you loaded the edit form (in step 1) with the last changed date for that node directly in the database (the current last changed date).

It does this to stop two people changing a node at the same time, in which case one persons changes might accidentally override the other persons.

To get around the error, you have to refresh the node edit form and make your changes and save it again.

There is no way around it but there are ways to lessen the annoyance of getting to the end of an edit and being told you have to refresh.
One such way is the content locking module.

That module makes it so that when you load a node edit page it "locks" that node, so if someone else goes to the edit page while you have it locked it will give them a warning and won't let them make edits until you have finished editing and the node is unlocked.

This means you won't waste time on an edit that you won't be able to save.


Pre-populate field in content from user profile

Firstly, thanks to all for the help. I followed your advice and configured devel to print $page. Followed the structure of the page and came up with the amended the code:

$form['field_location']['und'][0]['country']['#value']

Leaving Devel enabled, I can see the value has been set correctly to gb. However, this breaks the google map functionality.

On to the next problem :)


Use the hook_block_view_MODULE_DELTA_alter in your custom module to display text if user has not configured the custom location.you can access the current user object from global $user if you want to perform any operation on it.

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function demo_wipe_block_view_weather_user_alter(&$data, $block) {
//Check here that whether user has configured or not.
  if(!is_array($data)) {
    $data['subject'] = t('Blah Blah Blah!');
    $data['content'] = t('Blah Blah Blah! link');
  }
}

P.S. : I have tested it on php 5.5.3

I think you should also specify this as a feature request in the module issue queue to set default whether location(that should be in admin configuration) on user whether block if user has not configured the block yet.


Can I have more than one child content type for a book content type?

Yes you can create two different Content types for your chapter nodes, just like you have different Content types for your book nodes.

The "Parent-Child" relationship you describe is usually accomplished with Entity references.

Add Entity reference fields to your chapter_type and audio_chapter-type and configure them to reference text_book_type and audio_book_type nodes respectively.

Then when creating a chapter node you'll be able to choose which book node it belongs to.

You can use Views to list all child nodes on a book page through that reference field, if you need such a list.


I have my drush alias files at
  ~/.drush/[hostname].aliases.drushrpc.php
  […]
  But my other [hostname].aliases.drushrpc.php files cannot be found in
  drush status

The filename should be  ~/.drush/[hostname].aliases.drushrc.php. not [hostname].aliases.drushrpc.php: Your filename contains an extra p. See example.aliases.drushrc.php.


AJAX call, hook_menu the requested url does not exist

You've confused access arguments with access callback. It should be:

$items['aug_store_front/get-products/ajax'] = array(
  'title' => t('Get products from specific product group'),
  'page callback' => 'aug_store_get_products',
  'access arguments' => array('access content'),
);


Custom Content types nodes with Nodeblocks module

Figured it out by getting my head around what Drupal calls "Template Suggestions".  The Theme Developer Module helped.

For my particular use case I had to create a template file called block--nodeblock.tpl.php to override the default block output. I basically stripped everything out of the default except the actual content so that this was all that was left: <?php print $content ?>.

Then I made a node--content_block.tpl.php template to override this particular content type's display the way I wanted it.  I had to add some trim() methods to strip out some leading spaces that Drupal insisted on inserting.

<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

    <?php if($content['field_headline']): ?>
        <?php print render($title_prefix); ?>
        <<?php print trim(render($content['field_headline_level'])) . ' ' . $title_attributes; ?>><?php print trim(render($content['field_headline'])); ?></<?php print trim(render($content['field_headline_level']));?>>
        <?php print render($title_suffix); ?>
    <?php endif ?>

    <div class="content"<?php print $content_attributes; ?>>
        <?php print trim(render($content['field_content'])); ?>

The last thing I had to do was create a template to strip out all the extra tags that the Drupal default field comes with.  I did so with this file, named field--content_block.tpl.php:

<?php foreach ($items as $delta => $item) : ?>
      <?php print render($item); ?>
<?php endforeach; ?>


Using Drupal.settings.basePath in Modernizer / yepnope.js loads

Your local environment seems to be misconfigured. If you're running apache with vhosts then your VirtualHost definition should look like this:

<VirtualHost *:80>
  ServerName whatever-you-choose-for-a-dev-domain.com
  DocumentRoot "/path/to/the/drupal/root/directory"
</VirtualHost>

Where the DocumentRoot should also include /sitename/docroot

Alternatively you may be able to edit .htaccess in the Drupal root directory to
    RewriteBase /sitename/docroot
Which there should already be a commented definition of RewriteBase in there that you simply would uncomment. But I think the VirtualHost path would be the best one.


Have administrators approve user accounts after users confirm their e-mail addresses and set passwords

Easiest way is kinda like what frazras said, leave the regular auth process but use rules to send an email to admin group/role when a user confirms registration.

You'll probably want to use views to create a view then that looks for the user role (the default confirmed user) and create a confirmed or approved user role (be sure to strip the user role of all permissions & grant permissions to your new role that are how you want them). In the view you are creating make sure to exclude anyone that's a member of any role other than just user & maybe anon.

The link to that view in an email to admins makes it easy to monitor You could probably put in a link to approve via the email though I'd strongly advise not letting users approve users without verification unless you're comfortable with your ability to secure it.

http://drupal.org/project/Rules
http://drupal.org/project/views


Install Drupal with MS SQL Server 2008 R2

The requirements clearly states that the supported databases in Drupal 6 are "MySQL 4.1 or higher, PostgreSQL 7.1."

You would have to write the database support yourself to get this working.

Drupal 7 does support MS SQL Server however.


return other indexed fields using SearchApiQuery($index)

If you are using Solr, on server configuration (admin/config/search/search_api/server/YOUR_SERVER_NAME/edit), under "Advanced" fieldset, you should enable the "Retrieve result data from Solr" option:


Generate fields in content from other content values?

Yes, this is possible.  On approach is to use the Entity Reference module.  This allows one field to reference another content type.  With this approach, on your Event content type, you could have a field Winner that is an entity reference to the player(s) who won.

In Views, you could then easily a list of events a player has won by using a contextual filter to limit the wins displayed to those of the player URL.  You could create a second view and attach it to the first to show how many.

These all require a fair bit of configuration and may be hard to set up at first, but it's definitely possible.


How to change taxonomy term ID to term name?

You first have to create a relation with the taxonomy terms by adding the relationship with the taxonomy list or Taxonomy terms on node. Once you have added the relation, you can now add a contextual filter called name with the category Taxonomy term. This way you can pass the taxonomy term by name to the filter.


Multi site installation with cPanel showing Warning: symlink() [function.symlink]: File exists in

(1) You need to ensure if test1 does not exists there as directory to sub-domain. You will have to remove it and symbolic link will replace it and will point to main site directory.

Or alternatively....

(2) You can edit your sub-domain settings (from sub-domain manager in C Panel) and replace the file system path to /home/ioss/ashokks/ so that subdomain can point directly on main site without involving symbolic link as Options FollowSymLinks can be disabled in some server configurations.


How do I filter entity reference fields based on language?

The logic that defines if entities should be shown is in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView()

As you can see, translation is checked there, but the API doesn't directly support skipping something, the hooks behind that only allow to control applicable fallback languages and their order.

It's possible that you can use entity access, which is checked after that. Implement hook_paragraph_access(), for the view operation, check if the paragraph has a translation in the current content language and if not, forbid access. The same should work for your other entity reference, it's the same could, just implement hook_ENTITY_TYPE_access() for that too.

If that doesn't work, you can write your own field formatter plugin and override that method.


$form: An associative array containing the structure of the form,
  which is passed by reference. Form validation handlers are able to
  alter the form structure (like #process and #after_build callbacks
  during form building) in case of a validation error. If a validation
  handler alters the form structure, it is responsible for validating
  the values of changed form elements in $form_state['values'] to
  prevent form submit handlers from receiving unvalidated values.

So your form validation function should be as the following:

/**
 * validation functoin
 */
function myModule_search_validate( &$form, &$form_state ) {
  // function body
}

Then in your form submit function you need to set $form_state['rebuild'] = TRUE as following:

/**
 * submit functoin
 */
function plant_Ontlogy_search_form_alter_submit( &$form, &$form_state ) {
  // function body

  $form_state['rebuild'] = TRUE;
}

If setting state rebuild to TRUE didn't work with you by itself, try to set default value as the following example to each additional field:

$form['myM_options']['entity'] = array(
  '#type' => 'radios',
  '#title' => 'Search by',
  '#default_value' => isset($form_state['values']['entity'])? $form_state['values']['entity'] : 'gene',
  '#default_value' => 'gene',
  '#options' => array(
    "gene" => "Genes",
    "ortholog" => "Orthologs",
    "microarray" => "Microarray Features"
  ),
);


Display content with Taxonomy on User and Content matching

Create a view showing users, and use a contextual filter on User:UID, and set 'Provide default value' the the 'Currently logged in user'.

You then should create two Relationships. The first on User:blog_subject will relate the user to the taxonomy terms. The second, using the first, will be on Taxonomy Term: Content using Blog Subject which will then relate the term to the content. Both relationships should be 'Required'.

Once the relationships  are in place, delete the 'User Name' field that is a default for the type of view you created, and add the Content:Title field displayed as a link to content. Add filters like Content:Published to eliminate un-published content and a sort by, for example, Content:Post Date (desc). All of these fields will be using the relationships. Make sure you delete all the User:... filters and sorts.

With multiple terms possible, this may create duplicate rows. There are two approaches you can use. The simplest is to go to Advanced > Other and configure the Query Settings to 'Distinct'. This might work. The other is to list the term and Set the view to Group By the term. That way you will get a list of pages that conform to each subject. If a page appears multiple times, it will do so under separate subject lists.

This should show a list of content matching the interests of the current user.


Up to Drupal 7 all modules and themes list is stored in system table with there enabled (i.e. 1) / disabled (i.e. 0) status. To Disable your module, set the status to 0 for the module name that you want to disable. Check simple MySQL query below:

UPDATE system SET status='0' WHERE name='module_name';

After running the above query, try emptying the cache tables. You can identify cache tables by table name starting with cache_. To make sure Drupal doesn't try loading from cache.

You can find more details about same on Drupal.org in Disabling or enabling modules manually in the database Or check How to manually uninstall a module? question.


How to pass variables to a theme template file from EntityAPIController::buildContent()

You can provide theme variables through properties, e.g.:

$buildContent['module_plugin_instance_' . $instance_id] = [
  '#theme' => 'module_plugin_instance',
  '#instance_id' => 'foo',
];


Doing a quick test, works fine with HTTPS

Views REST XML

Views REST Json

All of the above is using FULL URL

Perhaps someone set it to Absolute file path, which will give you /path/image.jpg (with out the $base_url). Then in some template file they did http://example.com{{ field.image.content }}

update

using template_preprocess_image_formatter() is another solution to change the template formatter of the image.


$user->uid is always 1 when running automated tests

It happens exactly what described in the documentation page for DrupalWebTestCase::drupalLogin().

  Please note that neither the global $user nor the passed-in user object is populated with data of the logged in user. If you need full access to the user object after logging in, it must be updated manually. If you also need access to the plain-text password of the user (set by drupalCreateUser()), e.g. to log in the same user again, then it must be re-assigned manually. For example:

  // Create a user.
  $account = $this->drupalCreateUser(array());
  $this->drupalLogin($account);
  // Load real user object.
  $pass_raw = $account->pass_raw;
  $account = user_load($account->uid);
  $account->pass_raw = $pass_raw;


Assigning custom class to nested menu UL elements

This kind of issues should be managed by CSS, but if you realy need to override the theme_menu_tree() and define a custom ul class there, you can do that with the help of custom global variable created in theme_menu_link().

Not sure if it's "the right way" to do that, but works:

/**
 * Implements theme_menu_tree__[MENU NAME].
 */
function YOURTHEME_menu_tree__[MENU NAME]($variables) {
  global $level;
  $class = ($level == 1) ? 'my-class' : 'my-class-for-depth-' . $level;
  return '
' . $variables['tree'] . '
';
}

/**
 * Implements theme_menu_link__[MENU NAME].
 */
function YOURTHEME_menu_link__[MENU NAME]($variables) {

  $element = $variables['element'];
  $sub_menu = '';

  // set the global variable in order to use it in hook_menu_tree()
  // I called it "level" to avoid confusing with the $depth
  global $level;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $level = 1; // set the level as first for each list with submenu
  }
  else {
    $level = $element['#original_link']['depth'];
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}


Can the themeing and render api be accessed independently?

Not in Drupal 7 or earlier. There might be chances for Drupal 8. But in the currently available major versions of Drupal the mentioned components are still strongly integrated in the core system.


How to alter price in checkout page and when submit order

You could use a HOOK for your needs, just read a little bit about hooks, and then create a hook for your content type and change that price.

You can check here how to first create a module and then a hook

Hooks in drupal tutorial


Does "exclude from display" on views affect performance?

You should profile this and see.  It totally depends on your system.

Install the Devel and Performance modules.  Then enable the Query log (in the D7 version it is at "admin/config/development/devel").  Visit some view pages, and look at the queries at the bottom of the page.  Tweak your views and re-run.  Just be sure to disable caching (including MySQL query caching) when you do this, as it may skew results.

You can also copy/paste the SQL from the view config page (enable from "admin/structure/views/settings"), into Query Browser or another tool and look at the execution time.  If you do this, bypass the query cache, to make sure you get accurate results.

Also keep in mind that buffer sizes, etc, can affect results since data may or may not need to be read from disk.  You should really have an optimized MySQL instance before you profile.


Configuration management sync vs active vs staging

This has changed, before Drupal beta 14 it was active/staging now it is sync. These are the settings in settings.php:

Drupal 8 beta 14:
$config_directories['active'] = 'sites/default/files/config_HASH/active';
$config_directories['staging'] = 'sites/default/files/config_HASH/staging';

Drupal 8 rc1:
$config_directories['sync'] = 'sites/default/files/config_HASH/sync';


Why are `drush pm-list` & `drush pm-updatestatus` disabling the default theme?

Your themes for Drupal 7 should live here:

/sites/all/themes/THEMENAME - for all sites and all themes
/sites/example.com/themes/THEMENAME - for example.com of a multisite setup

Now in your case there is an additional note: You have the option to put your theme in a contrib and a custom subfolder. Themes in the custom subfolder would be skipped during the update process (see /r/drupal for cross reference). There is a caveat though: Apparently once you use contribyou also have to use custom otherwise it seems the whole tree breaks (see disqus)

Try to move the foo theme too: /sites/all/themes/custom/foo or /sites/example.com/themes/custom/foo then run drush rr and drush cc all


Product reference field causes $title to be empty

Check the content types display tab. It may be set to hide the title.


Lose ability to use node load with an argument in ajax form submit

I ended up finding a solution to this. Essentially, instead of trying to load the arg(1) inside the mymodule_form_submit (because apparently you can't do that when the submit is triggered via ajax), I instead passed the node ID to the form submit through a hidden form field. See below:

function mymodule_form($form, &$form_state) {
    $form = array();

    $form['node'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

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

    return $form;
}

function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load($form['node']['#value']);

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

And now it works just fine.


HTML tags in views field label. Is it possible?

Uncheck create label

Click on rewrite results, check mark override out and put:

  Price: -10%
  {{ field_price }}

I'm not 100% that it's {{ field_price }}, but you can click on replacement patterns to see the pattern name.


If I don't see the "Full HTML" and "Filtered HTML" input formats, is it OK to add them manually?

By default, Drupal 7 includes plain text, filtered HTML, and full HTML text formats.

If you are not seeing these as choices, you are probably not logged in as an administrator and you do not have the appropriate permissions.

Non-administrators are not given access to full HTML by default because this can be a security risk.

Try logging in as an administrator and going to the permissions management page.  Verify the permissions for Use the Filtered HTML text format etc. under Filters.

Of course, if you need an input filter with a custom configuration, you can certainly create your own.  Just be careful to not give your users any input options they shouldn't have.


I would do this in this way:

function YOUR_MODULE_init(){
    drupal_add_js('path/you/want/to/use/to/include/javascript.js');
}

function YOUR_MODULE_menu() {
    $items = array();
    $items['path/you/want/to/use/to/include/javascript.js'] = array(
        'title' => 'Generated js',
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name'
    );
    return $items;
}

function your_function_name() {
    $js = ... your code that composes js here ... ;
    print $js;
    exit;
}


How can I replace an image using a Form API?

Your 'logo' variable will be a file id, referring to a row in the file_managed table, so you can use the file_load() function to load the file object, create an image with the details, and attach it to your form field.

This is a (very) basic example:

$logo = variable_get('logo');

$image = '';
if ($logo) {
  // Load the file object
  $file = file_load($logo);

  // Get a thumbnail of the image (just an example)
  $args = array('style_name' => 'thumbnail', 'path' => $file->uri, 'alt' => 'Alt text');
  $image = theme('image_style', $args);
}

// Prepend it to your field
$form['logo'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#description' => t('Only image files will be allowed.'),
  '#default_value' => $logo,
  '#upload_location' => 'public://misc/media',
  '#upload_validators'  => array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_size' => array(2*1024*1024),
  ),
  '#prefix' => $image
);


easiest way to implement alternating row colors?

The easiest way would be straight CSS using the :nth-child pseudo-selector:

tr:nth-child(even) td { background: #ccc; }
tr:nth-child(odd) td { background: #aaa; }

The usual caveats apply (i.e. it doesn't work in Internet Explorer <9)


How to reorder items of multi valued entity reference field alphabetically?

Try adding a customjs.js file to your Drupal site and reference it from basic.libraries.yml (in Drupal 7 its the theme.info file).

You could add there could acting upon your  items and sorts them alphabetically; There are many such JS codes (classic or Jquery).

See this JQ code pen for example.


Using feeds_ex to import content to drupal using 2 steps API calls

The trick is to create a new parser, not a new fetcher.
I created a new module and a new parser at the following:
New files at MY_MODULE/src/Feeds/Parser/MymoduleJsonPathParser.php

I wanted to build on top of the feeds_ex module so I used their interfaces as the following:

use RuntimeException;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\feeds\FeedInterface;
use Drupal\feeds\Result\FetcherResultInterface;
use Drupal\feeds\Result\ParserResultInterface;
use Drupal\feeds\StateInterface;
use Peekmo\JsonPath\JsonStore;
use Drupal\feeds_ex\feeds\Parser\JsonParserBase;
use Drupal\feeds_ex\feeds\Parser\ParserBase;
use Drupal\Core\Form\FormStateInterface;

If you would like to add custom options that appear at the feeds UI add your custom form at the following:

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);

$form['FIELD'] = [ .....];
return $form;

}

Now you can build on your custom parser:

    protected function executeContext(FeedInterface $feed, FetcherResultInterface $fetcher_result, StateInterface $state) {
    $raw = $this->prepareRaw($fetcher_result);
    $parsed = $this->utility->decodeJsonArray($raw);
    // Your code gose here.
  }

I am writing a custom module and I will share it here when it's finished.


Create mini Panel, and add that. In mini panel you give classes, so you can wrap a class.


files missing in web/ folder when using composer.lock file

After some investigation, I found the culprit. The composer project uses drupal scaffold to place these files. However, this does not seem to be getting executed when the .lock file is already in place when you do the composer install

To resolve this, it was as simple as running the following command

$ composer drupal-scaffold


For Admin Theme

Create a custom drupal theme (its already answered).
Bring it to your drupal site.
Go to Home » Administration » Appearance, Select your theme in Administration theme select box and save


How can I set the template to use for a view page display?

if you want to add new page template only for views:

Implement hook_theme_suggestions_page_alter like the following:

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function mymodule_theme_suggestions_page_alter(&$suggestions, $variables) {
  //- Get the current route name.
  $route_name = \Drupal::routeMatch()->getRouteName();
  //- Check if the current route is a view.
  if (strpos($route_name, 'view') === 0) {
    //- Add suggestion to page when its a view page.
    $suggestions[] = 'page_views_view';
  }
}

Now in your views page you will have suggestions something like:

<!-- FILE NAME SUGGESTIONS:
   x page-views-view.html.twig
   * page--en.html.twig
   * page--list-page.html.twig
   * page.html.twig
-->

Now implement hook_theme like the following:

/**
 2. Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'page_views_view' => [
      'base hook' => 'page',
    ],
  ];
}

Then Create page-views-view.html.twig template inside templates folder in your module root folder.
Flush all cache.


How to exclude an external js from a particular node?

If the script is added in a correct way(using Drupal API) you should be able to unset it as following:

Drupal 7:

/**
 * Implements HOOK_js_alter().
 *
 * @param $js
 */
function HOOK_js_alter(&$js) {

  $node = menu_get_object();
  if (!empty($node->nid) && $node->nid == XXX) {
    unset($js['your_path']);
  }

}

Drupal 8:

/**
 * Implements HOOK_page_attachments_alte().
 *
 * @param $attachments
 */
function HOOK_page_attachments_alter(&$attachments) {
  /** @var \Drupal\node\NodeInterface $source */
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof \Drupal\node\NodeInterface && $node->id() == XXX) {
    unset($attachments['your_js_path']);
  }
}


Not sure about Lime, but Drupal 8 is set to use PHPUnit. See Deploy a PHPUnit system with a bottom-up approach.

  Deploy a PHPUnit system with a bottom-up approach

  Issue Summary

  Replace the SimpleTest framework with PHPUnit.

  Problem/Motivations

  The SimpleTest framework no longer has the same level of maintenance than the PHP Unit framework. PHPUnit has become the standard; most frameworks use it (ZF1 & 2, Cake, Symfony2, ...) and is actively maintained, sable and works great for every codebase, scenario.

  Replacing the testing framework with PHPUnit will allow better consistency in the drupal 8 codebase, by aligning ourselves with Symfony2 testing tools. Moreover, it integrates better with IDE (NetBeans, Eclipse, IntelliJ IDEA), Continuous Integration servers such as Jenkins/Hudson, and with Sonar for static code analysis as well. It has also code coverage which is a huge +.

EDIT

Following the comment from chx below about me posting the wrong issue, I'm pretty sure that this is the issue that noted the progress of PHPUnit: Start using PHPUnit for unit tests


How to register and create a node in the same form?

You're looking for the Inline Registration module.


Displaying uid on user/x/ and user/x/edit page

Implement hook_user_view() to show the uid on the user/x page.


How do I change what blocks show up on a user page depending on the user role of that page?

You need to expose that entity as a context to Drupal, then the visibility settings should automatically let you select between the current user and the user on the page.

Drupal core only does that for nodes at the moment, the logic for that is in \Drupal\node\ContextProvider\NodeRouteContext with its service definition:

node.node_route_context:
class: Drupal\node\ContextProvider\NodeRouteContext
arguments: ['@current_route_match']
tags:
  - { name: 'context_provider' }

So you need to duplicate that class and basically do a search and replace for node => user, remove the node.add part and put that in a custom module.


How to add comment form to a view of nodes in Drupal 9?

However, when hiding and rewriting the result/and or using the
replacement pattern for Content: Comments, the comment form disappears
and only the comment list remains.

It's due to a Views UI bug as I was able to replicate the issue on a fresh install.
A workaround you can do is to do the re-writing via template file rather than via UI.
In your theme's /templates folder add:
views-view-fields--view-name--machine-name.html.twig
and print the view fields there
{{ fields.title.content }} {# title field #}

{{ fields.comment.content }} {# comment field #}

{{ fields.field_name.content }} {# some other field #}

Flush all caches so template gets pickedup.


Error line appears when using drush 7.x.5.9 -- 32-bit executable?

Try running tput cols from your shell.  Drush is running this command to determine how many columns wide your terminal is.  You could convince Drush not to call TPUT if you instead export COLUMNS 80 (e.g. in bashrc), but it's probably better to figure out what's wrong with your tput executable.  This is possibly related to an installation problem that is independent of Drush.


You can translate Interface strings through Configuration > Regional and language > User interface translation (/admin/config/regional/translate).

Enter "Submitted by" into the "String contains" search field. It's important to enter correct capitalization of letters or your string won't be found (don't enter "submitted by").

Your search will find this string to translate:

Submitted by @author_name on @date

As you can see you can translate part of the message that doesn't contain tokens for data (you need to copy @author_name and @date into your translation so the text makes sense, don't translate "author_name" or "date", leave them in English as they are!).

Dates are special formats in Drupal, with special translation options.

You can translate Date formats by going to Configuration > Regional and language > Date and time formats (/admin/config/regional/date-time).

The one being used for "Submitted by" text is "Default medium date". Choose Translate in the drop-down next to Edit button.

Here you only configure how dates are usually structured in your language (maybe something like D, d/m/Y - H:i in your case for the Default medium format, to have the day before the month).

Month and Day name translations will probably already be available from Drupal Localization project, but if you see they aren't translated you can translate them yourself through the User interface translation page.

If you don't see some of the options mentioned here, make sure you have enabled all translation modules, including "Configuration translation".


Reducing number of DB queries when using views, search_api and relationships

Is there any way get Views to load all of the referenced entities in one go? No, there's not much you can easily change to fix that.

There's a lot of behaviour built in so that Drupal can handle multilingual data or different data storage back ends like MongoDB.

If you're not already doing so, you can use entitycache module to lighten the load. For cached entities, you will eliminate a lot of queries.

FYI, Entitycache will not work on its own. You will need to integrate with a cache back end like Redis or Memcache. See the module documentation and READMEs for configuration details.


What is easiest way to debug variables in nodes, views, blocks and page twig templates?

What is easiest way to debug variables in nodes,views,blocks and page
template

Welcome to Kint 101
Installing
Using Kint with Devel 8.x-2.1, which comes with the Devel module.
Using Kint with Devel 4.0.1. Kint no longer comes with Devel, you'll need to do  composer require kint-php/kint and apply patch.
Important: in order to use kint() in a twig file you need to enable debugging for twig. If you're not debugging inside a twig/template file, you can skip this part.
If you have Drupal Console installed drupal site:mode dev, remember to set it back to drupal site:mode prod when your developing is done.
If you don't have Drupal Console, do the following:

You enable Twig Debugging in sites/default/services.yml. (If
services.yml does not yet exist; copy default.services.yml and
copy it to services.yml.)
Set the debug variable to true. And clear cache.
parameters:
  twig.config:
    debug: true

Remember to turn debug back to false after you're done developing.
Source Debugging Twig templates
Now do the following to prevent issues with Devel 8.x-2.1, skip this part if using Devel 4.0.1
For starters, you are likely to run into this issue when you try a kint dump, specially if you just try{{ kint() }} without passing any parameters

This is due to the array or object being too big for your server resources to handle the default kint settings.
Edit /modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number to reduce recursion and the memory needed for dumping variables. The default is 7, I have mine set to 4. If 4 still doesn't work for you, keep lowering the number.
Ok, lets use kint
Note: If you're trying to dbug when logged out, you'll need to give Access kint information permission to the anonymous user role.
For Example, in comments.html.twig we do a {{ kint(content) }} and you will see

Tip #1 Do not click the + button, it's pure Evil
The + button will automatically open every single children and their children.
Instead, click on anywhere on the bar but the + button, for example, click here

Look how nice a tidy our Kint is

Also what is the easiest way to get protected variables values.

Getting a value
Lets say we're interested in the User. So click on user, but again do not click on the + button. You will see this

The id is protected, how do we get this value?
Tip #2 click on the available methods tab
This will reveal all methods that we can use here

So simply go with the one that makes most since, here being id() to get the user id.
{{ content.user.id() }}

why debugging became so complex in drupal 8?

It's not, as long as you know how to use Kint
Using all the above tips and tricks, I was able to answer this question Show comment author e-mail in comment.html.twig


The display formatter for an image on "Manage Display" allows you to select which image style to use.

The image style itself contains the relevant effect(s)


This is an example on how to catch this error:

try {
     $client = new Client();
     $response = $client->request('GET', $url);
     $content = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
     var_dump($e);exit();
}


How can I purge a specific URL from varnish cache without making a curl request?

Here's some code that I use to clear Acquia varish via the Purge / Acquia purge modules when a pdf with the same name is uploaded.  You could expand on this to clear the styles cache as well.

/**
 * Implements hook_entity_update().
 */
function my_module_entity_update(EntityInterface $entity) {
  $type = $entity->getEntityTypeId();
  if ($type != 'file') {
    return;
  }
  // \Drupal::logger('my_module')->debug("File entity found");
  $purgeInvalidationFactory = \Drupal::service('purge.invalidation.factory');
  $purgeQueuers = \Drupal::service('purge.queuers');
  $purgeQueue = \Drupal::service('purge.queue');

  $queuer = $purgeQueuers->get('coretags');
  // Invalidate cache tags so all pages that have the file get banned from varnish
  // Also invalidate the file's url.
  $invalidations = [
      $purgeInvalidationFactory->get('tag', 'file:' . $entity->id()),
      $purgeInvalidationFactory->get('url', file_create_url($entity->getFileUri())),
  ];

  $purgeQueue->add($queuer, $invalidations);
}


Print node URL in a custom block template

Ok, it seems I have solved the problem using twig/drupal path() function, building the linked title in this way:

{{ item.label }}

where "item" is the node object inside the list loop.


drupal 7 views horizontal align not working in grid?

You can horizontally align things with CSS

e.g

.container{
  text-align:center;
}

You can also align using a margin or padding.

In your case:

.view-galleryofimages .views-view-grid {
  margin:0 auto;
}

Should suffice.

See this summary for more info: CSS Horizontal Align


How can I change the redirect that happens after a node is edited?

You have a few options.

If you want to install a module and use a GUI you should be able to do that with Rules.  Just install the module, and setup a new rule to react on saving new content.

If you do not plan on using Rules for anything else, it is probably wiser to just use a hook_form_alter in your custom module.  Just edit the forms $form_state['redirect'] in a submit callback. Something like:

function test_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='MY_FORM') {
    array_push($form['#submit'], 'test_userlogin_submit');
  }
}

function test_userlogin_submit(&$form, &$form_state){
  $form_state['redirect'] = 'MY/NEW/PATH';
}


Is it possible to get the last number of a views pager to display after and before the elipses?

I'm not sure if this is the best approach, but it's been working for me.

First I set the pager items to display as inline-block. Then I styled the .prev/.next items to float left/right respectively so they're on the outside.

I used hook_preprocess_pager and $pager_total to set the last pager number $variables['tags'][4].

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
}

I added a conditional so the last pager item wouldn't appear twice on the last couple pages:

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
  if( is_numeric( $_GET['page'] ) &&  $pager_total[0] - 6 < $_GET['page'] ) $variables['tags'][4] = '';
}

I set the first page to "1" in the view settings, then use a similar conditional so it doesn't appear twice on the first couple pages.

function hook_preprocess_pager(&$variables, $hook) {
  global $pager_total;
  $variables['tags'][4] = $pager_total[0];
  if( is_numeric( $_GET['page'] ) &&  $pager_total[0] - 6 < $_GET['page'] ) $variables['tags'][4] = '';
  if( is_numeric( $_GET['page'] ) && $_GET['page'] < 5 ) $variables['tags'][0] = '';
}

This seems to work pretty well.


You have a couple of tasks,

Identify all the image styles
Identify where they're used. You can have multiple node displays, views, display suite, panels, etc.
Check if they're defined in code (features/custom modules)
Remove extra ones that aren't being used

They all apply to images. So your first step if find image fields and where they're used. Drupal has a report for that.

admin/reports/fields

For Views, you can use,

admin/reports/fields/views-fields

For each content type, check all displays see which ones are used,

admin/structure/types/manage/<CONTENT_TYPE>/display
admin/structure/types/manage/<CONTENT_TYPE>/display/teaser
admin/structure/types/manage/<CONTENT_TYPE>/display/<OTHER_DISPLAYS>

Then see if you have Panels or Display Suite. And check those modules to see if they reference other image styles.

After that, you can start looking into your code. This could be tricky. Assuming the contrib modules are in a separate folder,

sites/all/modules/contrib

It's easy,

grep -rn 'image_format_machine_name' sites/all/modules | grep -v 'contrib'

But if everything is thrown together into modules/, contributed, custom, feature modules, you'll have to exclude contributed modules manually. Probably Excel would be your best bet here.

I think basically that should cover the places where they're used.

Not sure if anyone would have any other ideas.


Getting parents' terms of terms tagged into a particular content type nodes

OK, so this solution has many steps, but the good news is that this is possible.

Here's what you need to do in your view:

In your view that lists your nodes, add a relationship to the topic term reference field (called field_topic) in my case.  In the 'Advanced' section, add the 'Content: Topic' field, and rename it if you want in the configuration screen.  As you can see, I did!

Next, add one more relationship (the parent term of this Topic term).  I'm filtering to only see term fields, and choose the 'Taxonomy term: Parent term' option.  Make sure, when you configure this second relationship, to choose that you want the Parent term of the already selected Topic term field.

If you want - at this point you can select the "Taxonomy term: Name" field twice in your fields list (once with the 'Topic term' as the relationship and once with the 'Parent term' as the relationship to see that your two relationship are bringing up the correct terms).
Finally, you're ready to set up a contextual filter!  What you want is for this view (which I assume is a block view) to pull up only those nodes that share the same topic parent with the current node's topic parent.  Sooooo, in your Contextual filters section (under 'Advanced'), choose the "Taxonomy term: Term ID" option.  Under the 'Relationship' choose, 'Parent topic' (or whatever you named your parent term relationship).  After all, we'll be filtering exactly by that - the term id of the parent of the topic term.
Choose to 'Provide a default' value for this filter when it's not available.  The truth is, we have to get the parent term id from the current node ourselves (I don't know how else to do it).  Choose that we'll provide it with 'PHP Code' and type in the following:

$node = menu_get_object();  // Get current node
$topic_term_id = $node->field_topic['und'][0]['tid']; // Just gets first topic term
$parents = taxonomy_get_parents($topic_term_id);
reset($parents); // Make sure pointer points to first element
return(key($parents)); // Return first key

Here's what my contextual filter looks like:

Obviously, I'm not really doing many checks in my code to test for the existence of terms, etc, but this should just about get you there.  Let us know if it works.  I just tested it and it works for me!!!