How to make Entity View show Entity's custom dynamic label as page title (D8)

Similar to the NodeViewController, you can write you own VeranstaltungViewController extending EntityViewController, and implement a title function. In your route can then set _title_callback to use this function (see NodeRouteProvider as reference).


Adding an auto-complete field to a custom module form

There's a full example for Drupal 6 here: Textfield that uses autocomplete. The code will probably be useful to people on this site as well so I'll post i here:

The following is based on a module with the name: 'cities'

In your form function:

$form['city'] = array(
  '#type' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => MENU_CALLBACK
  );
  return $items;
}

Also in your module file:

function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->city] = check_plain($data->city);
  }
  // return for JS
  print drupal_to_js($matches);
  exit();
}


Looks like you can get a renderable array using profile2_view():
/**
 * View a profile.
 *
 * @see Profile::view()
 */
function profile2_view($profile, $view_mode = 'full', $langcode = NULL, $page = NULL) {
  return $profile->view($view_mode, $langcode, $page);
}

https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L1084
See also that modules hook_user_view() which does the same:
https://git.drupalcode.org/project/profile2/-/blob/7.x-1.x/profile2.module#L399
/**
 * Implements hook_user_view().
 */
function profile2_user_view($account, $view_mode, $langcode) {
  foreach (profile2_get_types() as $type => $profile_type) {
    if ($profile_type->userView && $profile = profile2_load_by_user($account, $type)) {
      if (profile2_access('view', $profile)) {
        $account->content['profile_' . $type] = array(
          '#type' => 'user_profile_category',
          '#title' => $profile_type->getTranslation('label'),
          '#prefix' => 'type . '">',
        );
        $account->content['profile_' . $type]['view'] = $profile->view($view_mode);
      }
    }
  }
}

With a single entity in your code, you can:
render($profile2_p->view($some_view_mode));


How to use the language neutral url alias pattern in pathauto?

You can use the Pathauto i18n module:

  This module provides functionality to create aliases for each
  language. Also this module will be helpful, if you use field
  translation and you want show node on all language with paths,
  different from node/nid.


How can I link to a specific comment on drupal.org?

References to project issues in the form of [#1234] (or [#1234-2] for comments) turn into links automatically

That is from the very bottom of compose tips.

So just replace the colon with a hyphen and your guess would have been perfect.


Define a normalizer just for a specific use case

The supportsNormalization method comes from the Symfony Serializer component, and for this reason it is up to the implementation to decide what to do with these items.

However Drupal core serialization module provides a nice base class, ComplexDataNormalizer, which is probably the class your Normalizer should extend when you need to normalize a complex data type such as an Entity, Map or a list of those things.

Classes that extend the base class should provide a unique interface to target: ComplexDataNormalizer::$supportedInterfaceOrClass.

With the Symfony service locator, as long as the normalizer weight is adjusted for any conflicts, then it will be used. A good example of this is to look at the core hal module.

So for instance, in my module xero, I provide my own Typed Data data types to interact with a third party API and the top-level data types I have my own interface.

Example:

class XeroNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {

  protected $supportedInterfaceOrClass = 'Drupal\xero\TypedData\XeroTypeInterface';

You can read more about how the Drupal serialization module works in the documentation: https://www.drupal.org/docs/8/api/serialization-api/how-the-serializer-works


How to programmatically set the field formatter for a field given certain conditions

Is there a more convenient way of setting a field formatter for a particular field on an entity?

Yes, choose the formatter in the view mode settings (configure in the user interface) rather than using template preprocess.

(I found this old question looking for how to make a field formatter, and ended up copying Drupal\user\Plugin\Field\FieldFormatter and simplifying it by dropping the configuration parts, and then simply selecting that formatter on the view modes and Views tables i wanted to use it on.)

For ensuring this formatter doesn't show up in places it shouldn't, the key part is "isApplicable"; here's what mine looked like for a custom entity 'give_donation' and a field named 'recurring':

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition->getTargetEntityTypeId() === 'give_donation' && $field_definition->getName() === 'recurring';
  }


You need to add css to your theme css file and clear cache to see the effect...

I am not a css guy, but below css code should work...

.view-footballlinks .item-list ul li {
  float:right;
}

Try, and let us know...


Change "Passwords match" and "Password Strength" text on signup

The two sentences are set by Javascript (/modules/user/user.js) so for this you have to use JS too..

$(".password-strength-title").val("Test");

can replace the first one, but for the other it is more complicate. I have to look deeper.

EDIT

The info are here now I don't know if it is possible to do an alter

EDIT

Ok so for doing what you want 2 steps:

function your_module_element_info_alter(&$type){
  $type['password_confirm']['#process'][] = 'your_module_form_process_password_confirm';
}

Then alter the data:

function your_module_form_process_password_confirm($element){
  $element['#attached']['js'][1]['data']['password']['strengthTitle'] = t("Test Title");
  $element['#attached']['js'][1]['data']['password']['confirmTitle'] = t("Test confirm");

  return $element;
}


How can you group multiple answer fields?

The drupal 6 version of cck comes with a sub-module called multigroup. This will allow you to group multiple fields together and allow for unlimited inputs per group.


Can I call drupal_goto in form #submit handler?

Can you call drupal_goto in a submit handler: Yes
Should you call drupal_goto in a submit handler: No

Why?

The reason is that potentially other submit handlers might need to be called in order for things to work properly. If you call drupal_goto you would stop the execution flow and make it impossible for the other submit handlers to do their thing.

What you should do instead is to use $form_state['redirect'], which when set will be the url that is redirected to when the submission process is completed.

In your specific use case, however it could work since you don't want the node to be saved, but stopping the process in this way could give you strange bugs/side effects.

But you really should't be doing it this way.

Instead you should attach a validate handler to the node form. If the validation fails the node is not saved and you can display any message to the user via drupal_set_messsage or form_set_error. You could save in $form_state that the message has been displayed to the user and allow him to save the node anyway if he resubmits the form. This is what the validate handlers are built for, after all.


Specify node.tpl.php file via template.php for a specific node.

Try:

if ($variables['nid'] == '12') {
  $variables["theme_hook_suggestions"][] = "node__nrg_shop_display";
}

The templates folder should be checked automatically so you won't need to prepend the path, and you don't need to add tpl.php to the end of the string; the above should work for a template file called node--nrg-shop-display.tpl.php


Workaround to post inline JS code at any time in D8?

Sometimes the $form is not accessible and  I'd like to invoke some JS code on certain functions and conditions for debugging purposes.

Not sure if this will do for you, but posting this anyways just in case.
I use Greasemonkey for Firefox and Tampermonkey for Chrome which allows your browser to load any js file that you write locally on this app/your computer.


Custom Webform Email Response to two different recipients

We ended up doing this by creating a custom email template (e.g. webform-mail-26.tpl.php). And then we created another email recipient but chose to over-ride the "default" template with a "custom" template where I used the same text and tokens as the "default" template. It was counter-intuitive but it worked.


How can i Use drupal 8 CMI between two different sites?

I'm afraid you are right, configuration management is for different instances of a same site. According to the Drupal 8 CMI documentation,

  The Configuration Manager module in Drupal 8 provides a user interface
  for importing and exporting configuration changes between a Drupal
  installation in different environments, such as Development, Staging
  and Production, so you can make and verify your changes with a
  comfortable distance from your live environment.

The same idea appears in this article,

  Perhaps the most important concept to understand is that the
  configuration system is designed to optimize the process of moving
  configuration between instances of the same site. It is not intended
  to allow exporting the configuration from one site to another. In
  order to move configuration data, the site and import files must have
  matching values for UUID in the system.site configuration item. In
  other words, additional environments should initially be set up as
  clones of the site. We did not, for instance, hope to facilitate
  exporting configuration from whitehouse.gov and importing it into
  harvard.edu.


Best way to dynamically change only the href of a link in the main menu not the markup

Check out theme_menu_link. You can add it to the template.php file of your subtheme. Be sure to return the correctly formatted string.


Displaying taxonomy term list within another taxonomy term

Dee, I completely did not understand your question. But these code might help you.

/*To load a vocabulary*/

 $vocabulary = taxonomy_vocabulary_machine_name_load($machine_name);
 Example::$vocabulary = taxonomy_vocabulary_machine_name_load('book');

/*To get array of all term objects as a tree*/

$terms = taxonomy_get_tree($vocabulary);

/*To get children of all terms*/

foreach($term as $aterm) {

  $child = taxonomy_get_children($aterm);

}


Pressflow 7 doesn't seem to contain any relevant performance improvements at this time.

Below is a diff from 7.10 to the pressflow/master branch on github, where pressflow is now maintained. (https://github.com/pressflow/7)

$ git diff -R pressflow/master
diff --git b/includes/bootstrap.inc a/includes/bootstrap.inc
index d63a59b..e5e7ab7 100644
--- b/includes/bootstrap.inc
+++ a/includes/bootstrap.inc
@@ -728,6 +728,22 @@ function drupal_settings_initialize() {
   }
   $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';

+  // Load environmental config, if present.
+  if (isset($_SERVER['PRESSFLOW_SETTINGS'])) {
+    $pressflow_settings = json_decode($_SERVER['PRESSFLOW_SETTINGS'], TRUE);
+    foreach ($pressflow_settings as $key => $value) {
+      // One level of depth should be enough for $conf and $database.
+      if ($key == 'conf') {
+        foreach($value as $conf_key => $conf_value) {
+          $conf[$conf_key] = $conf_value;
+        }
+      }
+      else {
+        $$key = $value;
+      }
+    }
+  }
+
   if (isset($base_url)) {
     // Parse fixed base URL from settings.php.
     $parts = parse_url($base_url);
@@ -2329,6 +2345,17 @@ function _drupal_bootstrap_database() {
 function _drupal_bootstrap_variables() {
   global $conf;

+  // Pressflow Smart Start
+  if (!empty($GLOBALS['databases']) && variable_get('pressflow_smart_start', FALSE)) {
+    try {
+      $result = db_query('SELECT s.name FROM {system} s WHERE s.name = :name', array(':name' => 'system'));
+    } catch (Exception $e) {
+      // Redirect to the installer if an essential table is missing.
+      include_once DRUPAL_ROOT . '/includes/install.inc';
+      install_goto('install.php');
+    }
+  }
+
   // Initialize the lock system.
   require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
   lock_initialize();
diff --git b/sites/default/default.settings.php a/sites/default/default.settings.php
index f8894aa..08fc81b 100644
--- b/sites/default/default.settings.php
+++ a/sites/default/default.settings.php
@@ -487,3 +487,13 @@ $conf['404_fast_html'] = '<html xmlns="http://www.w3.org/1999/xhtml"><head><titl
  * Remove the leading hash signs to disable.
  */
 # $conf['allow_authorize_operations'] = FALSE;
+
+/**
+ * Smart start:
+ *
+ * If you would prefer to be redirected to the installation system when a
+ * valid settings.php file is present but no tables are installed, remove
+ * the leading hash sign below.
+ */
+# $conf['pressflow_smart_start'] = TRUE;

As this shows, there are only two actual changes, one allows to set $conf values from the environment and the other is a safety check when Drupal isn't installed properly. Both are probably only really relevant for their Pantheon hosting environment.

So, while the interview posted by @wiim is nice, it's two years old and nothing has really happened. So, you can IMHO save yourself the hassle of switching for now (of course, this might change).


how to effectively hide a field (with title) on a form

You can set the #access property for the form field to FALSE. The form field will not be shown to the users, but its value will be still be available in $form_state['values'] for the submission, and validation handlers.

Using #access is always the suggested way to avoid users can change the value of a form field, and avoid any third-party module depending on that form field starts to raise warnings, or fails to work as expected.


Guzzle httpClient Drupal Core throwing cURL error 28 Operation timed out

As @cilefen suggested in his comments my problem was related to the timeout value that was being set in the calling code rather then an error with an undefined constant. I had fixed the error in my particular situation by adjusting the timeout value in my custom code that was making the API call with the following (600 is an example).

$request = $client->post($url, [
  'timeout' => 600,
  'json' => [array(...)],
]);


Can't seem to make use of new user account field in display suite

Display Suite only shows user fields Author and User Picture by default. However, there is a way to do this by defining a Code Field with Display Suite

Go to admin/structure/ds/fieldsand create a Code Field

Select Entities: Node (make this field available to nodes). You can do some additional filtering in Limit field if you want

Use the following code (be sure to select Display Suite code en Text format and use the php tags)

 $author = $entity->uid;
 $u = user_load($author);
 if (isset($u->field_special_field[LANGUAGE_NONE][0]['value'])) {
   return $u->field_special_field[LANGUAGE_NONE][0]['value'];
 }

(Replace field_special_field with the name of your field,e.g. field_organization_role). Then go to your Content type Manage display and add the new field.

Another way:

This is really easy to do with Views, though. Create a View of your content type, select Unformatted list of fields. Add all the fields you want from your Content Type. Go to Advanced and create a Relationship to Content: Author. This will expose ALL the User fields in the list of Fields. You can add them at your heart's content. If you want to show only one node (rather than a list of all nodes) you can use Content: Nid in the Contextual filter area and pass the nid at the end of the url, as in www.example.com/view_name/[nid]


Views PHP: Comparing two Field and display Answer

First,  In your Match Results view, add a Global: Custom text field and just leave it blank/empty. (we will use this field to print the outcome)

You can override the view's display through your themes template file.

Go to sites/all/themes/YOURTHEME/  look for template.php and open it. You probably have other code inside there, so make extra space by hitting enter at the bottom and add the following code.

function YOURTHEME_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw > $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Win';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw < $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Loss';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw == $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Draw';
      }

}

Replace YOURTHEME with your actual theme name

Replace VIEWNAME with your view machine name. (example: match_results)

Replace DISPLAY with your display machine name. (example: block, block_1 ) You can find the name by looking at your view. (see picture below). If you're using the Master view, then the machine name is "default"

.jpg


Passing context to a block field of a display suite node

The way to do it:

Enable Views content pane (views_content, part of ctools I think)
Create a Views display using content pane instead of block display type.
Configure a contextual filter, but don't give it a default value.
Configure the content pane "argument settings" to take a node id from url.
In Display Suite, create a "Dynamic field". Move it into one of the layout regions.
Click the cog-wheel icon in the dynamic field, choose content to display, you find your newly created Views display under "Views panes".

Good luck!


pass array from module to render in template

Place the array into the variables. like.

function mysite_preprocess_panels_pane(&$variables) {
 $variables['ar'] = array('arg1'=> 'car', 'arg2'=> 'truck');
}


Centering pager for view using Bootstrap 3

Bootstrap centers the pagination by wrapping it in a

There are definitely a few ways of doing something like this, only going to list the main two.

At the theme level you would want to override theme_pager in your template.php with special attention being paid on the return statement.

Original theme_pager() return (see link above):

return '
' . t('Pages') . '
' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pager')),
));

Modified theme_pager() return to center pagination (taken from Bootstrap Theme):

return '
' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pagination')),
)) . '
';

Looking at the code between these you can see that all that is added is the text-center wrap, plus the Bootstrap theme actually uses the pagination class from Bootstrap unlike Bootstrap Business (seems like a weird thing to say when I said it out loud).

I couldn't actually get the other CSS answer to work with the demo of the Bootstrap Business theme but that doesn't mean that it won't or is wrong per say. Just incase you have an issue with that one here is one that I got to work with the demo site:

ul.pager li a, ul.pager li.pager-current {
  display: inline-block;
}
.item-list ul.pager li {
  float: none;
}

That being said I would go with the way Bootstrap does this, it's already proven and holds up better than changing those lines of CSS I believe.


How to add twig template suggestions per display mode with custom module?

The fix was ensuring to add the theme suggestions via HOOK_theme_suggestions_HOOK_alter(), as well as switching one template from user to user__full. Below is the updated module code:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_user_alter(&$suggestions, $variables) {

  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = 'user__' . $view_mode;
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user__full'    => [
      'template'  => 'user--full',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token'   => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];
}


How to submit a node form with AJAX Drupal 7

Check out this article.

http://drupal.org/node/752056

It should get you started.


How to trim text fields entered in the node automatically

To correct all those values entered into the database already, I'd suggest doing a mysql trim on those values and resetting them. Make sure you backup the tables first of course, but something like this should do it (if your field name is field_text_test):

UPDATE field_data_field_text_test SET field_text_test_value = TRIM(field_text_test_value);
UPDATE field_revision_field_text_test SET field_text_test_value = TRIM(field_text_test_value);

After you've run those statements, do a flush all caches on your drupal site.

And then to avoid this happening again, you could use the Form API Validation module which adds a trim filter on fields.


Update Node Problematically is not working fine

You can try to load node with its id :

   $nodenew = node_load(14); // load the complete node

So when you use node_save() all other field values that was previously stored in database will automatically get loaded. Then only thing remains is the field you want to update.

   $nodenew->field_site_url[$array_id]['value']=$website_url;
   $nodenew->revision=1;
   $nodenew->created = time();
   $nodenew->changed = $nodenew->created;
   $nodenew->comment = 0;
   $nodenew->type ='product';
   node_save($nodenew);


drupal single page Error 324 (net::ERR_EMPTY_RESPONSE)

I finally found the source of the problem, it was a unsupported PHP function in the view template. As I replaced this function, the page worked normally.


allow specific user to access specific pages in custom module

I did that through routing.yml file. Thanks for the comments. I posted this just for reference that may help someone else.

notices.notices_form:
  path: '/notices/addupdate'
  defaults:
    _form: '\Drupal\notices\Form\NoticesAddUpdateForm'
    _title: 'Notices Form'
  requirements:
    _role: 'administrator'

notices.notices_search_form:
  path: '/notices/search'
  defaults:
    _form: '\Drupal\notices\Form\NoticesSearchForm'
    _title: 'Search Notices'
  requirements:
    _access: 'TRUE'


There is no way to do this via Drush; the easiest way to find the locked files is with the find command:

find . -name ".drush-lock-update"


A deleted image filename is printed to the top of SOME of my nodes

While I don't know the mechanism of the behavior, deleting the SQL file-data from the relevant SQL tables via PHPmyAdmin and then flushing all caches, solved the problem.

Note: There where references to the file in 2 tables (One table deals with files and one deals with the Watchdog).


SOLUTION:

Discovered that the items for basic page and article had both been marked as disabled (though not by me) in the navigation menu. Re-enabling them under admin/structure/menu/manage/navigation fixed the problem immediately.

D7 Add Content is missing content types


What's the best option for responsive drupal theme using sass, Zen sub-theme or twitter Bootstrap

In my opinion bootstrap, with bower you can download bootstrap-sass in your theme folder really handy.


Import data into Select List using using Feeds and the Feeds XML Parser from xml file

If you're on Drupal 7.x, you probably want to be using this module:

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

This is the new home for no-longer actively maintained one (https://www.drupal.org/project/feeds_xpathparser)

I've been using feeds_ex and haven't had this problem.

Also, and I'm not sure about this, but I think the machine names for the list values should all be lowercase - but I could be wrong about this.


What is the default value for $operator in condition()?

QueryConditionInterface is just that, an interface. The actual class used is DatabaseCondition.

In DatabaseCondition:condition(), it does set the default operator:

if (!isset($operator)) {
  if (is_array($value)) {
    $operator = 'IN';
  }
  elseif (!isset($value)) {
    $operator = 'IS NULL';
  }
  else {
    $operator = '=';
  }
}


Remove HTML element when pasting from Word

Hi You can use https://www.drupal.org/project/wysiwyg_filter
and configure him in /admin/config/content/ckeditor , content types


How can I define the activity and/or case in a CiviCRM-integrated webform?

Case and activity settings are a bit tangled up with each other in the current (v4.9) version of the module...

BUT, I've just committed several changes to 4.x-dev (soon to be released as v4.10) which:

Support multiple activities and multiple cases on a webform
Detach the activity and case tabs from each other so you can more cleanly work with one or the other
Allow you to file an activity on a case without having to go through the entire case configuration on the webform

When I get this into working shape (probably next week) I would love your help testing it out.

And to answer your question, if you are updating an existing activity it should be sufficient to pass the activity id. In the current version this will only work if contact 1 is the creator or target or assignee of the activity. I may be able to make this more flexible in the next version.


On/Off Checkbox to toggle filter value in views exposed filter

Not totally sure if this is the same as your requirements, but I managed to have one checkbox that only shows relevant content when checked.
Basically, I chose these options in filter options:

Expose this filter to visitors, to allow them to change it
Filter type to expose: Single filter
Is one of: (select the 'on' value)
Allow multiple selections (checked)
Limit list to selected items (checked)

Then in BEF:
6. Display exposed filter as: Checkboxes/radio buttons.

So, pretty much the only difference is the selection of "Limit list to selected items" in the filter options. See pic below. (And it doesn't use jquery, so should be more performant) Hope that helps.

.


Where can I find custom content type templates file?

It's all in here Twig Template naming conventions

Nodes
Pattern: node--[type|nodeid]--[viewmode].html.twig
Base template: node.html.twig (base location: core/modules/node/templates/node.html.twig)

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. node--nodeid--viewmode.html.twig
2. node--nodeid.html.twig
3. node--type--viewmode.html.twig
4. node--type.html.twig
5. node--viewmode.html.twig
6. node.html.twig
Note that underscores in a content type's machine name are replaced by hyphens.

The higher the number the less specific, For example, the last one (6) it affects everything.

While (1) affects a specific node with a specific view mode, Ex: node--1--teaser.html.twig will only affect /node/1 with teaser view.

For your case, you want to use (4), so in your case, its node--news.html.twig


You could in a template preprocess function easily detect the number of results (rows) that a view has and set the output to an empty string if that is the case.

To get this to work, you might need to do a bit of work in template, as Views always adds some wrapping HTML that you probably don't want if the view is empty.

I would probably be easiest to do in the template_preprocess_views_view() preprocess function. You can consult the views interface to get hints about templates.


How to filter nodes on a view based on user role shared by both nodes authors and current user?

Finally, using role as contextual filter was not a good choice. It is working now but with a different option.
Using a term reference field for both user and node with the same vocabulary was my solution.
In my example, let's say I have a taxonomy field called Staff (field_staff), related to a vocabulary called Staff too.
I have added this field to user account and content type (the one(s) I need in Views).
Then, within my View, I have added two relationships:
Content using field_staff and
User using field_staff with a relationship to the previous relationship (reverse__user__field_staff).
Finally, I have added a contextual filter on User ID provided by default (logged in user) and with a relationship to User using field_staff.
And voilà, the view is listing any nodes filtered by field_staff equal to the current user field_staff.
Hope this helps.


Theming Views, getting a list of object I have access of

The 3 tools that I find vital to this is:

Click "Theme: Information" in the view page itself. This will give you a list of template files being used for the view and suggestions of template files you can use to override them by placing them in your theme folder (or a template subfolder of your theme depending on how you have set up in your .info file).
Devel module - this will allow you to inspect just about any aspect of your site and all the variables, fields etc available to you in a particular node/view.
Drupalforfirebug module and accompanying firefox/chrome plugin. Although I find it somewhat buggy in certain areas of drupal, it is great for inspecting all aspects of drupal (especially views).


Migrate content of cck fields from drupal 5 to 7

Once I had a same problem and after couple of hours testing/working with couple of approaches I figured out that the best way to deal with this is using views bonus pack module to get a CSV export file:

  This group of modules is sort of a recipe module that makes things
  easier by showing how to integrate some other modules as well as
  providing miscellaneous features that aren't distributed by Views
  itself. Sometimes these modules are only base recipes that will need
  to be themed and spiced up to fit your needs so be creative!

and import it via feeds module:

  Import or aggregate data as nodes, users, taxonomy terms or simple
  database records.


What is the process to upload custom drupal themes to Drupal.org? What is relevance of "PayWithPaytm"?

The Drupal community pages are basically a Wiki done in Drupal.  As such, anyone can get authorized to make changes.  However, like a Wiki, people can add spam like this.  This page was spammed today.

I've reverted the page back to the last revision so it should now be helpful.

Welcome to Drupal.


Views with taxonomy contextual filter not working in Russian language in Drupal 7

It's probably the collation of your fields and tables in database, try to check to see if all the tables collation is set to utf8_general_ci

you can google to find an script to bulk update your tables and or fields collation


How can I cascade field display formatters?

You should try the Media module. I think it will solve your problems.


How to display all the events in a week view of a calendar?

Calendar module creates a node for each day.So all you need to do is create a field of type date in your content type and then create nodes.

Alternatively,you can try using jquery fullcalendar plugin(http://code.runnable.com/UfNTSnKMU1ZgAACt/how-to-add-calendar-using-jquery-and-fullcalendar) and provide data for each day programmatically.


How do I sort nodes in node_view_multiple()?

The best way I can think of to do this is using EntityFieldQuery:

$query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'your_type')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('nid', 'ASC')
    ->propertyOrderBy('changed', 'DESC')
    ->addTag('random') //this gets the query passed through hook_query_alter
    ->execute();

And you will need hook_query_alter to do the random sort because EFQ doesn't do that natively

function icac_custom_query_random_alter(QueryAlterableInterface $query) {
  $query->orderRandom();
}

To get the nid's for node_load_multiple

$nids = array_keys($entities['node']);


After a lot of research i finally solved my problem. I don't know if this is the best way of doing it but it works for me.

I added a THEME_field() function to my template.php of the desired field.

Inside my template function i removed the even/odd css classes because i want all in a single line.
Probably exists a better way to access field values, this was the solution i found. Digging the $item array i was able to get my code and color description values.

If someone knows a better way of doing this please help me improve it.
There goes the code i hope it helps someone else.
Don't forget to replace THEME by your theme name and the FIELDNAME.

function THEME_field__FIELDNAME($variables) {
$output = '';

// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
  $output .= '
' . $variables['label'] . ':&nbsp;
';
}

// Render the items.
$output .= '
';
$codes = "";
$colors ="";
foreach ($variables['items'] as $delta => $item) {

    $code = $item['field_color_description']['#object']->title_field['und'][0]['value'];
    $color = $item['field_color_description']['#object']->field_color_description['und'][0]['node']->title;

    $codes .= $code."/";
        //avoid repeated color descriptions
        if (strpos($colors,$color) === false)
        {
        $colors .= $color."/";
        }
     }
     $classes = 'field-item even';

     $codeAndColors = rtrim($codes,"/") . " ". rtrim($colors,"/");
     $output .= '
' . $codeAndColors . '
';
     $output .= '
';

     // Render the top-level DIV.
     $output = '
' . $output . '
';

     return $output;

}


The order of the output for a render array is determined by the #weight attributes of it's contents. To reorder elements in a render array, set the #weight attribute of the target elements, using smaller values for elements that should appear earlier. Then set the #sorted attribute of the parent element to FALSE, this will make Drupal resort the elements of the render array before generating the output HTML. You can see an example of the technique in the Render Example module included in the Drupal Examples module. The relevant code is

$page['sidebar_first'] = array_reverse($page['sidebar_first']);
foreach (element_children($page['sidebar_first']) as $element) {
  // Reverse the weights if they exist.
  if (!empty($page['sidebar_first'][$element]['#weight'])) {
    $page['sidebar_first'][$element]['#weight'] *= -1;
  }
}
$page['sidebar_first']['#sorted'] = FALSE;

Now when Drupal goes to render the content, it will first be sorted according to #weight. Also note that elements which do not specify a #weight attribute are assigned a weight of 0 during sorting, so they will appear in the output in the order in which they are defined in the render array.


How to get formatted date string from a DateTimeItem object

A date field has two properties, value to store the date in UTC and date, a computed field returning a DrupalDateTime object, on which you can use the methods getTimestamp() or format():

// get unix timestamp
$timestamp = $node->field_date->date->getTimestamp();
// get a formatted date
$date_formatted = $node->field_date->date->format('Y-m-d H:i:s');

For a date range field:

// formatted start date
$start_date_formatted = $node->field_date->start_date->format('Y-m-d H:i:s');
// formatted end date
$end_date_formatted = $node->field_date->end_date->format('Y-m-d H:i:s');


how to duplicate a form action programatically

In your submit handler:

$form_state->setRedirect($route_name, $parameters, $options);

Or if you have a URL object:

$form_state->setRedirectUrl($url);

Reference:

FormState::setRedirect
FormState::setRedirectUrl


How to set up path for library and include files

If it's a theme function, guessing from the file name you mentioned, you should use them theme() function to get the themed output.

To get the path of a module relative to the Drupal root, use drupal_get_path() function.

If you want to include or require a file, you can use module_load_include(). However, note that if the including files print anything, they will be printed to the current output buffer (which means they will be printed on user browser).

Given the above available features, I think it's theme() that you are looking for.


I have been able to get Webform information into Views in the past, but I ended up delving into the database to do so since the integration of Webform and Views is limited to submission ids and edit links, not the specific data that was entered by the user.

I found this tutorial online that might be useful for you. http://archive.org/details/DisplayWebformSubmissionDataInViews


Replace this line(in sites\all\modules\service_links\js\facebook_like.js):

iframe.src = $(this).attr('href').replace('http://', '//').replace(/http[s]*\%3A\/\//, '');

with the below line:

iframe.src = $(this).attr('href').replace('http://', '//');


how to create manual reports and graphical represntation as content type

Try to use any of these modules :

Google Analytics Report

  Google Analytics Reports provides graphical reporting of your site's
  tracking data. Graphical reports include a dashboard widget for
  admins, a small path-based report in blocks, and a full path-based
  report.

Forena Reports

  Forena is database report writing software built on the Drupal
  platform. Forena is built of the idea that if you can write the SQL
  necessary to get the data out of a database, it should take very
  little work to get that data out on the web. It is designed to
  leverage knowledge of HTML, CSS, SQL and Java Script to help you
  create rich interactive web reports.

Charts & Graphs

  Charts and Graphs is an API for developers. It can easily be extended
  by third-party modules that want to add their own charting
  implementations. It does nothing by itself.


Look at the HTML of the page, find the id of the input/upload button, then hide it via a display:none; in your css will get you going quickly; otherwise, you will have to do a form_alter() in drupal to remove it from the form.


How to set a value programatically only when a content type is saved for the first time?

As per @Ivan Jaros comment:

/*
 * Implements hook_ENTITY_TYPE_presave()
 */
function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getType() == 'my_content_type') {
    /// Log the user agent if the account is being created.
    if ($entity->isNew()) {
      $entity->set("field_useragent", $_SERVER['HTTP_USER_AGENT']);
    }
  }
}


The only classes that extend ResourceBase implemented by Drupal core don't check/use what passed in the request. So I could not use Drupal core code as example.

If you really need to access any request value, and the argument passed to the get() or post() methods is not enough/adequate for your purpose, you can inject the request object in the create() static method.

  public function __construct(array $configuration, $plugin_id, $plugin_definition, array $serializer_formats, LoggerInterface $logger, Request $request) {
    parent:: __construct($configuration, $plugin_id, $plugin_definition,  $serializer_formats, $logger);
    $this->request = $request;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('request_stack')->getCurrentRequest()
    );
  }

In the class methods you then use $this->request to access the request object.


We need to write a hook_form_alter();
In my case ,

function mymodule_form_alter($form,$form_state,$form_id) {
  form['rmr_bar_li'][und][0]['anyfield']['#suffix'] =

;
}

Here anyfield is field inside the field collection below which you have to place your DIV tag.


Unfortunately, it looks like this isn't what Domain Access was intended to do, as its focus is "sharing information across subdomains" rather than restricting it:

https://www.drupal.org/project/domain/issues/480716

In the comments there is a link to a code library that can achieve what you want, however.


Is there a module that can create a Taxonomy out of the installed modules?

I have decided to use a combination of 3 modules to accomplish the task.

Views System, Views Data Export and Taxonomy import/export via XML

Views System is a Views module that lists all the installed modules and themes. Views Data Export enables the output of Views System to be exported as XML or CSV which Taxonomy import/export via XML can then import into a taxonomy.

A module which can update taxonomies from feeds would be nice, there is probably a module for that, but these will do for the time being.


In Views, try this:

add the field as normal, exclude from display
create a new field, Global:Custom Text
add the field name as a Replacement Pattern

It's likely that for security reasons it is psuedo-sanitizing the html. Global: Custom Text should display it as is, but I haven't tried it under these circumstances, so it may not.


If my_type is a content type defined in the Drupal site, then I would check in admin/structure/types/manage/my_type/comment/fields that you didn't delete the comment body.

If this is what happened then the node page changes from what shown in the following first screenshot to what shown in the second screenshot.

The screenshots has been taken using the user #1 for my test site, which means what shown happens to every user.

The same thing should happen when the content type has been deleted, or it has never existed on the Drupal site.

There could be other reasons:

The only input format available in that site is not accessible from the user who is visiting the page your code is outputting. This is not clearly the case if you are using the user #1 to visit the page.
It also means the site doesn't have the default input format, which is not possible to disable from the user interface. It could be the default input format has been deleted from the database; if this is the case, users would have problems also editing nodes, as the input formats used for comments are the same used for nodes, even if a comment for a node using (for example) full HTML could use plain text, or filtered HTML.
The content type has been created programmatically, in a way that didn't cause hook_node_type_insert() to be invoked. If this is the case, then the Comment module doesn't have the possibility of adding the comment body field, which is done using the following function.

function comment_node_type_insert($info) {
  _comment_body_field_create($info);
}


Its in rules

admin > config >  workflow > rules


How to add custom permission for a node?

A possible alternative is to use the Rules module, and create a rule that is a variation of the rule mentioned in my answer to the question aboutr "How to make the permissions of a module more granular?".

The variation in your case will be something like so:

Use the path specific to the node of your case.
Adapt the "Rules Action" to fit your needs.

You may also want to add some "Rules condition(s)" related to the "role" that is required to allow actions like edit, delete, etc. If you have multiple actions like that, you either build one such rule for each action, or you use the Conditional Rules module to make it all fit in a single rule. Obviously, this approach does not "introduce" a new permission that can be assigned by an admin (which is not a requirement either in the original version of this question, right?).


jQuery scripts not working on my Drupal theme

Looks like your classes aren't matching up. I'm guessing that the ideal action you want is when you click on the calendar link, it brings the region-front-calendar up.

The issue looks like your js isn't doing anything to that region, rather it's attempting to pull up a class called "second" which dosn't exist in the html snippet you posted.

If you switch that to the region-front-calander, that might be the answer your looking for.

(function ($) {
  Drupal.behaviors.yourBehaviorName = {
    attach: function (context, settings) {
        $("#block-menu-menu-mobile ul li .nolink").click(function() {
            $('html,body').animate({
                scrollTop: $(".region-front-calander").offset().top},
                'slow');
        });
    }
  };
})(jQuery);


The Pear installation method for Drush was deprecated many years ago; I am not sure how long it has been unavailable, but it will not be coming back. The recommended and supported ways to download Drush are:

Use composer
Clone the git repository, then run composer install
Download the .phar

The Drush Puppet module on drupal.org claims to support git and composer installation mechanisms; perhaps you'd have the best luck if you switched to using that one.


Block view for only the images uploaded to the image field of the current node

Got it figured out. In Views, goto Advanced,Contextual Filters. Select Node ID. Select "Provide default value". Select "Content ID from URL".

To only display this field only using Views, goto Content Type, and under Manage Display, set the both the label and format for the image field to hidden.


How do I create a new admin sub page and how to make it appear in the admin menu?

Easiest way I think of is to create a page display for you view. Set the path to admin/people/mypage and under the menu settings in views choose tab, give your menu item a title and keep the menu setting at Navigation as it defaults to.

Now if you navigate to admin/people you will see a new tab with your page and menu title.

In the views configuration you can add access restriction to your URL / menu item.

If you insist on not creating a page display and instead want to place your block on a page, without coding you own module I would use Panels and Page Manager. You will need the modules Ctools and Panels. Under structure and pages, create a new page and give it your URL, set it to have a menu item (as described in the Views example) and use Panels as variant type. Once your Panel is created you can place your block into any region available in the layout you choose.


Discussion about one user - multiple personas started and ended at drupal.org in 2007. I think your best bet is to use masquerade as a code example and implement it yourself.


Views Get Data from REST API without creating nodes

It is not easy way to show that data with views. You can show them to user without views and without  saving them but when you want use views you  must save them in database or create a custom module to do that. But my suggestion for you is to create a content type then save that data  in node. If you don't need to create a rule that delete them after a specified date, as example delete all data that  older that 3 days ago.


How to show a table depending on a drop down selection?

You can take a look at the #ajax property of the Drupal Form API.

Here is a good start :

$form['blood_group_wrapper']['tables'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
);

$form['blood_group_wrapper']['blood_group'] = array(
  '#type' => 'select',
  '#title' => t('Blood Group'),
  '#options' => array(
      'a+' => 'a +ve',
      'b+' => 'b +ve',
      'ab+' => 'ab +ve',
      'o+' => 'o +ve',
      ),
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => 'ajax_show_table',
    'wrapper' => 'table-wrapper',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

function ajax_show_table($form, $form_state) {
  $table = '

';
  $form['blood_group_wrapper']['tables']['#markup'] = $table;

  return $form['blood_group_wrapper']['tables'];

}


How to get the drupal version using phpMyAdmin query?

This will work with Drupal 7 - I don't have other version to test it on but think it should work...

Because the version is stored in the text file CHANGELOG.txt we can write that to a table in the DB, read from the table, and then delete it again afterwards:

First run this: (make sure to change the path to your changelog file)

CREATE TABLE `drupal_version` (`data`  varchar(255) NULL);
LOAD DATA INFILE '/var/www/your_site/htdocs/CHANGELOG.txt' INTO TABLE drupal_version;
SELECT * FROM drupal_version WHERE data LIKE "%Drupal%" LIMIT 1;

This will return something like:

Drupal 7.26, 2014-01-15

And run this to delete the table we just made:

DROP TABLE drupal_version;

Whilst this is a long winded way of reading text from a text file it is strictly speaking getting the version using MySQL...

Second Option

As Topsitemakers suggested looking in the system table I had a look and found the version was hidden in there, but only against specific modules. I figured the field module would be in all version of drupal, however I very highly doubt that this query will actually work on any version other that 7 as it's so specific and a bit of a beast:

SELECT MID(info, LOCATE(':"', info, LOCATE('"version";', info)) + 2, MID(info, LOCATE('"version";', info) + 12, LOCATE(':"', info, LOCATE('"version";', info)) - LOCATE('"version";', info) - 12))
FROM system WHERE filename LIKE "%/field.module"

For me this query returns:

7.26


How do I add a new condition in Rules 2?

Read Rules 2.x / Drupal 7; I think you can find what you want, there.


obscuring email addresses in user to user email conversation

I think this is perfectly possible, though out of the scope of Drupal to some extent. Drupal can set from and reply_to headers in the mails sent out to, eg "John Doe <abc@mydomain.com>". You'd have to then set up a mail service on the domain which would receive any replies and forward them to the correct users. How you would configure the mail service is a matter for another forum, I think.

(I suggest you edit the original question to make it about obscuring or masking the original email address rather than encrypting it. What you describe is not really encryption.)


I put this in a comment already, but here are some more detailed instructions on how to set up permissions to restrict access to content types.  I assume you are using Drupal 7; if you're still on Drupal 6, the exact sequence of clicks will be different, but the basic approach is the same.

Log in as an administrator.
Click People in the nav bar at the top.
Click the Permissions tab (top right of the People overlay).
Click the Roles sub-tab (immediately below Permissions tab).
Add a new role using the text box at the bottom of the overlay.  For example, "editor".
Click the "Permissions" sub-tab immediately to the left of Roles.
Go down the list of permissions and choose which role can do it.  For example, if you want any authorized user to be able to pose comments, check the "Post comments" check box in the Authenticated User column.  And if you want only editors to be able to post book pages, Check "Post book pages" in the editor column and NOT the Authenticated User column.
Click the "List" tab at the top of the People overlay, next to Permissions.
Find the user accounts of everyone you think should be an editor, and add that role to their account.

If you have a lot of users already, you can add the role en masse by checking the box next to the names you want to grant editorial permission to, and then pick "Add a role to the selected users - editor" from the drop-down box in the Update Options part of the overlay.


Display if and when a particular field exists

Welcome to d7 - just in time as d6 will soon become unsupported.
In D7, content_format is deprecated.

https://www.drupal.org/node/1054586

Check out this for how to render entity fields in d7: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

You'll have to adapt your existing script to this new rendering method. It might be a good opportunity to clean up the presentation and readability of the script so that you'll be prepared for the inevitable migration to d8!


Why am I seeing "Undefined index: und" when I'm using LANGUAGE_NONE?

if(count($node->field_override_ads) && $node->field_override_ads[LANGUAGE_NONE][0]['value'] == 0)

You need to check if a value even exists before checking the value. And I'd actually write it this way:

if(count($node->field_override_ads) && !$node->field_override_ads[LANGUAGE_NONE][0]['value'])


How can I display an image within a node with an SRC value that incorporates a URL taken from another field?

You could use a custom 'screenshot' formatter for the link field. Further info for D6 and D7.


It's actually the other way around; it's the theming of the page template that invokes the theming of the html template (as strange as that might sound).

When Drupal goes to serve a normal HTML page (through drupal_deliver_html_page()), it calls drupal_render_page(). To get the basic render array for the page, that function invokes hook_element_info() with the 'page' argument.

The system_element_info() function defines that type like this:

$types['page'] = array(
  '#show_messages' => TRUE,
  '#theme' => 'page',
  '#theme_wrappers' => array('html'),
);

When the drupal_render_page() function eventually gets around to calling drupal_render() on the $page array (once it's been populated with the page content/blocks/etc), theme_page() is called with the $page element as it's 'render element', and the return from that call is passed to the theme wrapper (theme_html()).

It's that return value that populates the $page variable in html.tpl.php


Custom arrangement for fields with multiple values in Drupal 7

You've got an explanation on how field_view_field and rendering api for fields work in this blog.

Here you've got an example (extracted from the link above):

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

You just need to loop over the $delta value for the fields to render them in a multiple valued field.


Change class on the div wrapper of a form element

You can override theme_form_element() normally if you want to change the theming globally. If you're interested in modifying just one specific form element then I'm aware of a couple of choices.

You can register a new theme function for the particular type of form element you're interested in (eg. textfield). You then create this theme function (based on the original, eg. theme_textfield()) but that doesn't call theme('form_element', ...) at the end (you could either handle both the wrapper and the element in the one theme function, or you could make a separate wrapper theme function and use that). Finally you add a #theme property to a particular form element, and that element will get your custom theming.
You can create a template file called form_element.tpl.php which just has the default behaviour of theme_form_element() and then use hook_preprocess_form_element() to add a template suggestion. Then you create the new template that matches the suggestion. You often hear people mentioning that templates are slightly slower than functions, and for such a frequently used theme call I can imagine people balking at using a template. I've never done any measurements for this myself however. Also, you need to have enough context at the preprocess stage to be able to make the suggestion.


How to add Jquery Validation to Custom form and set error to field?

If the form field is empty you need to stop propagation of the parent form. This should be what you need.

 countryValidation = function() {
    // Lets use a function so we can check the field
    $country = $('#country');
    if ($country.val() === '') {
      return false;
    } else {
      return true;
    }
  }

  $('#user-number-value').on('focus', function(){
    if(countryValidation() === false){
      // If the field check comes back false on focus lets add a class
      $('#country').addClass('invalid');
    };
  });

  $('#country').on('change', function(){
    // This will remove the class when the user fixes the error
    if(countryValidation() === true) {
      $('#country').removeClass('invalid');
    } else {
      $('#country').addClass('invalid');
    }
  });

  $('form').on('submit', function(e) {
    if(countryValidation() === false){
      // when the field comes back invalid lets add the class
      $('#country').addClass('invalid');
      // this will prevent the form from submitting
      e.preventDefault();
    };
  });


Do you use "Content: Has taxonomy term ID" field as contextual filter?

If yes then edit this filter, in "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" section check "Override title" and in appeared textfeild input "Department: %1"

"%1" will be replaced by the name of current term. If no term is specified "%1" will be replaced by "all".

If you want change word "all" then in section "WHEN THE FILTER VALUE IS NOT IN THE URL" click on "Exceptions", check "Override title" and specify your value.


Show terms in view filtered from another view

You don't need two Views Display for that, you can do that one with one Page Display.

Create Views of type Taxonomy term and add Page Display
Add Filter for Food Vocabulary
Add the Parent Relationship. It is called Taxonomy term but look at the Description The parent term of the term. This can produce ....

If you Require it the results will only show terms that have Parent items, so you'll probably want that.
Add Contextual filter Name from the Taxonomy term Category and configure it:
Relationship: Parent
When the filter value is NOT available
Display a summary
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term name
[Food]
Transform dashes in URL to spaces in term name filter values
More
Transform spaces to dashes in URL

You will see a list of your parent items in the results (as a Summary), then when you click on one you will see Views results terms that are its children.


How do I create an ideogram-based 'features' list on nodes?

If you get a Drupal 6 specific answer, that's great, but in the meantime, I would suggest you look at this question. It involves Drupal 7, but the basic principal is the same. If I have had the experience of doing this in D6 I would have added the information to that question, but I have not.


Specific number of values in field setting per role

Sure.  You can manipulate the multiple characteristic of the select via a form_alter() hook.  You just have to make sure the field itself is a multiple value field to start with, and then do something along these lines:

function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if ( /* your user is NOT an admin */ ) {

    if ($form_id == 'YOURNODETYPE_node_form') {

      $form['#field_info']['field_NAMEOFTHEFIELD']['multiple']=FALSE;

    }

  }

  // any other form alters here

}

If this doesn't work out of the box for you, a drupal_set_message() and print_r() of your $form will give you a dump of what you have to work with, and you basically just want to find the multiple array key for the field in question and change it to FALSE for non admins.

But once again, you need to make this field a multiple value field to begin with, but you then don't allow non-admins to enter multiple values into it on the form.

(More information on the Form API can be found here for D7 if this doesn't work as the above is just a quick edit on a D6 testbed here)


adding css in fresh.css nothing change is made

You need to tell your theme to pickup your css file.. You can do that using .info file of theme using below code..

stylesheets[all][] = fresh.css

Clear Drupal Cache to see changes...

For more information refer Writing theme.info files...


Re-submit form after confirmed AJAX form

I found the solution, at least it worked in my case. I want to share if someone need it.

function renderForm($form, $form_state) {
  $form['submit'] = array(
    '#type'  => 'submit',
    '#ajax'  => array(
      'callback' => 'callbackAjax',
    ),
  );
}

function callbackAjax($form, &$form_state) {
  if (empty($form['#skip_validate']) && !$condition) {
    // Show dialog with confirm button
    // If confirmed, doing code in else clause
    $confirm_form = drupal_get_form('renderConfirmForm', $form, $form_state);
    $commands[] = ajax_command_open_dialog($confirm_form);
  }
  else {
    // Save data
  }
  ...
}

function renderConfirmForm($form, &$form_state, $main_form, $main_form_state) {
  $form['continue'] = array(
    ...
    '#ajax'  => array(
      'callback' => 'renderConfirmFormCallback',
    ),
  );
  $form['close'] = ...;
  $main_form['#skip_validate'] = TRUE;
  $form['#main_form'] = $main_form;
  $form['#main_form_state'] = $main_form_state;
  return $form;
}

function renderConfirmFormCallback($form, &$form_state) {
  callbackAjax($form['#main_form'], $form['#main_form_state']);
}


It looks like you were using JS string concatenation syntax in PHP. Try

drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("' . download_list() . '"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}


How does form API work for CCK (and other #after_build processes)?

The form API is usually doing that for you, but it probably does that before calling the after_build functions.

The #after_build functions are called in form_builder(), #disabled handling is in _form_builder_handle_input_element(), which is called earlier in form_builder().


You need to alter the date through template_preprocess_node() and template_preprocess_comment() in your theme. The first preprocess is used for the forum nodes (initial forum post) and the latter for comments (replies).

Add the following code to your theme's template.php file:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}

function YOUR_THEME_preprocess_comment(&$variables) {
  if ($variables['node']->type=='forum') {
    // Custom date.
    $variables['date'] = format_date($variables['node']->created, 'custom', 'M d Y, H:i:s');
    // Use date format provided by Drupal:
    // $variables['date'] = format_date($variables['node']->created, 'short');
  }
}


How to add selective js on the page load?

JS included in your theme's .info file will be loaded on every page, there's no option to make them conditional (that I know of).

If you have files that need to be conditionally loaded you should do so in your theme's template.php file (perhaps in a hook_preprocess_page() function), and use drupal_add_js():

function MYTHEME_preprocess_page(&$vars) {
  if ($some_condition) {
    $path = drupal_get_path('theme', 'MYTHEME') . '/path/to/file.js';
    drupal_add_js($path);
  }
}


Programmatically Setting Content Ranking Factors For Drupal Search

I would do this with a view instead of trying to tweak Drupal's search page:

Create a view
Add the filter "Search: Search Keywords" and expose it
Add two sort criteria: your date field and the "Search: Score" field and expose both of them
In Advanced > Exposed form > settings, check "Allow people to choose the sort order" if you want to give people that option
Add the fields or setup the display as you prefer

You can set the default sort option by ordering the sort criteria and the asc/desc setting by choosing that option for the top criteria. You can also use the Better Exposed Filters module (full disclosure: I'm the maintainer) to combine the sort field and direction into a single dropdown and/or rewrite the text of the options.


Technically you've got two Problems. The first one is namespacing, like Molot pointet out. To use $ for jQuery you need at least to wrap your code into this construct:

(function ($) {
  $('body').fancystuff();
})(jQuery);

That's enough for getting your code executed, for the drupal way you need to attach a behaviour to the Drupal object like the tutorial in Molot's link shows.

The second problem is a missing slash in your drupal_add_js:

drupal_get_path('theme', 'bootstrap') . '/' .'js/product_pages.js'


Drupal 7 - better navigation for Pages in custom menu

This best approach in this regard can be a single multi level menu along with Menu Block module.

Top level menu form main navigation to sections while first level children appear as section items menus. Menu Block configured with 2nd level items chooses second level items siblings of current active item.


Filter is Stripping URL with custom scheme

I wouldn't recommend hacking the HTML filter in core. If you want you could copy/modify it into your own module and create your own filter, here is a link to a blog post that should help get your started.

Or you could try one of the contrib packages like Custom Filter.


Custom language switcher block, returning urls problem

I finally found what the problem was.
This code "$type = $this->getDerivativeId();" was null, and, as a result, this code "$links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));" could not build the following part of the $links array:

"[language] => Drupal\language\Entity\ConfigurableLanguage Object
                    (
                        [id:protected] => en
                        [label:protected] => English
                        [direction:protected] => ltr
                        [weight:protected] => -10
                        [locked:protected] =>
                        [preSaveMultilingual:protected] =>
                        [originalId:protected] => en
                        [status:protected] => 1
                        [uuid:protected] => 6c14f789-dcf3-4149-883f-63c29df3e544
                        [isSyncing:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [isUninstalling:Drupal\Core\Config\Entity\ConfigEntityBase:private] =>
                        [langcode:protected] => en
                        [third_party_settings:protected] => Array
                            (
                            )

                        [_core:protected] => Array
                            (
                                [default_config_hash] => HolYKYAaiuzaHd7bV6FOM0HVbmmEMd3Zq4JAcgW55_4
                            )

                        [trustedData:protected] =>
                        [entityTypeId:protected] => configurable_language
                        [enforceIsNew:protected] =>
                        [typedData:protected] =>
                        [cacheContexts:protected] => Array
                            (
                                [0] => languages:language_interface
                                [1] => url.site
                            )

                        [cacheTags:protected] => Array
                            (
                            )

                        [cacheMaxAge:protected] => -1
                        [_serviceIds:protected] => Array
                            (
                            )

                        [dependencies:protected] => Array
                            (
                            )

                    )"

All the above was missing, so the url could not be properly build.
The solution was to add "Derivative" php file for my class, just like the core language module includes both the "core/modules/language/src/Plugin/Block/LanguageBlock.php" and the "core/modules/language/src/Plugin/Derivative/LanguageBlock.php".
Of course, you have to fix the machine names and namespaces if you do something similar.


You can have another view which selects that image. Then on your existing view you can add a header and choose "Global: View area". Then you just select the view you created earlier and that's it.

Another solution would be to have just another views block displaying that image.

The third solution would be to add an attachment (under Displays click Add > Attachment) instead of a new view block. Choose the fields (image in your case) and attach this (look for ATTACHMENT SETTINGS section) to your existing one.


Simplenews adds newsletters title at the top of the newsletter

Find simplenews-newsletter-body.tpl.php in modules/simplenews/theme folder.
Copy it to your current theme's folder and open/edit it. You'll see that it has a $title variable printed at the top. Comment it out and clear cache to make Drupal see your template change. Test and see the title gone.

REMOVE OR COMMENT THIS LINE =>
<?php print $title; ?>

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


Should the Drupal 8 sites/default/files/config folder be stored in git with its hash suffix?

In the site install process, Drupal will write the configuration directory path to settings.php.
Any other deployments of the site would then make use of the directory defined in settings.php.
The hash itself is not information that needs protection, but it helps make the configuration harder to find in case it were not properly protected from public access.
If you're making your entire configuration public in a repository, it is important to check that it does not contain any compromising information (e.g. API keys).

The configuration should be protected by .htaccess (which core does by default) if it is in a publicly accessible directory, making it impossible to read and not just difficult to find.

It is possible to move the sync directory to another location.
Pantheon places it in sites/default/config, with an .htaccess file to protect it.
Alternately, setting up your repository so that Drupal is not in the root folder (as Acquia does) will allow creating a configuration directory that is outside of the document root.

/
|-- docroot
|    |-- core
|    |-- modules
|    |-- ...
|
+-- config
     +-- sync


Commerce Kickstart 2 - Disable ajax in seach products backend

You can install (if it's not installed yet) Better Exposed Filters. If you edit the View in admin/commerce/products/list (or any of them) and you select BEF for displaying your exposed filters (using defaults) then the autosubmit feature will no longer work.

On the other hand, see https://www.drupal.org/node/1735254 for an explanation on how to disable the autosubmit feature. It's just adding a CSS class to your filter. You have to find out how to add classes to exposed filters in Views, though. Some dirty jQuery can help, I guess.


Insert/create user in database using login form

It is not possible to create a user account in Drupal without writing an email account.

An example of how you can create a user programmatically is:

 $new_user = array(
  'name' => 'name',
  'mail' => 'name@email.com',
  'pass' => 'password', // note: do not md5 the password
  'status' => 1
 );

 //custom fields
 $new_user->field_name_lasname['und'][0]['value'] = 'Name and Last Name';
 //custom fields ( custom fields)
 $new_user->field_referenced_field_['und'][0]['target_id'] = 0;

 user_save(null, $new_user);

Please excuse me my English is not good


How to add a “Last Modified at” field in footer area?

You can add a View in views, create a block display, give it a contextual filter of node id from current URL, then output the Changed field and select a date format. You can change the label to "Last modified on" and you're done. Then just place that block in the right region.

Sorry I don't have code or pics, posted from mobile.

Edit:

You can add a last modified date in the footer area of page.html.twig:

{% if node %}

Last modified at {{ node.changed.value|format_date('custom', 'm/d/Y') }}

{% endif %}

This will work also, first is a no-code solution. Example, perhaps your requirement changes and you need to also show the time next to the date. That is just a simple update to the View, no twig edit + git + deploy + etc needed. Some prefer one way over the other.

Also, and I am going out on a limb here - you should know that node.changed only contains the last modified time on that node. If you changed other things on the page, like menu links in the header, or added new blocks, that date value won't change, because they are not part of the node object being viewed.


Most likely your source plugin isn't supplying the created field to do what is done in the reference article:

source:
  plugin: custom_article
destination:
  plugin: entity:node
  bundle: article
process:
  ...
  created: created

This part of the source plugin config is saying, "import article nodes by setting its created field from the source column created generated by the custom_article plugin".

Adding:

created:
  plugin: default_value
  default_value: 1389312000

Is telling the migration to "set created to 1389312000 as a default (if there's no source plugin data"

If you're copying the reference article's modules/migrate_custom/src/Plugin/migrate/source/Article.php, you'll need to make sure your plugin's query() method is correctly querying its source so that's available for processing and

process:
  ...
  created: created

Is set in your migration config so that it's sourced correctly.


As suggested, Check whether "Database logging" module is enabled in your modules list.


Module that allows to compare, edit and/or merge revisions

I doubt there is an out of the box solution. But maybe you can Views of Pending revision items per content item using Views and if needed the Revisioning module and maybe Rules. Eg, somehow you want to list stuff with pending changes and Revisioning+Rules seems to be able to do that:

  Rules: when Triggers won't do, use the event-condition-action paradigm
  of Rules. More complicated to set up than Trigger, but very powerful.
  Revisioning adds its own events and conditions to Rules, for example
  "content is about to be published" and "content has pending
  revisions".

Then for the view itself you could try to link to a 2nd page that uses the Diff Different module to make the UI per field item you are talking about to move field data around.

I don't see any out of the box solution and you need to build a Workflow of pages/forms/views etc. I'm just trying to help by listing some tools to help achieve that.


Showing only certain product attributed in a view rather than them all in Commerce

I found a solution in the form of a patch here > https://www.drupal.org/node/1696656


html.tpl.php is deleted and the site is down!

Found a solution. An unconventional solution though!

Step I: I moved my custom theme from sites/all/themes/ to one step up (sites/all/). So the system cannot identify the theme in place. I got access into the Drupal.
Step II: I set "Bartik 7.22" as the Default theme.
Step III: Then moved my theme back to its place again.
Step IV: Renamed the file html.tpl.php to html.tpl.php.BACKUP.
Step V: Then reactivated and set default my theme in the Appearance.

It's live!

  Reason: I think it's the Drupal cache. The process I followed was simply tweaking the caching in an alternative, but unconventional way.


I want a Notice message when save configuration

Above mentioned is correct bit more Explanation on that

Syntax : drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE);

Example usage:

drupal_set_message(t('your message to the user.'), 'error');

Parameters

string $message: (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.

string $type: (optional) The message's type. Defaults to 'status'. These values are supported:

**'status'
'warning'
'error'**

bool $repeat: (optional) If this is FALSE and the message is already set, then the message won't be repeated. Defaults to TRUE.
Return value

array|null A multidimensional array with keys corresponding to the set message types. The indexed array values of each contain the set messages for that type. Or, if there are no messages set, the function returns NULL.


How is the module Userpoints Donation intended to work?

The purpose of the Userpoints Donation module is mentioned near the top of the module's source:

  ... uses User Points API to give users ability to give points to users.

But "give" actually means "transfer", as shown in userpoints_donation_giveform_submit(), which:

increments the amount of points for the user who receives the donation (= receiver).
reduces the same amount of points for the user who donates them(= donator).

Before actually doing so, various extra validations are performed, such as:

Does the donator have sufficient points, so that after transferring the points the user points balance of the donator is still positive?).
The receiver has to be a valid user.
You cannot transfer points to yourself.
The amount of points donated cannot be below 1 user point (which also implies that the donator can only "give" points, not "take" points ...).
...

However, for an appropriate link (with title "Donate points to this user") to be shown to the user who wants to do such donation, it is required that such user has been granted the permission "give points to another user". So if "Nothing has changed" (as in your question), it could well be that the required permission has not been granted yet.


How was this amazing drupal performance presentation done?

It's nothing overly complicated; the 3d navigation makes use of the reveal.js library.

  reveal.js is a framework for easily creating beautiful presentations using HTML.

And then there are a few helper libraries:

Highlight.js - for syntax highlighting
classList.js - adds element.classList support to browsers that don't support it
carousel.js - seems to be custom DOM helper functions.

Reveal is pretty easy to use, it just requires a lot of patience and a will to succeed. Good luck!


How to set a placeholder to a form element in a exposed view filter?

You can implement the hook_form_FORM_ID_alter() hook, in the case of the view exposed filter form the name is views_exposed_form

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  //You need to verify the id
  switch ($form['#id']) {
    case 'views-exposed-form-nouvelles-page-1':
      //Setting placeholder
      $form['title']['#attributes']['placeholder'] = $form['#info']['filter-title']['label'];
      //Cleaning the filter labels
      unset($form['#info']['filter-title']['label']);
      break;
  }
}

How you can find the element name? It's easy, you can Inspect your Element:


Can you stop embedded Flickr Images from following their link if the user clicks the image, thus leaving your Drupal website?

For now I have completely disabled Flickr as well as Media_YouTube and Media_SoundCloud in favor of using the Media_Oembed Module. Media_Oembed handles the all of the above Embed needs (and more).  In Media_Oembed, the Flickr Module does not out-link.  Probably a better overall solution in general.

  There are two OEmbeds!! At first, I tried Oembed, which is still in beta (as of 2015-06-03) and I could not get it to work; I don't know what the problem was, but Media_oEmbed seems to work fine.


Multisite: Share users and user roles for existing set up

You don't need additional modules to achieve what you want.

First: Fix you configuration:

'prefix' => array(
'default'   => 'default_db.',
'users'     => 'myhost_users.', //
'sessions'  => 'myhost_users.',
'role'      => 'myhost_users.',
'authmap'   => 'myhost_users.',
),

The dots on the end of 'users' => 'myhost_users.' tells Drupal to query the users table in myhost_users data base (SQL syntax); without dots you'll get an error like "Base table or view not found myhost_usersusers/myhost_users_users or similar.

Now,

'database' => 'db',
'username' => 'db_user',
'password' => 'db_user_pass',

are credentials for the default db where Drupal is installed. To query users db you need to add this user with his password (db_user, db_user_pass) to the myhost_users database. in other words, if you have a site with 2 subsites:

myhost_site1 - user of this db
myhost_site2 - user of this db
myhost_users - (assuming this db stores Drupal users, that you want to share across ites) user of this sb + user of myhost_site1 and user of myhost_site2

To stay logged in on each site it is necessary to share cookies between sites: edit settings.php file of each site, uncomment the line with # $cookie_domain = '.example.com'; and replace '.example.com' with your domain. Don't forget the dot at the beginning ('.mysite.com') -- without it both mysite.com and notmysite.com could be treated as the same domain.


Here is a way to do this:

$create_icon_path = 'my_icon.png'; //my icon path
$create_icon = '<img height=15 src = "/' . $create_icon_path . '">';
$create_earlywarning_url = Url::fromUserInput('/node/5');
$link_render_array = array(
  '#title' => array(
    '#markup' => $create_icon
  ),
  '#type' => 'link',
  '#url' => $create_earlywarning_url,
);
return \Drupal::service('renderer')->renderRoot($link_render_array);

Hope this solves it!


Why is the "My account" link shown even if it is disabled?

This is a known bug and is already discussed a lot:

http://drupal.org/node/1092866

http://drupal.org/node/1197622

Quick fix would be to create a new menu and add that in your template.


Fixed it. I had to work with
['und'][0]['value']['#default_value']

So my new code is:

<?php
    $fieldMap = createFieldMap();
    foreach ($form['registration_information']['register_entities'] as $name => $data) {
        foreach($form['registration_information'][$name] as $subname => $subdata) {
            foreach ($fieldMap as $salesforceKey => $drupalMachine) {
                $form['registration_information'][$name][$subname][$drupalMachine]['und'][0]['value']['#default_value'] = $contact[$salesforceKey];
            }
        }
    }


How to use entity autocomplete for "user" target_type with specific roles?

The selection settings array is passed to the plugin options,
 which in this case is Drupal\user\Plugin\EntityReferenceSelection\UserSelection.

In that class, you can see that the relevant array key is $options['filter']['role'], which is an array.

Therefore, the correct code here is:

$form['user_list'] = [
  '#title' => ('Select User'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#required' => TRUE,
  '#selection_settings' => [
    'include_anonymous' => FALSE,
    'filter' => [
      'role' => ['sales'],
    ],
  ],
];


The correct way to style websites is with CSS.

You can use a selector from the existing Views output, or you can assign a special class to your Content: Title Field under Style settings. You can Create a CSS class for the field wrapper or the HTML element.

Then use the class selector in your CSS inside the theme:

.my-class a {
  color: #cc0000;
}

If you're not creating your own (sub)theme and only want to make minor adjustments you can use the CSS Editor or CSS Injector modules.


How to Delete A Field and Retain Its Value?

I'm not sure this can help you, but one solution that I can suggest is to update your nodes (instead of directly querying the database): transfer one field values to the second one and save it then delete the first one. You can use entity_metadata_wrapper or just functions that are provided by node module.
You can try something like this... Example:

$nodes = node_load_multiple(array(), array('type' => 'MY_CONTENT_TYPE'));
foreach($nodes as $node) {
  $node_wrapper = entity_metadata_wrapper('node', $node);
  $field_code = $node_wrapper->field_code->value();
  $node_wrapper->field_code_file->set($field_code);
  $node_wrapper->save();
}


How to direct authenticated and anonymous users to different ( custom ) front pages?

You can use hook_user_login function to achieve this.

function custom_module_user_login(&$edit, $account){
  if($acount->uid > 0) {
          $redirection = 'myview/'.$acount->uid;
  } else{
      $redirection = 'node/1';
  }

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.

  if (!is_null($redirection) && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
    $GLOBALS['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }

}

For more info check here


How do I get the $language object inside a form builder?

Always use l() (or url(), which justs generates the URL) for generating links; then you, don't have to worry about the current language, base path, whatever clean URLs are enabled or not.

l(t('Back'), 'my/home');

That said, global $language should always work.


FileField Sources module you are looking for, it is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

  Re-use files by an auto-complete textfield
  Attach server-side files uploaded via FTP
  Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only)
  Select existing files through the IMCE file browser


How to set Form API link href to # hashtag

Not sure if this will work, give this a try

'#href' => '&num',  OR  '#href' =>'&#x00023', OR '#href' => '&#35',


How to Override OG Group Owner Permissions for view/edit group content?

Because group owners are considered the equivalent of "Super administrator" (user 1) of their group AND group content, which I happen to totally disagree with, this wound up being solved using hook_node_access() as follows for Question 1:

/**
 * Implements hook_node_access().
 *
 * Runs every time a user tries to edit an endorsement
 */
function icme_admin_node_access($node, $op, $account) {
  if ($node->type == 'endoresment' && $op == 'update') {

    // Does the user explicitly have create/edit endorsement content access?
    // By default, the OG module provides group owners add/edit/delete access
    // to all group content
    $ua_create = user_access('create endoresment content');
    $ua_edit = user_access('edit own endoresment content');
    if (!$ua_create && !$ua_edit) {
      // Show access denied message, and, interestingly enough,
      // also sets the permission for the edit link.
      return NODE_ACCESS_DENY;
    }
  }
}

Question 2 is similar, but just need to change $op == 'update' to $op == 'view'.

I'm curious to see if anyone posts a better solution (other than fixing the OG module).


How to keep domain consistency (with or without www)?

I found the answer. The .htaccess file contains the following comments.

# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www\. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Uncommenting one of those rewriting rules is all you need to do.


Backup and Migrate writing empty files locally

Found out the problem: a file system quota on that particular user on the server. Drush finally gave me this clue when I ran it as the web user:

drush bam-backup files
dm-0: write failed, user block limit reached.
file_put_contents(): Only 0 of 400 bytes written, possibly out of free disk space files.inc:411                         [warning]
Public Files Directory backed up successfully to XYZ-2016-12-27T23-28-18 ( bytes) in destination      [success]
Manual Backups Directory in 12 min 59 sec.
Error while sending QUERY packet. PID=19337 database.inc:2227

Of course there was plenty of disk space, just not available to that user, and I never saw that message when running the command as root. There was enough space available to write the database backups, just not the files directory backup (600MB). Of course, BAM sent me emails saying the backup was successful. I still don't know what the error sending the QUERY packet is about, but the earlier problem of mysql crashing noted did not reappear. Also, I discovered that the web user was not the owner of the module - I forgot to change the ownership after having drush 'update all' earlier (as root); that could have caused the other problems, but the main issue was the disk quota.

In any case, drush bam-backup archive finally worked. Hope this helps someone else in the future.


Changing the HTML produced by Panels: Is it possible?

I've looked into this issue before. Here's the issue you want to read. It seems nuts at first, but there are actually good reasons for it being like this.

Bottom line: think of Panels Flexible Layouts as a prototyping tool. Use it to try out and draft ideas in development, staging, user-testing etc, then when you've got the perfect layout signed off, implement it for production with clean, crisp, hand-optimised HTML as a custom Panels layout (more on those below).

Here's a quick summary of why it is the way it is, based on that issue I linked to:

Panels' HTML output needs all that crazy markup to be able to accommodate the craziest flexible layouts anyone could want to create - think loads of nested fluid and fixed regions side by side.
Nothing automatically generated will be good enough for HTML purists, so the Panels guys haven't tried to keep them happy within the flexible layouts feature. So there's no HTML optimiser algorithm that tries to pare down the HTML generated by your layout to the bare minimum, because no matter how good it was, it still wouldn't be best-standards HTML.
Something they don't mention: if there was such an optimiser, certain changes to the layout would cause now-redundant divs and classes to disappear. If you hung CSS off these, you'd need to re-write your CSS most times you make a small change to a Panels flexible layout. This means that if they tried (and failed) to make Panels Flexible Layouts into a best-standards production tool, they would also have weakened it as a prototyping tool.
You can get clean, lean Panels HTML output. The expected workflow, reading between the lines, is I believe something like this:

You use Panels Flexible Layouts during early development, while trying out ideas.
Once you have settled on a particular layout, if you want clean HTML, you implement it using a custom layout, using only the precise amount of HTML markup that layout needs with just the right classes, semantics etc for your site (how-to below).

While I didn't like it at first, on reflection I think it makes sense. Rather than trying to do the impossible and create one tool that is perfect for both prototyping and for best-standards in a production context - which both have very different needs and could only result in a comprimise that wasn't quite right for either - they've gone with one tool that is ideal for prototyping and another seperate tool (custom layouts) that is ideal for lean production.

This means you can get the best of both, at the cost of a little bit more work implimenting your final layout as a template based on best-standards HTML - but a HTML purist will want to do that little bit of extra work anyway to get their output perfect.

How to create custom panels layouts? There's a detailed guide in the documentation on how to do so. Here's a quick basic summary:

Copy an existing layout from /sites/all/modules/panels/plugins/layouts to become /sites/all/themes/[your_theme_name]/layouts/[new_unique_layout_machine_name]
Rename the files in the new copy to match their new folder name. Note that the .tpl.php file should have hyphens instead of underscores.
Add a line to the theme info file: plugins[panels][layouts] = layouts This tells Panels that you have custom layouts in this theme, and where they are (replace the string layouts if it's not the path from your theme to your custom layouts folder)
Edit the files with your perfect, sleek, minimal, semantic best-standards HTML and CSS.

Don't forget to also update the .inc file with info about your layout like name, categories, filenames, etc.
theme in the .inc file should match the .tpl.php file's filename, without the extension. Any underscores you enter here in the theme value will be converted to hyphens.
Also consider editing the .png icon to better reflect your actual layout.

Clear the cache. Your new layout appears as an option in Panels with the name, category, etc you specified in the .inc file. Use it.


How to filter only first level menu links using views?

I found the answer by adding Filter criteria as given below in views. Please improve this answer if I am not correct.

Parent plugin ID (not_begins menu)


For changing order total, this line

// Replace ORDER TOTAL text as per your requirement.
$components['commerce_price_formatted_amount']['title'] = t('ORDER TOTAL');

should be added inside your above mentioned function. Check if it works.


What are the variables does one search for when trying to render a custom form?

To answer your explicit question (and to reiterate what Clive said), there's no one thing that you could grep to conclude the arguments to change for the getStorage() & create() methods.

The above solution assumes:

You're looking for an entity form.
You're aware that EntityFormBuilderInterface::getForm() needs an entity object.
You can build an entity object with Drupal::entityTypeManager().

It's a specific solution to building entity forms. If you're looking for a method to find any arbitrary constructed form, this solution isn't going to help here.

The most generic thing one could search for to find such a form (an invoke it for rendering), is probably a label that is unique to the custom form, but it really depends on how the form is constructed (e.g. EntityFormBuilderInterface::getForm(), FormBuilderInterface::getForm(), or some arbitrary form array builder function).

If you're familiar with the pattern of construction, there might be some specific terms to search for (e.g. searching for classes implementing FormBuilderInterface or EntityFormBuilderInterface), but there's not going to be one search pattern that works for all forms.


Why doesn't print module_invoke('user', 'block', 'view', 0); use template files?

The code module_invoke('user', 'block', 'view', 0) eventually calls user_block('view', 0). The user_block function returns an array in this case; that's just how hook_block works. The documentation for hook_block says:

  If $op is 'view': return an array which must define a 'subject'
  element (the localized block title) and a 'content' element (the block
  body) defining the block indexed by $delta. If the "content" element
  is empty, no block will be displayed even if "subject" is present.

If you want to know how to render this block, check this comment on the theme_block documentation page.


Consider using the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

By using this module, and to the extend it should be needed, you can then further refine / extend what you get (out-of-the-box) from this module via a custom module(s) and/or view(s).


Use the Form Block module. Enables the presentation of user registration, site wide contact, or node creation forms in blocks.


User profile fields translated but not showing up on user account modification and registration

After you translated the select list options of your (user) field, make sure that you ALSO change the Format of that selection list from Default to Default Tanslated, which you can do via "Manage Display" (located at /admin/config/people/accounts/display). Similar to what is explained in this comment also ...

Note: same is true for using such fields within a content type.