How do I render a submit button so that it's disabled initially and enabled by JavaScript?

Using #disabled on the submit button is the wrong solution because it communicates to the Drupal form API that the button is not expecting input. In other words, it causes Drupal to act as if the button were not there at all. Hence, clicking the submit button has no effect. This all makes sense from a security perspective, because normally you wouldn't want crafty users disabling backend logic just by using developer tools to force a disabled or read-only form element into being enabled.

Instead, the solution is two-fold:

Render the button as disabled via HTML attributes, so that the button is only disabled in the browser but is still considered an active button on the backend.
Mark the hidden field as '#required' => TRUE so that it's not possible to bypass the form even if the user is crafty with Dev Tools.

Here's what that looks like in practice:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = [];

    $form['selected_values'] = [
      // Though this field is hidden, it's required. So, the title is still
      // shown if/when the field is ever NULL during submission.
      '#title'    => $this->t('File selection'),
      '#type'     => 'hidden',
      '#required' => TRUE,
    ];

    $form['actions'] = [
      '#type'   => 'actions',
      '#weight' => 100,
    ];

    $form['actions']['submit'] = [
      '#type'         => 'submit',
      '#value'        => $this->t('Submit'),
      '#button_type'  => 'primary',
      '#attributes' => [
        // This button is programmatically enabled/disabled via JS on the
        // frontend.
        'disabled' => 'disabled',
    ];

    return $form;
  }

The frontend logic for enabling the button stays the same. The difference here is that the button is only disabled in the rendered HTML rather than being disabled in the backend form. In addition, if a crafty user enables the button by removing the disabled attribute on the HTML DOM element, they'll just end up with a validation error that says:

  File selection field is required.

Separately, as for why the second approach failed to enable/disable the "Submit" button based on the incoming values, this is because Drupal builds the form first before processing the incoming values so that it knows which form elements need to be invoked to process the input. So, at the time that the form builder is invoked, there is nothing yet in form state values. Hypothetically, it might be possible to get the raw input via $form_state->getUserInput() and then control whether or not the button should be enabled based on that; but, this approach may have security implications.


Complicated Views query relationships (for me)

Create your View looking at User records.
Add a Relationship under the Advanced section to link to your Taxonomy.
You then may have to use some Grouping, or Aggregation

Does that help?


You might want to investigate using the SMS Framework module along with Twilio SMS Integration instead - they have more users and there is more active and more recent development with these modules. They also have D8 ports, so you are covered for when you decide to upgrade to D8. But the answer below will work whether you use the above two modules or whether you just use the Twilio module.
When you say "Drupal Rule" I'm going to assume you mean a Rule made with the Rules module.
A Rules module Rule requires an Event, one or more optional Conditions, and one or more Actions. In this case, the Action would be to send an SMS message. The SMS Framework module does provide an Action for Rules, which is named "Send sms". You can use this action to send the SMS message. All you need now is an Event.
You want an Event that is fired when the anonymous user submits the password reset form. Drupal core does not have any hooks or events for password reset. This Event does not come with Rules. I know of no contributed modules that provide this Event. So you will have to write a few dozen lines of code. You can also do this without Rules, but you will also have to write code and it will be more code than with Rules.
Writing an Event is not hard, but it does require coding. A tutorial on how to do that is outside the scope of this issue. Below I will outline the basic steps and point you to some documentation. What you need to do is:

Implement hook_rules_event_info() to declare your event to Rules and define the variables that will be stored in the event. These variables will probably the telephone number and the user email address plus whatever other information you may need to complete the task.
Implement hook_form_alter() to alter the user_pass form so that it executes a custom submit handler.

Your custom submit handler should use the submitted email address to look up the user's telephone number.
Your custom submit handler will then call rules_invoke_event() to invoke your own custom event. You will pass this event the telephone number and the email address.

There are many examples of this that can be found. Some randomly selected pages which discuss this are:

https://www.drupal.org/docs/7/modules/rules/3-developer-documentation/events
https://drupalize.me/videos/declaring-events-rules?p=1152
https://drupalize.me/videos/invoking-rules-events?p=1152
https://www.powercms.in/article/how-create-custom-rules-event-programmatically-drupal-7
https://azimut7.com/blog/custom-rules-event-drupal7


Remove duplicate values in a column after join in drupal 7

Can you try with the result you are getting and avoid the duplicates using below codes.

 $used_tids = array();
 foreach ($result as $row) {
        if (!in_array($row->tid, $used_tids)) {
          $new_result[] = $row;
          $used_tids[] = $row->tid;
        }
      }
      // new filtered results after avoiding duplicates
      $results = $new_result;


Autopopulate a node with the content of a menu

Create a new View, Block, Content -> 'Basic Page', fields

once the main Views UI opens you can modify as desired - by default, this will create a view of Titles that act as links in a block you can place wherever you like. You can remove the Title (title) by clicking on the Title Field, and un-click 'Create a label'


How to add a view tab to node edit form?

I'm assuming you mean "Drupal tab" when you say you want to display Views as a tab on the Event edit form. "Drupal tabs" are the "View | Edit | Translate | Etc" links that are usually visually styled as tabs.
Although, a Drupal tab is an independent page, it will not be like a Block within the Edit form, it will be just a link on the "View | Edit" menu, you'll have "View | Edit | Registrations". This means you won't see registrations listed when you go to Edit (unless you add a Block to that page through regular procedure), you will see your Registration results when you visit the "Registrations" link/page.
Display a Views Page as one of Drupal tabs
You will need to have the "Page" Display in your Registrations Views. Page Displays have special Page settings that include the Path and Menu options. Additionally, you'll need to adjust the Contextual filter too, to only appear on Event type nodes.
You can combine these two settings to make that Views Page appear among the Drupal tabs of a set of links.
The Path needs to follow the logic of the set of links. In your case you have drupal tabs /node/[nid], /node/[nid]/edit etc. You'll want to set your Path to node/%node/registrations.
On the Menu you should choose the Menu tab option, fill in what you want the tab text to say (into "Menu link title"), choose a Parent, it can some menu you're not displaying anywhere if you don't need this page to appear as a menu item elsewhere. The Weight will affect the order on the Drupal tabs, enter a larger number (e.g. 50) to make sure it comes up at the end, and not before "View" or "Edit".
You already have the Contextual filter configured and working, so you might not need to do anything else. Check that the Contextual filter ID from the "Content" Category with these settings:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS in the URL or a default is provided
Specify validation criteria
Validator: Content
Content type Event
Set the option for the case when the argument doesn't validate to something that makes sense to you.
When you save this View and reload some Event node page you should be able to see the Registrations as a Drupal tab. Rebuild Drupal cache if it doesn't appear.


I just tried this on my D7 site I am making and if you go to admin/config/media/image-styles/list you can add a new style. Inside the new style you add an effect to crop and then you can choose the anchor point. The anchor point will allow it to crop from the top instead of equally top and bottom. You can then set your field to display using that style in the display settings or in views or whatever you showing it in.


The file needs to be located at [MODULE FOLDER]/src/Form/ReportServiceCallForm.php


Specifying CCK Field for Filter Processing

It is not possible.
An implementation of hook_filter() is invoked not only for nodes, but also for comments, CCK fields, etc. When it is invoked, the hook doesn't know in which case it is being called, and it only gets the content of the text that needs to be filtered; it cannot understand from that if the text is the body of a node, or it is the content of a comment, nor does it get a reference to the object containing the text that needs to be altered.

The function that calls the implementations of hook_filter() is check_markup(), which is then called by other functions, such as:

profile_view_field()
theme_comment_view()
user_comment()

As you can see, the input filters are called by user_comment() for rendering the signature of the user, and another module could use the input filters for rendering text for which an administrator user decides which input format users can use.


How do I display labels in checkbox grid table?

I was able to figure this out by creating a new custom element. My solution can be downloaded on my Github https://github.com/minnur/webform_checkboxes_table


Do path parameters need to be sanitized before using in the controller action method?

How to sanitize something depends on what you want to use it for.

It's entirely different if you want to protect against SQL injection in a database query or XSS when printing something.

PHP tried to do magic things on input but those features were removed a long time ago, see http://php.net/manual/en/security.magicquotes.whynot.php for example.

Protecting against SQL injecting is easy with the provided tools, Drupal 8 also autoescapes all output unless its told that something is safe. And simply don't use eval(), ever.


Try using Custom Breadcrumbs instead.

  Allows administrators to set up parametrized breadcrumb trails for any node type. This allows CCK-style node types to have "Home > User Blog > 2005 > January" style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases. Breadcrumb visibility can be customized via a php snippet.


Index Data from External Database for Search - Views

Like Michiel said Solr is a good option but is complicated to set up.

Another option is to implement a Google search server that can then be integrated with Drupal using the Google Search Appliance module. This is a paid solution but easier to setup.


Constructing array of term reference labels in php template?

Following @4k4's suggestion to post the final code as an answer myself... here's the code that I'm now using and that seems to work well...

First of all, I defined a simple helper function:

function getTermName($term) {
  return($term->getName());
}

This allowed me to extend my code (see my original question above):

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  ...
  $accesstags = array_map("getTermName", $entity->get('field_accesstags')->referencedEntities());
  if (in_array('subscription', $accesstags)) {
    ... allow access ...
  }
  ...
}

I'm still wondering, if there is a simpler way (without having to iterate over the array of terms), but for now the solution works well. Thanks again for your help, @4k4.


How to display multiple fields from a taxonomy term on a node (and control the html)

Sounds like this this could be achieved with Inline Entity Display.

  Overview
  Make available the fields and text properties from referenced entities into the parent entity template and the manage fields display overview.

This should allow you to move individual fields from your referenced taxonomy terms aroung independently on you node's manage display setting page.


How to let user decide how comments be sorted

It seems that the most obvious way to manage your user's behavior on comments would be to use Views.

And if you want to hide the main comment section, you can do so in your content type's parameters (check the comment section of you content type). You'll see stuff like hide and close.

Hope that gives you a start point.


Block wrapping DIV disable with theme hook?

You can specify an additional variable in hook_preprocess_block() and check for that variable in block.tpl.php file, example:

function front_preprocess_block(&$vars, $hook) {
  //dpm($vars);
  $vars['must_be_removed'] = FALSE;
  if(/* CONDITION e.g. $vars['elements']['#block']->delta == 'MY_BLOCK_DELTA' */) {
    $vars['must_be_removed'] = TRUE;
  }
}

and block.tpl.php file;

<?php if($must_be_removed): ?>
  <?php print $content ?>
<?php else: ?>
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

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

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

<?php endif; ?>


How can I save two logos for a custom theme?

Created theme-settings.php in custom theme root, there created new function, it renders new fieldset and a managed_file field

function theme_name_form_system_theme_settings_alter(array &$form, FormStateInterface $form_state) {
  $form['options_settings'] = [
    '#type' => 'fieldset',
    '#title' => t('Theme Specific Settings'),
  ];

  $form['options_settings']['add_logo'] = [
    '#type' => 'managed_file',
    '#title' => t('Additional logo'),
    '#upload_location' => 'public://logo/',
    '#default_value' => theme_get_setting('add_logo'),
    '#states' => [
      'visible' => [
        ':input[name="File_type"]' => ['value' => t('Upload Your File')],
      ],
    ],
  ];
}


FullCalendar links open a new tab, don't want that

In view edit, click on FullCalendar settings under Layout. There is an option to open events in new window.


Unauthorized : CSRF validation failed issue for Logged in user

Added X-CSRF-Token in beforeSend like below everything works fine now.

$(document).on("pageshow","#user_login",function(){
      try {

        $.ajax({
              url:"example.com/?q=services/session/token",
              type:"get",
              dataType:"text",
              error:function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
              },
              success: function (token) {

                        $.ajax({
                          url: "http://192.168.0.6/site_name/?q=drupalgap/system/connect.json",
                          type: 'post',
                          dataType: 'json',
                          beforeSend: function (request) {
                                request.setRequestHeader("X-CSRF-Token", token);
                            },
                          error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert('page_dashboard - failed to system connect');
                            console.log(JSON.stringify(XMLHttpRequest));
                            console.log(JSON.stringify(textStatus));
                            console.log(JSON.stringify(errorThrown));
                          },
                          success: function (data) {
                            var drupal_user = data.user;
                            //console.log(data);
                            if (drupal_user.uid == 0) { // user is not logged in, show the login button, hide the logout button
                            //alert(drupal_user.uid);
                             // $('#button_login').show();
                             // $('#edit-user-login-form-name').hide();
                            }
                            else { // user is logged in, hide the login button, show the logout button
                              //$('#edit-user-login-form-pass').hide();
                              alert(drupal_user.uid);
                             //$('#button_logout').show();
                            }
                          }
                        });

                    }
        });

      } //try end
      catch (error) { alert("page_dashboard - " + error); }
    });


drupal_get_messages() returns all the messages set using drupal_set_message, which also includes error messages set during form validation. This also clears the messages.

You can then add a custom validate handler to the webform by altering it by implementing hook_form_alter or hook_form_FORM_ID_alter.

In your custom validate handler, call drupal_get_messages() to clear any error messages.


How to convert currency dynamically on Product Page?

You can use  Commerce Multicurrency module for INR price field in the products content types.


Why is my file upload always NULL in $form_state?

Okay, this is tricky how Drupal handles the file uploads and took me some time to figure out.

$form_state indeed shows NULL or empty strings or empty arrays for my file upload unless I add a proper upload function. The file exists but is not uploaded yet.

It's worth taking a look at user_validate_picture():

function user_validate_picture(&$form, &$form_state) {
  // If required, validate the uploaded picture.
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );

  // Save the file as a temporary file.
  $file = file_save_upload('picture_upload', $validators);
  if ($file === FALSE) {
    form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
  }
  elseif ($file !== NULL) {
    $form_state['values']['picture_upload'] = $file;
  }
}

Calling this function from inside my own validation function will upload the file to temporary://What-is-Sustainability_0.png and it's now visible in $form_state['values']:

This is what I was looking for, now I can simply save the file where I need it and have the fid available to link it to entities.


Get a file URL from a custom entity referenced on a user profile

Solution:

$cv_wrapper = entity_metadata_wrapper('user', $user);
$cv_upload = array();
foreach ($cv_wrapper->field_cv->value() as $feature) {
    $cv_upload[] = $feature->field_candidate_cv;
}
$fid = $cv_upload[0]['und'][0]['fid'];

Printed the array of $cv_upload using:

drupal_set_message('<pre>'. print_r($cv_upload, TRUE) .'</pre>');


If you have custom module you can implement hook_views_pre_render(). It will allow you to change the views title before rendering.

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'your_view_name') {
    $title  = drupal_get_title();
    drupal_set_title(l($title,"node/add/event"));
  }
}

Not exactly but close to what you need.


How to validate fields with the Rules module?

It sounds like you don't have the supporting module Rules Forms: https://www.drupal.org/project/rules_forms

This module adds form validation for existing (core) forms and custom forms from contrib modules.

The documentation states that Rules Forms can:

Validate the values of form elements during form validation.
Set form errors when rule-based validation fails.


cloning a live drupal website (db) to a local / working mamp version

I use this command to dump my databases which are hosted on Ubuntu:

mysqldump -uusername -p --databases db_name | gzip -f > db_name.sql.gz


Import latitude and longitude from XML to Location field for GMap, for Views display

What I did was I just made two CCK fields for latitude and longitude. I used the function gmap_simple_map to create a map in my nodes, code placed in the node tempalte file.

Then, in Views, I made a block attachment that was a GMap and chose those CCK fields (which must be defined under fields) as my latitude and longitude.


Use entity_view:

$build = entity_view('commerce_order', $order, 'full');
$markup = drupal_render($build);


Is there a bulk method of doing 301 redirects from old nodes to new node pages?

Redirect Module + Path redirect import Module

The module Redirect has great options, one of which creates redirects when you rename a page and hence change an alias.

The module Path redirect import works with Redirect and allows you to upload a CSV of redirects (or use Drush), it even checks if a page you are redirecting to exists.


Add property to ProductVariationType via hook_entity_type_build()

Ends up that hook_entity_type_build() is not the right way to implement what I want. I found a solution usign ThirdPartySettingsInterface, which every ConfigEntityBase implements.

First I've altered ProductVariationType form via hook_form_alter() in order to add a checkbox to the form and register a new #enity_builder.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MY_MODULE_form_BASE_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var ProductVariationTypeInterface $entity */
  $entity = $form_state->getFormObject()->getEntity();

  $form['warehouse_management'] = [
    '#type' => 'checkbox',
    '#title' => t('Enable warehouse management'),
    '#default_value' => $entity->getThirdPartySetting('commerce_warehouse', 'warehouse_management'),
  ];

  $form['#entity_builders'][] = 'MY_MODULE_entity_ENTITY_ID_builder';
}

Then I've defined my custom entity builder function where I register my third party setting. Pretty simple! This article helps me out a lot.

/**
 * Entity builder for commerce_product_variation_type entity.
 */
function MY_MODULE_entity_ENTITY_ID_builder($entity_type, ProductVariationTypeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->setThirdPartySetting('commerce_warehouse', 'warehouse_management', $form_state->getValue('warehouse_management'));
}


How to act on paramters being passed to the homepage?

I think my approach would be to use $_SERVER['REQUEST_URI'] in a hook_preprocess_HOOK (see this) on template.php in a theme folder if all I needed to do is theming based on it.  For example:

function example_preprocess_page(&$variables) {
  $current_path = $_SERVER['REQUEST_URI'];
  // and so on
}

And then you could explode() it, modify stuff in the page array or the node array, etc.


How do I get the image path inside a jsonapi response?

For entity reference/images fields you have to include them to have their "full" data:
https://drupal-api.ddev.site/jsonapi/node/movies?include=image_field

The response will contain an object called included where you'll find that data,
Details for a image field:
{
  "type": "file--file",
  "id": "cc6ef625-8549-49c3-bc1c-0ef41551d8f7",
  "links": {
    "describedby": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/resource/schema"
    },
    "self": {
      "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7"
    }
  },
  "attributes": {
    "drupal_internal__fid": 29282,
    "langcode": "it",
    "filename": "1920x1080.jpg",
    "uri": {
      "value": "public://images/articles/2021-04/1920x1080.jpg",
      "url": "/sites/default/files/images/articles/2021-04/1920x1080.jpg"
    },
    "filemime": "image/jpeg",
    "filesize": 40767,
    "status": true,
    "created": "2021-04-13T10:22:44+00:00",
    "changed": "2021-04-13T10:22:52+00:00"
  },
  "relationships": {
    "uid": {
      "data": {
        "type": "user--user",
        "id": "c178495f-8a4c-410c-8e83-ebac79bc2162"
      },
      "links": {
        "related": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/uid"
        },
        "self": {
          "href": "drupal-api.ddev.site/jsonapi/file/file/cc6ef625-8549-49c3-bc1c-0ef41551d8f7/relationships/uid"
        }
      }
    }
  }
}

Please note you'll have to cross-check the id of that file with the id value of the image_field to get the correct file\url for each different image.


What's the best practice way to test block Views with SImpleTest?

The simpletest code needs to place the block into a region. Then, you should see the content after doing the drupalGet('/').


Eventually, I found out that some updates had been implemented in the theme and some modules and the problem was with the cache, not having been updated, so I run rebuild cache from Drush and the problem was fixed.


It looks like the directory it's expecting the source to come from doesn't exist. Here's the snippet of code which causes the exception to be thrown.

if (is_dir($source)) {
  $updater = self::getUpdaterFromDirectory($source);
}
else {
  throw new UpdaterException(t('Unable to determine the type of the source directory.'));
}

When updating this is the default directory: $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();

Make sure your defined temporary folder in the file system can be written to by Drupal.

If all else fails, manually update your modules via file transfer.


Some fields are not indexing in apache solr index

I had the search_index view mode was enabled and I have only enabled that one term reference field in search_index therefore only that field was indexing and not others.

So I enabled other fields search_index which I wanted to be indexed and it solve my problem.

So if you have enabled this search_index view mode for your content type then only those will be indexed which are enabled in this view mode.


Why is file_create_url() returning inconsistent values?

For each of the video files, this (for example):

$content["field_mp4"][0]['#item']['uri']

should be this:

$content["field_mp4"][0]['#file']->uri

Change #item to #file and change the syntax to reference an object instead of an array.


Since user is already defined as menu item from a module, you cannot use hook_menu() to alter it, but you need to use hook_menu_alter(). Since user is used for the currently logged-in user, it probably a bad idea to redirect them to login.

As said from Mołot in his comment, the correct way of altering the login process is altering the login form, and add new validation handlers. This is similarly to what the OpenID module in Drupal core does.

function openid_form_user_login_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function openid_form_user_login_block_alter(&$form, &$form_state) {
  _openid_user_login_form_alter($form, $form_state);
}

function _openid_user_login_form_alter(&$form, &$form_state) {
  $form ['#attached']['css'][] = drupal_get_path('module', 'openid') . '/openid.css';
  $form ['#attached']['js'][] = drupal_get_path('module', 'openid') . '/openid.js';
  $form ['#attached']['library'][] = array('system', 'jquery.cookie');
  if (!empty($form_state ['input']['openid_identifier'])) {
    $form ['name']['#required'] = FALSE;
    $form ['pass']['#required'] = FALSE;
    unset($form ['#submit']);
    $form ['#validate'] = array('openid_login_validate');
  }

  $items = array();
  $items [] = array(
    'data' => l(t('Log in using OpenID'), '#openid-login', array('external' => TRUE)),
    'class' => array('openid-link'),
  );
  $items [] = array(
    'data' => l(t('Cancel OpenID login'), '#', array('external' => TRUE)),
    'class' => array('user-link'),
  );

  $form ['openid_links'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#attributes' => array('class' => array('openid-links')),
    '#weight' => 1,
  );

  $form ['links']['#weight'] = 2;

  $form ['openid_identifier'] = array(
    '#type' => 'textfield',
    '#title' => t('Log in using OpenID'),
    '#size' => $form ['name']['#size'],
    '#maxlength' => 255,
    '#weight' => -1,
    '#description' => l(t('What is OpenID?'), 'http://openid.net/', array('external' => TRUE)),
  );
  $form ['openid.return_to'] = array('#type' => 'hidden', '#value' => url('openid/authenticate', array('absolute' => TRUE, 'query' => user_login_destination())));
}


How do I forcefully uninstall any module having content?

For example, I made any custom content entity type and add content
  into it. Now I can not uninstall my custom module until and unless I
  delete all content or truncate module specific db table – Sugandh Khanna.

Unfortunately, in Drupal 8 you can't disable a module, like you can in Drupal 7.

In Drupal 7 you need to disable the module first, which means all module related code stays in DB. Then, if you wanted, you Uninstall to remove everything from DB.

In Drupal 8 the only option is to uninstall the module, which means you have to destroy all traces of your module from the Database. You cannot just disable the module anymore.

Also, to uninstall Flag (as in your comment here), you have to uninstall dependencies first, then and only then, it will allow you to uninstall Flag. Because if module X depends on Flag and somehow you removed flag, it will totally screw up module X, X becomes useless, module X is nothing without Flag. Therefore you need to remove module X first, then and only then it will allow you to remove Flag.

For more info: Why can't I uninstall modules in Drupal 8? (Explained)

Issue: Disabled modules are broken beyond repair so the "disable" functionality needs to be removed


I'm working on a similar problem.  I have an ubercart based shopping system that a customer wants to have available on a public computer in his store.  We need to change themes, branding etc and auto-logout users.  His users will also be ordering from home, so we have to identify that particular computer and change the behavior and look of the site when we know they are ordering from the in-store kiosk.

Kiosk module that may help

This module allows an administrator to put selected computers into "Kiosk Mode".
"Kiosk mode" simply means that a given computer will have an extra flag set for template files, which allows a themer to exclude certain page elements, such as off-site navigation.

I'm installing this on my test server and we'll see how well it goes.  I'm hoping to figure out how to get that variable (if $kiosk) into ubercart checkout conditions and trigger some actions based on it.  It seems like themeing is pretty easy with this module but as for changing behavior, I'm not super sure how it will work.

Please let me know if you find any magic bullets as we're both trying to do a similar thing and i'd be great to share a solution.

UPDATE: I've been working with kiosk mode module (drupal 7 version) for a bit and have been able to create custom rules by calling the kiosk_is_kiosk function defined in the module. Simply use custom php condition in rules with this code:

 return kiosk_is_kiosk();

And you can have different workflows for kiosk terminals than for regular on-line users.  So for example, once an order is finished the kiosk will log out the user, but not a person using the same site from the home.

-Zachary


In such cases, Drupal first downloads the image to the temporary directory and then moves it to the public directory. Go to admin/config/media/file-system. Make sure that both temporary and public directories are defined and both are writeable by the web server. The easiest way to do this is to make the web server user the owner of the directory. The command is:

sudo chown -R www-data <directory>

where www-data is the web server user. Depending on your OS and web server, the user could be apache2 or httpd as well.


Which hook will load after node page load and file download

It's not really clear what you need re node hooks, since your title says "after node page load" and the body of your question says "after a node is loaded". Those are very much two different things. If you're looking for a hook that fires after the page has been displayed on the front end, there isn't one (though you could theoretically implement your own using AJAX).

Your best bet would be to consult the list of Node API Hooks and select the one that best suits your exact use case.

To get notified of file downloads through the private file system you can implement hook_file_download(). There's nothing similar for public file downloads, as Drupal's default behaviour is to pass straight through to existing files, without bootstrapping (hence no hook could ever be fired).


Avoid adding breadcrumb if title is empty

I think you can remove the breadcrumb if you create a template for the view:

views-view--your-view-name--page.tpl.php


Approach of building a website for local basketball league?

I see you tag this as Drupal 7.  You don't need OG unless you want to have groups where members of the group can chat with one another.

Content Types:  League, team, news/articles (maybe Players)
Modules:  Image field, Viewes.

News & Articles are self explanatory.
Create node reference fields for Teams & Players
Teams would node reference league,  players would node reference a team.
You may only have 1 league or multiple.
Add fields to players (name, height, position, photo)
May want to use image style to set defaults size for photos
Depending on your use, Players can be users or a content type
Then you will use views to display everything the way you want, such as, team gallery, teams in league, etc.

Also you may want to embed a view into a node.   Use embed_views module


Looking for best way to approach user profiles

Yes, Profile2 is probably the best approach there.

However, I don't think you'll be able to switch within a single registration form without custom coding.

To present alternative registration form pages for profile type, you can use the module:

profile2_regpath


Translated content not accessible / wrong links

In addition to enabling "URL" Detection method (path prefix or domain) and positioning it to be used first, you also have to Configure it.

Set German as your Default language under  Administration > Configuration > Regional and language
Go to the Language Detection and Selection page and enable the "URL" Detection method
On the Language Detection and Selection page click through the Configure button for the URL (/admin/config/regional/language/detection/url)
Select "Path prefix" as the " Part of the URL that determines language" option
Delete the de from the "German (de) path prefix (Default language)" option
Clear cache! This can be tricky through the interface if you're using the admin module because the /de/ might linger on the menus but will lead to a Page not found. Delete the /de/ in your browser Location bar from the flush cache link to make it work.

After this you should have the correct Home in German, without the /de, German content and links without the prefix and English content and links with /en/.


How to use "IS NULL" and "IS NOT NULL" Operators in JSON API Collections?

You don't need this line, because value is supposed to be null
&filter[filter1][condition][value]={{TID}}


Using custom .tpl.php for fieldable panel pane view mode

Two dashes for tpls. Your file should be named fieldable-panels-pane--banner--banner-full-bleed.tpl.php


What could cause the Features create page to time out?

The features UI can be notoriously slow for large Drupal sites. We recently experienced a ~50 second delay in loading the aforementioned page (create a new feature). The reason why (after debugging it all) was it was loading every single menu item on the site (>3000 of them) and trying to render a checkbox for every single one.

I posted a simple workaround on drupal.org https://drupal.org/node/1153028 - it looks like my patch will never get accepted in features, but at least it got the module maintainers looking at the performance issue.

On a related note, you do not need to use the GUI in order to create a feature. With large Drupal sites I would recommend using drush only as it has the advantage of being much faster. Please see https://drupal.org/node/960926 for more details.


In case you use panels, Organic Groups module comes with a content create panel pane that allows to select the content types to include in such a links list.


It is possible manually.
Suppose you have a book entitled "Tutorial". inside it you have created 3 book pages entitled : "Installing", "Configuring", "Running".
When the book is dispalyed the 3 pages will be ordered starting with the most recent

To reorder the book, edit the book first and choose outline in the tabs

In that screen, click on the link "reorder an entire book". The result wil be the following:

Click on the link "edit order and titles" to access the interface where you can reorder the pages

Use the + icons on the left of pages to reorder thje book.
I hope this will help.


One thing might help you(not sure)is that you can write your function in hook_cron and run that cron in background. So let's say your cron run after every 5 min, which means your page is refreshed and cache will get clear on every cron hit.


Panels "custom content" argument formatting

Just in case someone came here through a Google search, there is an answer to the specific question.

You can specify the default formatting of tokens by going in the Content Type in question, then in "Manage Display" tab, at the bottom of the page under "Custom Display Settings" you will have to enable the "Tokens" display.

The formatting that you choose for each field in this display will be used whenever you print the field through a token.

You could also use the Advanced Entity Tokens module, which allows you to specify a different view as an "extraction base" for your field formatters.

Edit:

Note that you can also create specific token formatters for profile2 entities by following the exact same method explained above. By default profile2 creates a single Display but there is still a Custom Display Settings option at the bottom of the page where you can enable the Tokens display and specify the formatters that you want to use for your Profile2 tokens wherever you use them (including Panels).


Accessing Drupal 6 data using Drupal 7 entities

As I understand it you're discounting the Remote Entity API module because you don't have a RESTful service...
The module actually relies on the Web Service Clients module, which provides that REST service for you:

Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being connecting to other Drupal installs via the Services module with either the REST or XMLRPC server.
Clients module allows you to create connections to remote services with an admin UI. These handle fetching a result from a remote service. Different types of connection are provided for different types of services. There is a Drupal client connection type for different versions of Services (5.x-0.92, 6.x-2.x, 7.x-3.x), hence Clients can be used to connect to sites with different versions of Drupal.

Emphasis mine.


Passing NID argument from views to panelizer

I had the exact same setup and issue. I could see the title of the view pane but no content even after I had made sure to set Argument input:Edit (in content pane view) to be:

Argument source: From context
Required context: Content ID

The reason I was not seeing content and only the title of view was simply because I'd forgotten I'd made a tpl of that view and had not yet cleared cache...


Have a look how orConditionGroup() is used in core.
For example, in ConfigEntityQueryTest it is used this way:

$query = $this->factory->get('config_query_test', 'AND');
$and_condition_1 = $query->orConditionGroup()
  ->condition('id', '2')
  ->condition('label', $this->entities[0]->label);
$and_condition_2 = $query->orConditionGroup()
  ->condition('id', 1)
  ->condition('label', $this->entities[3]->label);
$this->queryResults = $query
  ->condition($and_condition_1)
  ->condition($and_condition_2)
  ->execute();

I am sure you can apply this to your problem.


Allowing one page to be accessed by Anonymous user in restricted site

The content access module provides per node access.


How to load terms in alphabetical order or in the same order they are in CMS?

For getting all child terms in a vocabulary try the following code.

$cc=array();
$tax=taxonomy_vocabulary_machine_name_load($name);
$vid= $tax->vid;
$child_terms = taxonomy_get_tree($vid);
foreach($child_terms as $values) {
  $tname=$values->name;
  $cc[] = $tname;
}

The above code will give you child terms of that vocabulary in array $cc. For sorting in alphabetical order use asort($cc);

Hope this will help you.


Fatal error: Call to undefined function entity_view_mode_prepare() /sites/all/modules/field_collection/field_collection.entity.inc on line 600

This error has been removed in latest drupal 7 versions. Please upgrade your drupal core version to the latest.

OR
Temporary solution:
Copy and paste the below function in includes/common.inc file

function entity_view_mode_prepare($entity_type, $entities, $view_mode, $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $GLOBALS['language_content']->language;
}

// To ensure hooks are never run after field_attach_prepare_view() only
// process items without the entity_view_prepared flag.
$entities_by_view_mode = array();
foreach ($entities as $id => $entity) {
$entity_view_mode = $view_mode;
if (empty($entity->entity_view_prepared)) {

  // Allow modules to change the view mode.
  $context = array(
    'entity_type' => $entity_type,
    'entity' => $entity,
    'langcode' => $langcode,
  );
drupal_alter('entity_view_mode', $entity_view_mode, $context);
}

$entities_by_view_mode[$entity_view_mode][$id] = $entity;
}

return $entities_by_view_mode;
}


I had to set the fieldWidget to hidden.

 //langcode
        $fields['langcode'] = BaseFieldDefinition::create('language')
            ->setLabel(t('Language'))
            ->setTranslatable(true)
            ->setDescription(t('The redirect language code.'))
            ->setDisplayOptions('form', array(
                'type' => 'language_select',
                'weight' => 2,
            ));

Also I used Drupal's language configuration settings to enable the multilanguage feature for the entity.

The only missing bit is the language translation interface that you can use with nodes.


Hide price and add to cart form for purchased product

Here's a function that you can use to accomplish your goals. I tested it with Commerce Kickstart 2.

function MYMODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] != 'full' && $build['#entity_type'] != 'node' || empty($build['field_product'])) {
    return;
  }

  // Load your purchased products.
  $purchased_products = array('HAT2-BLK-OS');

  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

  $all_products = commerce_product_load_multiple($products);
  if (count($all_products) == 1) {
    $product = reset($all_products);
    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }
  }
}

Let's step through it. The first thing that happens is that you need to get your SKUs that you'll base your hiding off of. Just replace this line with a line that loads the products that the current user has purchased.

  $purchased_products = array('HAT2-BLK-OS');

Then, you load the products:

  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

If you just have a single product per page, you could grab a single product_id.

Then you need to load your products.

  $all_products = commerce_product_load_multiple($products);

I'm assuming a single SKU per product here, so it does reset($all_products) to grab the first one. Then, just do a check to see if that product's SKU is in the array of SKUs that were already purchased:

    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }

If it, then hide the sku (in product:sku) and the add to cart form (in field_product). The result will then be this:

As opposed to this:


I have run into this issue repeatedly and often the only way I have been able to add the missing field/relationship is to export the view, add the new field/relationship in a text editor, and then re-import the view.


What hook should I use to alter the File Upload field in Webform 7.x-4.16

I believe you could go far with hook_form_alter in drupal 7. Unless you're implying a multiple step webform where some webform hook may apply.

Browse over the webform.api.inc file in the module folder and if none of the hooks sound good for your needs try a simple form alter.


Since your module provides a settings.yml file, it must also provide a mymodule.schema.yml file describing the config object that stores the settings.

The real error pertains to something along these lines, and not a database error:

The test did not complete due to a fatal error.
Exception Uncaught e ConfigSchemaCheck   86 Drupal\Core\Config\Testing\ConfigSc
    Drupal\Core\Config\Schema\SchemaIncompleteException: No schema for
    MODULENAME.settings in
    Drupal\Core\Config\Testing\ConfigSchemaChecker-&gt;onConfigSave() (line 86
    of
    /var/www/docroot/core/lib/Drupal/Core/Config/Testing/ConfigSchemaChecker.php).

By providing a schema.yml file, clearing cache and re-running the tests this should resolve itself.

Related:

https://www.drupal.org/node/2848879
Simpletest fails with "invalid database prefix" - no other information given

You have to be careful of this one, because any contrib module that provides a settings.yml without a matching schema will throw the same error. It is confusing because you can install the module in your main application, but when you install it with a test, it will error out.

It will be easy to narrow down which ones, because it will be one that is listed in your required modules var (protected static $modules = [...]) which is how I stumbled upon the Menu Breadcrumb issue I mentioned.


Drupal 7 - How to show an upcoming event from site 1 on site 2?

You can use Shared Blocks, it has both drupal 6 and 7 stable releases:

If you have a main site with blocks that you want to syndicate across several
other websites, you need this module!

Features:

Allows publishing and subscribing of Drupal blocks
Changes to published blocks are updated on sites with subscription blocks
Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
Block subscriptions are updated on cron with an adjustable refresh interval


Adding node into search api solr programatically

Two things first. These two items are purely a suggestion and have no impact on the code samples bellow:

You should post the code that saves your nodes. The Solr API module should automatically pick up nodes when you save and update them (the search_api module code runs when you call "node_save"). It is odd that it doesn't for you.
You should think about running your solr re-indexing operation after you import all of your data. This will speed up your bulk imports and you can schedule the solr re-index via cron or run it via drush.

The following information comes straight from the search_api module.

These are the pre-conditions for the code examples bellow:

You need to run these after you call the node_save function.
The $type variable refers to the entity type (node, user, term, etc..). In your case it sounds like $type='node'
the $entity variable refers to the node object you're saving. You would pass this object to the node_save($entity) function during the bulk import operation.

If you're inserting nodes:

  $type='node';
  list($id) = entity_extract_ids($type, $entity);
  if (isset($id)) {
    search_api_track_item_insert($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_insert('multiple', array($combined_id));
  }

If you're updating nodes:

$type='node';
list($id) = entity_extract_ids($type, $entity);
if (isset($id)) {
    search_api_track_item_change($type, array($id));
    $combined_id = $type . '/' . $id;
    search_api_track_item_change('multiple', array($combined_id));
}


Drupal 7 Wildcard menu like txt-txt-% is not locating

Wildcard menu items for root level is not supported.
Partial match wildcards are not supported either.

You can, however, remap incoming requests to a proper menu router that Drupal supports by implementing hook_url_inbound_alter. Unless there is a strict requirement to use the path pattern you mention, I wouldn't go for this solution because this hook is executed to every request, including normal pages and Ajax requests.


Adding title attribute to #type password_confirm

The password confirm element is converted to two fields in a process function (form_process_password_confirm()), so adding your own process function to the password element would do the trick.

Per this issue it seems you actually need to overwrite the existing #process array instead of just appending to it, e.g for the user register form password element:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['pass']['#process'] = array(
    'form_process_password_confirm',
    'MYMODULE_password_confirm_process',
    'user_form_process_password_confirm'
  );
}

function MYMODULE_password_confirm_process($element) {
  $element['pass1']['#attributes']['title'] = 'Title';
  $element['pass2']['#attributes']['title'] = 'Title2';
  return $element;
}


How do I get parameters from form redirect?

Ok i got it by this way :

So i have 2 parameters from my form to pass to my controller :

public function submitForm(array &$form, FormStateInterface $form_state)
{

    $metier=$form_state->getValue('metier');
    $position=$form_state->getValue('position');

    $url = \Drupal\Core\Url::fromRoute('recherche.resultat')
          ->setRouteParameters(array('metier'=>$metier,'position'=>$position));

    $form_state->setRedirectUrl($url);

}

The key is in the YAML routing, you need to build your path like that for get parameters ( name of parameters need to be same as your route, see previous function (submitForm)) :

recherche.resultat:
  path: '/resultat/{metier}/{position}'
  defaults:
    _title: 'resultat'
    _controller: '\Drupal\recherche\Controller\ResultatRechercheController::resultat'
    metier: ''
    position: ''
  requirements:
     _permission: 'access content'

And in my controller for get my parameters :

Class: ResultatRechercheController

 public function resultat($metier, $position)
    {

        kint($metier);
        kint($position);

        return array('#markup'=>t('la premiere spécialite est @specialite',array('@specialite'=>'test')));

    }

And the URL is clean :

  localhost:8888//monsite.com/resultat/{metier}/{position}


View Contextual filter for content updated dates

The date format CCYYMMDD is indeed the same YYYYMMDD.

CC means century number as a 2 digit cardinal number where the first century was given the number 00. The present century is century number 20.

YY or YYYY means year (written as a 2 or 4 digit cardinal number with a leading zero if required), The present year is 14 (two digits) or 2014 (four digits).

MM means month as a two digit cardinal number with a leading zero if required.  The present month, January, is written as 01.

DD means day om the month as a two digit cardinal number with a two digit leading zero if required.  Today is day number 24 of January.

In other words, today's date (January 24th 2014) is written 20140124 in both these formats, and December 1st 2013 is written as 20131201 in both these formats.


Many years later, but for future reference, the problem might be related to the fact that you are using the PECL gmagick PHP extension. I believe the ImageMagick module is not meant to work with the gmagick PHP extension. There is a module meant to be used specifically with PECL's gmagick: https://www.drupal.org/project/gmagick . I hope that helps somebody.


You have different ways/options to add custom javascript/jQuery file with your module.

Option 1: Add myscript.js in module info file (mymodule.info).

scripts[] = js/myscript.js

Option 2: Add myscript.js using hook_init and drupal_add_js

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'MODULE_NAME') .'/js/myscript.js', 'file');
}

Option 3: Add myscript.js to any Drupal form or any callback that contains Drupal form

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = array(
    'data' => drupal_get_path('module', 'MODULE_NAME') . '/js/myscript.js',
    'type' => 'file',
  );
}


How to create view with user's flagged content?

Have you tried adding contextual filters -> USER -> get uid from url


Javascript is probably your villain.

Especially on IE6 and IE7 and still in IE8, Javascript is MUCH slower than the rest of the world.

Despite not being the most brilliant piece of js ever, drupal.js is harmless.  The real harm probably lies a lot of plugins or maybe one or two poorly-coded scripts that perform some kind of expensive DOM lookup or other task that is negligeable in Firefox et al but really slows down IE.


What can we do to remedy the unrecoverable error we encounter for any Drush command?

Make sure your Drush commands are issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

Since your question did not specify that, it "might" be the reason why ALL your DRUSH commands are failing ...

Refer to this issue for other possible causes (things you may want to check).

If you recently enabled contributed and/or custom modules, try to temporary disable them to check if the Drush issue gets resolved by doing so.


In Drupal 7 you can use this code.

For a view page

print views_embed_view('name_of_view','page_1', $node->nid);

For a view block

print views_embed_view('faculty_core','block_1', $node->nid);


Notice: Undefined variable: node in eval() and Notice: Trying to get property of non-object in eval()

Something is trying to run the php_eval() function in php.module. Most likely you have something configured in your site (such as a block) to use the PHP input filter, which evaluates PHP code and prints the output as text. I would check all the blocks you have defined first.

You can also temporarily put a call to debug_print_backtrace() at the top of the php_eval() function and print it's results while browsing your site as an anonymous user to see what exactly is calling that function.


It is better to check the arguments from arg() function, this way:

<?php
// PHP VISIBILITY CODE:
// If URL is node page

if (arg(0) == 'node' && is_numeric(arg(1))){
  $nid = arg(1);

  // Load node:
  $node=node_load($nid);

  // Display block only if node is of certain content type
  if ($node->type=='user_art') {
    return TRUE;
  }
}

return FALSE;
?>

Maybe the problem is with the views argument to get $node->uid. Try this:

More info: https://groups.drupal.org/node/129979#comment-751473

1 - Create a new Block View to view Users (not Content)

2 - Filter Criteria should say User: Active (Yes)

3 - There is a default sort Criteria item. Remove it since it doesn't matter.

4 - Add a Relationship: Choose "User: Content authored"

5 - Add a Contextual Filter: Chose "Content: Nid"

6 - In the configuration options for the newly added Content: Nid, choose these options:
WHEN THE FILTER VALUE IS NOT AVAILABLE:
Provide default value
In the Select box, choose Content ID From URL.

WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED
Specify validation criteria
Validator select box: Content
Content Types: choose the content types you want the view to work with.
Filter Value Format: Node ID
Action to take if the filter value does not validate: Hide View

7 - Save the View.

8 - Go to Structure -> Blocks and configure the block to show on the types of content you want it to show on and position it wherever you want it to appear.

9 - Done.


Remove labels in printer friendly version of books

Here is how I approached the problem:
Copied

/modules/book/book-node-export-html.tpl.php
/modules/book/book-export-html.tpl.php

to my theme directory and modified the $contents variable via str_replace.

This works fine as a temporary fix, but I guess performance-wise this is not the best solution, would would be still nice to find a way to apply CSS.


Error while set a paragraph field to NULL during cron run

Even if the cron job is working now after you changed the order, you might get the same error later when using the saved parent entity.

Don't delete referenced paragraph entities programmatically (now the last command after you've changed the order). The Entity Reference Revisions module is handling this automatically after all revisions referencing the paragraph are removed.


Is the Role listed on admin/user/roles?  If not, your Feature might not be defining a Role, or the Feature might be overridden.

Roles defined by Features do actually show up in user_roles().  I created a simple Feature defining a single role, then enabled it:

% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
)

% drush pm-enable yayfeature
The following extensions will be enabled: yayfeature
Do you really want to continue? (y/n): y
yayfeature was enabled successfully.                                                                                [ok]

% drush features-revert yayfeature
Do you really want to revert user_role? (y/n): y
Reverted user_role.                                                                                [ok]

% drush php-eval "print_r(user_roles())"
Array
(
    [1] => anonymous user
    [2] => authenticated user
    [5] => yay
)


Drupal 6 CCK date field is saving current time when the time field is left blank

Set your Default value for your event date field to Blank. This will make the date/time field empty upon default. A user has to enter date if it's a required field, but can leave the time field blank. If it's left blank it will default to 00:00.


ApacheSolr Search results with AJAX (D7)

Apache Solr AJAX module is available for D6

Project page says

  The Apache Solr AJAX module AJAXifies Apache Solr Search Integration –
  if you change your query or filters, you see the new result set
  instantly – no need to reload the full page.

For D7 there exists a Sandbox Project

You can try the module, Download module using below commands,

git clone --branch master http://git.drupal.org/sandbox/darthsteven/1116776.git apache_solr_ajax___d7
cd apache_solr_ajax___d7

Found an article here Drupal7 AJAXified Solr Search with facets. Search API, Panels and some custom code. you can give a try..


File browser of ckeditor increase overhead by loading unnecessary folders

This might help people having the same issue.

The way IMCE works will scan the whole directory over Http requests then filter using permissions. This can cause a big overhead.

My solution was to dynamically generate new folder every month, this way I make sure that there are not that many pictures to load every time.


What is better for performance: Many entity types with one bundle or one entity type with many bundles

This might not be the answer you want as it does not cover performance, but I think that you should choose what makes sense.

The Drupal entities system is about 'families of things'. Think of it as Classes in object oriented programming. An entity is a base class and a bundle is a sub-class that has access to the properties of its parent.

If all the types of entities have no shared fields/properties, create them as different entities. If they share properties, create them as bundles and put the shared properties in the entity. (Or use a combination of entities and bundles if it makes sense.)

But you can use other comparisons too. If you for instance have multiple types of documents (invoices, orders, notes, etc.) that all have different data, it could still make sense to make them as bundles of a 'document' entity.

With respect to memory, I think that ECK creates all entities as a type of EckEntity and then performs some magic to label it differently (please correct me if I am wrong). So you should not need to worry about loading of different classes, it is just the ECK classes.


Get "Raw" views data (with no or little markup)

Are you using Views 6.x-3.x or 7.x-3.x? If so, you can do a ton of the grunt work of stripping out views' default markup by adjusting fields' 'Style settings'. If you're using an older version of Views, Semantic Views does just about the same thing. One gotcha: If you don't want the default  wrapper around each field, you need to check the 'configure the field and label wrapper' option and set it to 'None' - that trips me up sometimes.

To adjust the other bits of markup around, for example, the entire view, or each row, you can copy the views template files (in the views/theme folder) into your theme's folder, and modify them to your heart's content.

The reason Views creates all this extraneous markup is that it is trying to be all things for everyone. I find, a lot of times, that it's easiest (and barely helps performance or page load times) to just go with the default markup, unless I'm trying to do some advanced theming. There's a class for just about everything!

On another note – if you're trying to return just some data, in a format like JSON or XML or something similar, you'll want to use a different display type for views besides one of the standard 'Unformatted fields' or 'list' types...


Random default image for a CCK image field

Module called image field random does the job you specified.

Description:
Populates an image field with a random image on save.


Why is my view for Solr indexing is not showing any results?

You need to export the solr conf from drupal and import it into solr server.

The export button is on your server conf in drupal.

The readme of the search api module can guide you about that.


Display a View of Private Organic Groups for 'Requesting Access'

Answer: edit the OG Extras Group view and do the following. Answer taken from here:https://drupal.stackexchange.com/a/865/2957

You can tell Views to ignore the access control of some of the Views. On Views 3.x, this parameter can be found under "Query Settings" / "Disable SQL rewriting", and is described as:

  Disabling SQL rewriting will disable node_access checks as well as
  other modules that implement hook_db_rewrite_sql().

The full nodes will stay private, so you should make sure not to link to them in the View so that your users do not land on "Access Denied" (403) pages.


How do I dynamically populate a select field?

I read somewhere that I couldn't use $form_state in a form hook

Not quite. If hook_form_alter() is being executed for the first time, then yes, $form_state can't be used to get a field's value because $form_state['values'] will not be set.

However, if hook_form_alter() is being re-executed, like from an #ajax callback, then $form_state['values'] will be set with the current form values, just like it would be in #submit[] and #validate[] functions. By the way, the $form['#validate'][] functions are also executed during an #ajax callback.

In your case, I believe you would get the current value of field_type from $form_state['values']['field_type'][LANGUAGE_NONE][0] (best to use the constant LANGUAGE_NONE instead of the string 'und'). Wherever you build the #options array for field_target_select during the execution of hook_form_alter(), you would do something like this:

$selected = 'some_default_value';
if (!empty($form_state['values']['field_type'][LANGUAGE_NONE][0])) {
  $selected = $form_state['values']['field_type'][LANGUAGE_NONE][0];
}
$child_options = my_function_to_get_child_options($selected);
$form['field_target_select'][LANGUAGE_NONE]['#options'] = $child_options;

What you have as your ajax callback function in your question looks correct:

function ajax_nudge_taxonomy_selected_callback($form, $form_state) {
  return $form['field_target_select'];
}


form Class, add a check function before the buildForm method

You can do all that inside of buildForm():

use Symfony\Component\HttpKernel\Exception\HttpException;

public function buildForm(array $form, FormStateInterface $form_state) {

  $data = a_check_function_or_method_before_buildForm();

  // throw an exception
  if (empty($data)) {
    throw new HttpException(500, 'No data connection.');
  }

  // or return an empty form with an error message
  if (empty($data)) {
    return $form['#markup'] = '
No data could be collected!
';
  }

  // build the form with $data

}

Another possibility would be to call first a controller, which then decides what to do, return a form or something else.


The field variables are not right - they need to correlate to the field name.

Example:

{{ content.field_icon_1 }}

{{ content.field_icon_1_title }}

These are the render arrays you are looking for. {{ content.text }} does not exist.

Also, keep in mind that these render arrays are rendering those fields - you may want to place the markup in those field specific templates.


Import CSV to nodes/entities in Drupal 8 including a UI

I do this all the time, making use of migration configuration entities (provided by the migrate_plus module). Define a migration plugin in your migration module's config/install directory, using the CSV source plugin from the migrate_source_csv module - omitting the 'path' source configuration, which will be filled in from the form. Let's say the ID of this migration is example_csv. Create a form with a file upload element (named 'csv_file' in this case), and in the submitForm() method:

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $all_files = $this->getRequest()->files->get('files', []);
    if (!empty($all_files['csv_file'])) {
      $validators = ['file_validate_extensions' => ['csv']];
      if ($file = file_save_upload('csv_file', $validators, 'public://', 0)) {
        $csv_migration = Migration::load('example_csv');
        $source = $csv_migration->get('source');
        $source['path'] = $file->getFileUri();
        $csv_migration->set('source', $source);
        $csv_migration->save();
        drupal_set_message($this->t('File uploaded as @uri.', ['@uri' => $file->getFileUri()]));
      }
      else {
        drupal_set_message($this->t('File upload failed.'));
      }
    }
  }

This updates the migration settings with the new file. You still have to run the migration using drush mi example_csv to actually import the content.

Or add some code to the function to actually execute the import:

      $migration_instance = \Drupal::service('plugin.manager.migration')->createInstance('example_csv');

      $executable = new MigrateExecutable($migration_instance, new MigrateMessage());

      try {
        $migration_status = $executable->import();
      }
      catch (\Exception $e) {
        \Drupal::logger('migrate_drupal_ui')->error($e->getMessage());
        $migration_status = MigrationInterface::RESULT_FAILED;
      }
      if ($migration_status) {
        drupal_set_message($this->t('Import Successful'));
      }
      else {
        drupal_set_message($migration_status, 'error');
      }


How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)

Here is a complete working example of overriding entity_metadata_user_access:

/**
 * Implements hook_module_implements_alter().
 */
function YOURMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'entity_info_alter') {
    $group = $implementations['YOURMODULE'];
    unset($implementations['YOURMODULE']);
    $implementations['YOURMODULE'] = $group;
  }
}

/**
 * Implements hook_entity_info_alter().
 */
function YOURMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['access callback'] = 'YOURMODULE_entity_metadata_user_access';
}

/**
 * Overrides entity_metadata_user_access function.
 */
function YOURMODULE_entity_metadata_user_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
  // Include Entity API module's logic
  $return = entity_metadata_user_access($op, $entity, $account, $entity_type);

  // Do your own logic here:
  // $return = $return || ...

  return $return;
}


How a field collection item is linked to a node

If you check admin/structure/field-collections, you will find the machine name of you collections in the first column. Prepend the machine name with "field_data", just like any other field, and you will find a table with an "entity_id" column.
In my case I have a collection called field_coworkers, and with

SELECT entity_type, entity_id FROM field_data_field_coworkers;

I can find the entities, that the fields are attached to.


The module Node Embed does not work for a custom user role

In the Module Documentation for both CKEditor Integration and WYSIWYG Integration it says:

"Enable the default view 'ckeditor-node-embed' (if its not already enabled). This view provides the content of the 7plugin dialog box."

The access to this view is "Permission | Administer Content"

If your custom roles do not have this permission it won't work.

I altered the access to be by Role and selected roles I wanted to be able to use Node Embed and it then worked.


This could be done by using theme_pager in TEMPLATE.PHP and by applying some if condition to be specific on just the search page

if(arg(0) == "search" && arg(1) == "site") {

$variables['quantity'] = 5;

}

These two lines did the magic !!!


How to conditionally show a views field?

You could do this by creating a views row template for your view and then adding in logic to test whether or not a thumbnail exists. This also lets you style the row output differently so you don't have a gap where the image would have been.

Here's the handbook section on views theming:

http://drupal.org/node/352970

but your logic in the views template would be something like:

  if ($fields['field_<video thumbnail field name here>']->content) {
      <output image>
  }


Quiz: Multiple choice question - Able to have the question correct with any correct answer

There is an option " Score if chosen and Score if not chosen " in multichoice question.

Set Score if not chosen = 1 and Score If chosen = 1

I hope, It would fix the issue.


Drush does not handle platform-specific issues such as file permissions. To get rid of group write, just run chmod -R g-w /path/to/drupal. If you wanted to do this automatically, you could make a post-update hook for the pm-updatecode command.  See the example Drush pm_update hook file for one example post hook function.

In your case, you would want something like this:

function drush_myhook_post_pm_updatecode() {
  passthru('chmod -R g-w .');
}

Save that in a file named myhook.drush.inc, and put it somewhere that Drush will find it, such as DRUPAL_ROOT/drush.  Then run drush cc drush, and your hook should run the next time you call drush pm-update.


Make sure that you have selected the Drupal site that your module is in (e.g. with an @alias, via --root and --uri, or cd /path/to/drupal/sites/default), and also ensure that the module is enabled. Otherwise, Drush will not find and load the file.


Views body field pop-up not loading and preview not working

This happened to me when I used the jQuery Update module with newer versions of jQuery (specifically 1.7). It causes several administrative oddities that you can get around, but the Views admin bug is pretty much crippling.

Here is a great patch that will allow you to choose a different version of jQuery for administrative pages, so for example, you can run jQuery 1.7 for the front end, but still use 1.4.4 for the administrative areas.

http://drupal.org/node/1524944


When using the batch API, can I setup multiple batch jobs or can I only setup one batch with multiple operations?

You can call batch_set() more than one time, and batch_process() will execute all the batch sets that have been set with every call to batch_set().

Normally a module will call batch_set() once, and pass as $batch['operations'] an array containing all the functions to call, but if two different modules are setting their own batch sets, they will be both executed.


Glossary mode on View Block disappear once a letter is clicked

Found the step by step correct setting  from here.

Create a view with page to show desired content type  (PS: you must create a view page, event you only use the view block)
click on CONTEXTUAL FILTERS
add content title
Select this page override
Select Provide default value and type fixed value

Enter "a" for default display only "a" word containing content and enter "all" for default display "all" content

select Specify validation criteria:Basic
Click More AND check Glossary mode option
Set Character limit 1
save
Use Ajax "yes"

Now add a attachment

click on CONTEXTUAL FILTERS

add content title
Select this attachment override
Click Display a summary
Click Unformatted and check Display items inline, under Separator add "-" or "|"
Set Attach to: page From ATTACHMENT SETTINGS
Set Inherit contextual filters: NO From ATTACHMENT SETTINGS
Use Ajax: Yes
Now save and run the page


How to give href links in custom modules for multilingual site?

You have a mistake in your code.

Wrong:

t('
Back to My Page
');

Correctly

'
' . l(t('Back to My Page'), 'my-page', array('attributes' => array('class' => array('stn')))) . '
';

For more information see function l();


How to specify a Rules condition like 'Before creating new content'?

Try using Rules (System) event "Drupal is initializing" (= init), which is actually BEFORE your form is shown. If you still can't get it to work, you may have to add an extra condition (like the URL of such form?).

You may also want to look at my answer to the question "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?". The sample there also includes such "Drupal is initializing".

However using a condition like path_has_alias will most likely NOT work either. Instead try replacing such condition with something similar to this Rules condition (in export format here):

{ "text_matches" : {
    "text" : [ "site:current-page:url" ],
    "match" : "node\/\\d+$",
    "operation" : "regex"
  }
}

In the above example, adapt the regular expression (= node\/\\d+$) to fit your URL naming for that form. In your case that regular expression should be something similar to node\/add\/manuscript-submission ...

To double check my own answer here (regex-stuff can be complicated ...), I created this prototype rule to get you going:

{ "rules_limit_access_url_node_add_something" : {
    "LABEL" : "Limit access URL node\/add\/*",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      },
      { "OR" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "node\/add\/book" } },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/add\/article",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Adding content for selected content types (such as for \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022) triggers some extra (Rules) logic, as you can see here.",
          "type" : "warning"
        }
      }
    ]
  }
}

Some more details to understand this proto-type (and make it work for your case also):

my 1st condition was just to have "some other condition" (in my case: applies for admins only), that's like the "data_is"-condition in your question (ignore my condition here for the rest).
my rules action in my prototype is just for (easy) debugging, and as a proof that my rule works as I expect it to work (use whatever action you see fit in your case).
the text_matches Rules condition is the most important part for you to look at. Actually, you'll need 1 such condition for each of your content type you want your rule to apply to. In my prototype I decided to have it apply to these 2 content types (whereas I used 2 different techniques you can pick from):

article : just using an exact text match
book: using an (extremely basic) regular expression (which you may want to take advantage of if you have multiple content types that you can group together in a single regular expression.

in case you didn't notice: be aware of the or part of the Rule condition also ...

I suggest you replace the path_has_alias condition with the applicable parts of my prototype rule above (i.e. the text_matches Rules conditions). Together with the "Drupal is initializing" (as in your edited version already), it should work.


Token's available "Replacement patterns" nested table should only be displayed on-demand

The default token tree can contain many thousands of lines of HTML, and the corresponding Javascript listeners and functionality can totally break things memory wise (or just give you a darn laggy experience). Plus it can confuse the heck out of site administrators.

These issues refer to current developments for loading the token tree 'on demand' or via a popup:

http://drupal.org/node/1684984
http://drupal.org/node/1229568

And OP pointed out in his comments, the Token tweaks module lets you set a depth limit for the token tree, which seems to have solved his memory problem.


Try with the value of the field and then concatenated with " like the second way:
I tested it with the following:

"name" : {{ content.field_text_test.0['#context']['value'] }}

"name" : {{ '\"' ~ content.field_text_test.0['#context']['value'] ~ '\"' }}

"name" : {{ '\"' }} {{ content.field_text_test.0['#context']['value'] ~ '\"' }} {{ '\"' }}

Here is the result:


Only show block if View or nid has certain term referenced to it

Did you try php code? If you enable 'PHP filter' module, you can add php code under 'Pages restricted to certain pages' option in block configuration and write your code like

<?php
$relative_path = request_uri();
if (some condition)   {

    return TRUE;
   }

 else
    return FALSE;

?>


If you can guarantee that no content will change on the live site while you do the work then that is fine.

This doesn't just include content creation, but also things like users signing up, users commenting or submitting webforms (unless you don't need to keep the webform submissions on your site), users flagging things, or rating things or subscribing to things.

Basically anything an user, admin or not, can do that might change the database in some way.
Or even things that change without user action, like time based events (this is probably less likely).

If you can't be sure of that and you can't afford to lose any data there are other options.
Whether these options are suitable for you also depends on your specific project and what you are actually changing.

You can try keeping a record of any database changes you make and make them again to the live site when deploying your changes.  This method is very error prone and can cause you grief if you are not extremely careful. - Things like views & contexts (and many other things) can be exported and imported, making certain tasks very easy to deploy in this manner. Other things require manually reproducing all the changes. There are other import/export type modules around for things like content types, users, taxonomy, menus etc. that are useful to varying degrees depending on your requirements.
You can try using modules like features or configuration management, for deploying your database config.

In the end, an exact answer cannot be given for a question like this as it depends on your requirements.


Do private properties persist between submissions on multi-step form?

Yes, do the same in D8, use $form_state. There is one caveat though. The form object and form state doesn't persist for the original form build. This was removed in the early stages of Drupal 8, because the form cache table was growing too fast. Since then forms are only cached after the first rebuild.

Normally this isn't a problem. If you store for example the form step in $form_state and it is initialized again with 1, but you have a form action triggered incrementing it to 2, your form then can use the cached $form_state to move back and forth.

This doesn't work however for data no longer available in later rebuilds. In this case use a hidden form value which will be cached together with the rendered form. Add the correct cache metadata for this value so that the rendered form can be invalidated when the value is changed.


Yes you can. But it needs a little bit of effort beforehand.

You need to have a composerized and version tracked local copy of your site on your computer. All the updating with Composer will happen there then. Look around a bit for Drupal+composerize, there are a few options out already to composerize your site.

From now on, after upgrading/updating your local site with Composer you upload the updated dependencies (the vendor/ directory, the core/ directory, all contrib directories, all libraries directories etc. but also updated scaffolding files like the robots.txt file, the development.services file etc.) to your host via (S)FTP for example and then access your live site's /update.php URL to trigger pending database updates.

As your local site should be version tracked now via Git for example you'll always see which files exactly got updated. For that you may need to adjust the default .gitignore files a bit to only ignore files with sensitive information like the settings.php file. But everything else (the vendor/ directory, the core/ directory, the contrib directories etc.) should better be version tracked to identify changes more easily. When you are done git add . everything and git commit -m "Update project." and git push to some private repo somewhere before you update your project the next time.

Ah look, there's still one alternative. Although what's been described above should be the recommended way you can follow the guide on Update core manually which tells you that you could Download Drupal zip and then upload certain contents of it to your host replacing the vendor/ and the core/ directory and some scaffolding files. This guide applies for Drupal 9 as well.


How do I retrieve node data for a referenced node in a template file?

it seems you need to know value of node which is referring the current node.
I am assuming machine name for the refernce field you have on event content type as "field_event_gallery"

In your custom module or template.php
// function to get backrefernce value.

function mymodulename_get_back_refernce_value($current_nid) {
  $nids = array();
  $results = db_select('field_data_field_event_gallery','n')
            ->fields('n',array('entity_id'))
            ->condition('field_event_gallery_nid',$current_nid)
            ->execute()
            ->fetchAll();
  if(is_array($results) && count($results) > 0) {
    foreach($results as $result) {
      $nids[] = $result->entity_id
    }
  }
  return $nids;
}

Now in your theme template.php use template_preprocess_node(),something like below

function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  if ($node->type == 'gallery') {
    //get referring nids
    $referring_nids = mymodulename_get_back_refernce_value($variables['node']->nid);
   if(count($referring_nids) > 0) {
     foreach($referring_nids as $referring_nid) {
       $referring_node = node_load($referring_nid);
       $variables['parent_event_link'][$referring_nid] = l(t('View parent event: @event_title', array('@event_title' => $referring_node->title)), 'node/' . $referring_nid);
   }
  }
}

finally in your template loop through $variables['parent_event_link'] and print it.

My codes are not tested, you have to debug to make them workign for you


How do I add a title attribute to the search submit button, exposed search, and reset buttons?

I have found the answer of my question.

I have used the following code in my form_alter function.

if ($form_id == 'search_block_form') {
   $form['actions']['submit']['#attributes']['title'] = t('Search');
  }
  if ($form_id == 'search_form') {
   $form['advanced']['submit']['#attributes']['title'] = t('Search');
  }
  if($form_id == 'views_exposed_form') {
    $form['submit']['#attributes']['title'] = t('Search');
   $form['reset']['#attributes']['title'] = t('Reset');
  }
  return $form;

It solved my problem.


node.getRevisionCreationTime equivalent in views

I found the answer eventually:

The crucial thing to do was to built the query starting with content revisions rather content. Rather unintuitively - creating a relationship the other way around does NOT get you to where you need to get in this situation!

To create a view listing the node's title, creation date, changed date, first publication, and publication date (the creation date of the current revision, follow these steps, and then add/remove as required:

Create a view showing content revisions of type all as follows, creating a page for easier review:

Remove the field "Content revision: Changed (Changed)" as this is not what we are interested in.
Add a relationship to Content as seen in the screenshot below:

This is one of the #DrupalWTF moments - where's the crucial documentation that allows me to select the correct relationship!?
There are apparently two RDBMS foreign key relationships you can use to join revisions and content:

a. Via content revision foreign key to the id of the node this revision belongs to - this is the first content relationship, and

b. Via revision id referenced as foreign key from the content table as current node - this is the second content relationship shown above in the screenshot.

For whatever reason you cannot reach the creation date of a revision when joining via the first content relationship, #Drupal, #WTF?

Require the relationship for all results, and change the administrative title if you wish:

Add a filter criterion to show only blog posts
The relationship shows revisions for all content types, so we need to filter for content type blog post (Yours may be different). This is pretty straightforward, see the following screenshots:

a. Select the filter criterion:

b. Configure the filter:

Add the various date related fields
This is repetitive; to add the fields select them all in the "Add field" form, and configure them all the same way:

(Content) Authored on,
(Content) Changed,
(Content) Published on,
(Content revision) Revision create time

Here are the screenshots:

and

Et voila, all fields present as required.

Now you (I) can go to town for formatting and sorting.


How do I add the page number to the page title on drupal default paginated pages?

Have you investigated the Page Title module? It, among other things, features

  Pagination Suffix: One of the things you may noticed about Drupal in terms of SEO is that whenever you go through a paged list of content, the page title never changes. Google Webmaster Tools will flag this up as a problem as you essentially have several different pages all being identified with the same page title. A new feature, introduced in Page Title 2.1, is the ability to append the page number as a suffix pattern. This means any URL which contains something like page=2 in the query string will also have an optional token pattern suffixed onto the end of it. Important: for this feature to work properly, you need to be running Token 1.12 or later.


In Views where it says Filter criteria there is a button that says Add, if you click on the arrow to the right you can access "And/Or, Rearrange", click that.

You now have an UI where you can group filters together and use OR between groups of filters.

In the example below the node should be Published or of type flickr_image. First thing you need to do is click Create new filter group. From there you can drag your filters into your groups. Next select if the operator between the filters should be AND or OR.

After this add your three fields. Use the filter between, if the filter is exposed it will look like this.

I would keep the first filter exposed and the other not exposed. But then comes the tricky part. The other two filters must inherit the value from the first exposed filter.

I think you need a little bit of glue code to get this going. Put the code below in a custom module. You need to change MYMODULE to the name of your module, MYVIEW to the machine name of your view. And of course field_1 and field_2 to their real names.

function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'MYVIEWNAME') {
    $filters = $view->display_handler->get_option('filters');
    $filters['field_2_value']['value']['min'] = $view->exposed_input['field_1_value']['min'];
    $filters['field_2_value']['value']['max'] = $view->exposed_input['field_1_value']['max'];
    $view->display_handler->override_option('filters', $filters);
  }
}


How to disable CACHE in FORM which loads database values in form fields

In the linked question the module Internal Page Cache was not enabled. If you don't want to disable page caching for all pages, but only for this form page, then add \Drupal::service('page_cache_kill_switch')->trigger() before you return the form:

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {

// Define form fields.
$form['#cache']['max-age'] = 0;

$form['name'] = array(
  '#type' => 'textfield',
  '#size' => 80,
  '#title' => t('Your Name'),
  '#default_value' => $result->name,
);

\Drupal::service('page_cache_kill_switch')->trigger();

return $form;
}


settings.php not in expected location(s)

You should search for setting file as:

find sites/ -name settings.php

as the file won't have any other name than settings.php (unless included from settings.php).

So you're down with these 2 valid entries:

sites/mobile.mysite.com/settings.php
sites/mysite.com/settings.php

Normally when you have settings.php in sites/default it applies to all sites, unless overridden by the site specific file (which is the case).

So:

sites/mobile.mysite.com will work on sites like mobile.mysite.com
sites/mysite.com/settings.php works on sites like mysite.com

Here is example from default.settings.php documentation page:

For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the settings.php file is searched in the following directories:

sites/www.drupal.org.mysite.test
sites/drupal.org.mysite.test
sites/org.mysite.test
sites/www.drupal.org.mysite
sites/drupal.org.mysite
sites/org.mysite
sites/www.drupal.org
sites/drupal.org
sites/org
sites/default

  The configuration directory will be discovered by stripping the website's hostname from left to right and pathname from right to left. The first configuration file found will be used and any others will be ignored. If no other configuration file is found then the default configuration file at sites/default will be used.

If you're still confused, please run drush status command to find the right settings file, e.g.

$ drush status | grep settings
 Drupal Settings File            :  sites/default/settings.php

or for specific site:

$ drush -l http://mobile.mysite.com status | grep settings


Why does updating the description of a custom block not update the block title?

There isn't really a reason, that's just how it works, the title of the block_content entity is an internal administrative title and while used as a suggestion for the initial block title, will then afterwards no longer have any effect on that.

You can place the same content block multiple times with different block titles.

While you think it's a bug, someone else might rely on it, it's not something that can be changed now, not by default anyway.


I need to prevent the translation of admin + toobar interface

You can use the Administration Language module:

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.


I was using the wrong hook as suggested by kevin. The hook to be used there was bootstrap_preprocess_menu__main .... It all became cleared after reading this comment https://api.drupal.org/comment/62602#comment-62602


Is it possible to do calculations like percentage in Views

You can use global php to acheive this (not recommended)

The best way to do it is by using this hook_views_pre_render(&$view) in your theme template file or in your custom module.


Until the issue Convert pager.inc to a service is solved you find the pager information still in global variables:

global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;

$count_of_total_records = $pager_total_items[$element];

Where $element defaults to '0' if this is the first pager with no element id set.


Restoring tempstore with another session ID

I've experienced the same issue while trying to pass private.tempstore data through anonymous to authenticated user in Drupal 8.

The function

user_login_finalize($user);

Performs de migrate() method. This method migrates anonymous session to authenticated session, but only the Native Session Storage (Symfony).

Private.tempstore has to manually be migrated as Ekta tells.

If you can't or you d'ont know how to implement it, just store the data in native $_SESSION['yourkey']

The problem it's that native Session it's loaded every time a page it's called, and with Tempstore you have more control about this. For this reason it's not the better solutions!.

This could be a good issue for Drupal Core in a future, migrate the tempstore too when session login.


how to check non existent field added later using entityfieldquery?

If you look on the fieldCondition documentation page you will see the following warning:

  Note that entities with empty field values will be excluded from the EntityFieldQuery results when using this method.

Checking whether a field exists or not has been added to entityFieldQuery in Drupal 8, but unfortunately won't be backported to Drupal 7.

This means you must use standard SelectQuery in order to achieve this. You must join the table which contains your data, and check whether the fiels IS NULL. It would be something like:

$q = db_select('node', 'n');
$q->condition('n.type', 'central_government_vacancy', '=')
->addJoin('LEFT', 'field_data_field_expired_processed', 'f')
->isNull('f.value');
$r = $q->execute();


How to add another color to theme color pallette?

It's starts working when I changed color.module in line 234 (added TRUE param):

$palette = color_get_palette($theme, TRUE);

Caution: This removes any custom colour palette so you might want to note the colour settings somewhere

EDIT

Now I have removed TRUE param from code, my new field still appears and everything is working correctly.

Anyway at last problem is trivial to solve, just disable and enable theme again, but it remove blocks settings etc on this theme.


Display popup message when i hover on taxonomy link to display description

It can be easily done with Simple Dialog module. All instructions you can find at the module page


How to filter latest 10 days from the current date in Views

You can set it using filter criteria. Look at the snapshot below.

Look at the Pist date (> -10 days),by adding the field post date in the filter criteria and setting to -10 days will give you the nodes created in last 10 days


The Domain Access module has quite thorough documentation.

For your specific issue, you want the Before installing section, which covers the necessary Apache configuration. In short, you're right that you want to configure all domains to point at a single docroot--once that is set up, Domain Access will properly handle which content is available on specific domains.


How do I get kint() to include the variable name in output?

Put the variables in an array. Then you see the variable names and you have the advantage, that if the first variable is a big array you can collapse it to see the second one:

kint(array(
  'abc' => $abc,
  'def' => $def,
));


login_destination module and link with anchor

Try this.

<?php if ($comment_form): ?>

<?php l('Login or anonymous comment', user, array('query' => 'current=node/3#comments')); ?>

<?php print $comment_form; ?>


How can I get both "body" and "summary" fields to appear in a new article?

I think you'll have to do it in a form alter hook as you suggest, I don't know of a way to do it in the UI.

Looking at the code for text summary fields the "Edit Summary" link and functionality are done completely through javascript, added in the form by setting an #attached property on the element, which includes a JS file (modules/field/modules/text/text.js).

All that JS file does is add that "Edit Summary" link so it would be completely safe to just get rid of it. This example uses the standard page content type:

function mymodule_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  unset($form['body'][LANGUAGE_NONE][0]['summary']['#attached']);
}


Drupal 7 admin can't upload images, but all other users can

i guess you reached the upload limit for user 1, are you using IMCE ?


Passing node id as contextual filter to field collection view

Please try the following.

Add a relationship "Field collection item: Entity with the {Field Collection name (field_collection_machine_name)}" You should change the one in {} with your filed.
Now you should get the content nid in the contextual filter which could be used to filter using the node id.
To limit it to show only the flagged fields you should select the "Flags: Field collection item flag" from the relationships and select the flag you want to filter it by and select if it should be for the current user or all users