How to show children terms of parent terms in taxonomy?

Here's one way to do this.

Use Panels to override term_view.

Edit the overridden term_view panel.  Add a new variant with the default settings.  In the Content section, add content.  You want a List of related terms, which can be found under Taxonomy term.  You can set this to be the Child terms of the Term being viewed.


How to override VBO redirect after performed action?

I tried to alter the wrong form. VBO somehow merges its form stuff with the views form itself. So I had to look there to attach my custom submit. Then I had to pay attention to attach it in the same moment the views_bulk_operations_form_submit is attached. Then I set the cancel button to also bring me back where I want. And finally set $form_state['redirect'] in my attached submit.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_form_MYVIEW_page') {
    $form['#action'] = '/my/target'; // the url that is displayed when in VBO multistep

    if (!empty($form['actions']['submit']['#submit'])) {

      if (in_array('views_bulk_operations_form_submit', $form['actions']['submit']['#submit'])) {
        $form['actions']['submit']['#submit'][] = 'MYMODULE_vbo_redirect';
        $form['actions']['cancel']['#href'] = 'my/target';
        $form['actions']['cancel']['#options']['path'] = 'my/target';
        dpm($form);
      }
    }
  }
}

function MYMODULE_vbo_redirect($form, &$form_state) {
  $form_state['redirect'] = array('my/target');
}

Only problem left is that this redirect always gets triggered when performing any VBO action from this view. But I can live with that for now.


Duplicates b/c of Node References, Views "Group By" not helping

Well, as it turns out, I avoided this issue by adding another filter, on the 'list' nodes (the children), and I'm lucky that I have one child 'list' node per network that has a unique flag (a 'master' checkbox field that can only be checked on one child per parent 'network' node).

I filtered to only child 'list' nodes that contain that flag, and this means that my parent 'network' nodes only show once.

I still wish I didn't have to do it this way, though. If anyone else can think of a way to actually get a distinct set of nids/titles without my having to use the 'master' flag on the child nodes, I'll definitely mark that answer correct.


How can I track statistics regarding the number of sign-ups vs. account deletions?

Views is your friend. You can build a view that shows the total number of registrations per week, for example. You can use an exposed filter to change the date ranges.

You can use user stats to keep track of last login time and then built a similar view.

If you user userpoints you can get stats based on activity (or the lack thereof).


You can achieve this using Profile 2 and Profile2 Registration Path

As the project page of Profile2 Registration Path mentions

  Profile2 Registration Path enables you to set a unique registration
  path for each Profile2 profile type. Users who register via that
  unique path will be presented with fields from the chosen profile
  type(s).


how to do validation for duplicate primary key in database

What you are doing is:

Show a "select" form element containing a list of nodes whose content type is "product"
Show an error if there is a row in a database about the node the user selected

That is poor UX.
Suppose that there are 20 nodes of that content type, and only two nodes don't have a row in the database table where you save the data; there is a high probability the user gets the error message about the data being already present at least two times. Imagine what would happen when all the nodes have a corresponding row in the other database table.

What you need to do is showing only the nodes for which there isn't a row in the other database table. That means, for example, using a query like the following one.

$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.type = 'product' AND n.nid NOT IN (SELECT s.productid from {formModule_stock} s)");

The module should also show a message in the case all the nodes have a row in the other database table. In this case, the user should not see the form to select a node, rather than seeing a "select" form without any item.

As side note, avoid using upper case letters in the short name of modules. While PHP is case insensitive, you would have problems when you write update functions for your module.


I would create a custom token and use that in my alias. I'm assuming you're using pathauto to create your aliases. This page gives a pretty good example of how to create your own token. Then you can select your token in the pathauto UI.

You can create the hook_tokens_info hook basically exactly as they've done, but replacing the "customs" with your real values. For your hook_tokens implementation, you should have access to the entity in the $data variable i.e., $data['node'] will have your node object if you're using this for nodes. From there you should be able to do something like $data['node']->field_your_list_field->getValue() to get the value of your field. Just be sure to return a $replacements array where the key is your custom_token and the value is the value to replace with, in your case this would be something like you-selected-value-X.


How to print "node title" in comment.html.twig template?

Because the comment reply page/route does not belong to a Node entity
$node = \Drupal::request()->attributes->get('node');

returns null.
Instead, access the node object with
$node = $variables['commented_entity'];


Best way to define entity and additional custom logic (CRUD) in module

Given that you want to change the formatting of a file field, then I would create a FieldFormatter plugin, which could probably extend FileFormatterBase (or one of its sub classes). This would allow the formatter to be a configurable option for file fields in the Manage Display interface (or as part of a content type configuration YAML that your module provides).

By implementing FormatterInterface::viewElements, you can add to the render array that is returned.

To summarize:

Create a field formatter plugin for file fields in a custom module: drupal generate:plugin:fieldformatter --field-type=file
Create a content type: drupal generate:entity:bundle --bundle-name=company --bundle-title=Company
Add a multiple-value file field to the content type.
Configure the file field to be displayed with your custom field formatter plugin (in Manage Display).

Edit: Added drupal console commands as far as I know them


Robots.txt will not help your site being crawled (technically) by anything. They're just guidelines which Bots should follow. You should limit dev and test server access by Firewall rules, or as you've mentioned by httpauth.


Do i need write access to the files directory to migrate d7_file?

Ok, i figured this one out.  The magic lines are in /core/modules/migrate/src/Plugin/migrate/process/FileCopy.php
First, make sure source_base_path is correct in your config: Check drush mmsg d7_file after migrate-upgrade d7_node --limit=1 to see whether it is correctly finding the files.  Use drush config:export and config:import to modify it til that works.  Alter settings.php to put config/sync somewhere other than /sites/default/files
Second, mount the live site's public files dir read-only at /sites/default/files.
Third, modify /core/modules/migrate/src/Plugin/migrate/process/FileCopy.php around line 149 to comment out the action.  Make it look like this:
    if (!is_dir($dir) || !is_writable($dir)) {
      if (!$this->fileSystem->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
        throw new MigrateException("Could not create or write to directory '$dir'");
      }
    }

    $final_destination = $this->writeFile($source, $destination, $this->configuration['file_exists']);
    if ($final_destination) {
      return $final_destination;
    }
*/
      return $destination;```

Last, run drush migrate-upgrade d7_file

Enjoy.


How to call default node validation functions

If your form has a structure similar to the one used for the node edit form, then you can use node_validate(), which is called from the form validation handler for the node edit form.

function node_form_validate($form, &$form_state) {
  node_validate($form_state['values'], $form);
}

node_validate() converts the first argument in an object using the following code.

  // Convert the node to an object, if necessary.
  $node = (object) $node;
  $type = node_get_types('type', $node);

Your form validation handler's code should be similar to the following one.

function mymodule_form_validate($form, &$form_state) {
  // Run your validation code.
  node_validate($form_state['values'], $form);
}

As general rule, the validation code should go in the form validation handler. If the form validation handler set any error, the form submission handler is not called, and the user is returned to the form to correct what is wrong in the data that has been submitted.


There is a Date filter inside views that can be set and customized easily to satisfy your needs. You need to enable the Date module first. Here:

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

If you find implementation using Date module difficult, you can achieve the same result using the straight forward Views between dates filter module:

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


Try the  Commerce Order Reminder. It can help you!!

  As the name implies, this light weighted module sends email reminders to website users of the orders that were left uncompleted. The reminders will only be sent about those orders that have the email property filled. This includes even those orders of anonymous users that entered their email in the billing information form but did not complete the checkout process.


Compress Images that are already uploaded

A module like Max Image Size will resize the original images that have already been uploaded, but I don't believe it is possible to also use an optimization on the images when they are resized.  You can only specify a new maximum width and height.


Display a taxonomy term every number of rows

I think you must alter the view.

Create the views normally, add taxo to every rows.
Use the Hook hook_views_pre_render(&$view)
Delete the term for every rows except 1/3.

For example something like this:

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_myviewname') {
    $result = $view->result;
    $count = 0;
    foreach ($result as $i => $row) {
      if(!$count % 3){
        unset($view->result[$i]->field_MYTEXONOMYFIELD[0]);
      }
      $count++;
    }
  }
}

Example from : http://www.drupal8.ovh/en/tutoriels/238/alter-a-view-edit-view-result-programmatically


how do i use subquery in db_api condition?

If I understand you properly you need to use a standard where clause rather than a condition in your sub query, e.g.

$subquery = db_select('some_table_2');
$subquery->where('some_table_1.id = some_table_2.id');

...

$query->condition('some_table_1.something', $subquery);


Is it possible to have common content for several users?

Have a look at the Group module (commonly perceived as an alternative for Organic Groups).

Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable. Which also makes it integrate very well (out of the box) with commonly used modules such as Rules, Views, etc.

Some more questions you may want to look at for more details:

What are the various roles supported by the Group module?, which explains the various types of roles that can be used.
What are the features of the Group module versus Organic Group module?

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


drupal 7 wildcard and parameter replacement?

There seems to be some disparity in your naming conventions here. Your functions should be named with MODULENAME_ as a prefix, including all hooks that you implement.

For example, if your module is called 'sample' then as well as the folder the module files are in being called 'sample', your files will need to be named similarly (sample.info, sample.module, etc.). If you don't follow this convention your hooks won't be called; and it's just good practice to prefix your module's functions with the module name.

The other thing here is that you don't actually need to use your own router load function...the node module has already done it for you (with the node_load() function). You can simply re-use that:

function sample_menu() {
  $items['node/%node/images'] = array(
    'title' => 'Images',
    'weight' => -10,
    'page callback' => 'sample_show_tab_page',
    'page arguments' => array(1, 'images'),
    'access callback' => TRUE
  );
  return $items;
}

You should be aware that node_load() returns a node object, so the first parameter to your page callback function will be that object. The second will be the string 'images', as per the arguments you've provided in page arguments.

Your page callback (which I've renamed :P) would then look more like this:

function sample_show_tab_page($node, $arg1) {
  // Use whatever you need from the node object
  $nid = $node->nid;
  $title = $node->title;
  // etc...
}

Finally, and perhaps most importantly to commit to memory, make sure you clear Drupal's caches once you've added/edited any hook. Such implementations are cached, and the system won't pick up these changes until you tell it to.


Optionally add image/icon after node title based on boolean content type field?

While this can be on in the page preprocess, and the node template, and probably several other places as well, I would discourage that. It is putting to much logic in the theme, that doesn't belong there. The main advantage of my solution is that the field can look right regardless of where you display it. On a page, in a block, in the header, or essentially anywhere that properly integrates with the Field API.

My solution is as follows

Add a text field, with the boolean Yes/No options

Implement two hooks, hook_field_formatter_info() and hook_field_formatter_view()

function product_field_formatter_info() {
  return array(
    'product_star' => array(
    'label' => t('Recommended product'),
    'field types' => array('text'),
  );
}

function project_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  if ($field['type'] == 'text' && $display['type'] == 'product_star') {
    return array(0 => array('#markup' => '<img src="star.png">'));
  }
}

Clear the cache

Go to the fields display settings, and set it to "Recommended product"

Profit!


form_set_error highlight offending field?

Don't put the [value] inside, it should work with only

form_set_error('field_reviewer_terms_of_service', t('You must agree to the Terms of Service.'));

See the documentation for form_set_error().
You may have to use some [value inside your field if it is multivalued, see this comment but we need to see the HTML ouput for your field.


Entity reference value from url in node add form block

Node Reference URL Widget can help you :)


Delete node: Remove header, footer and rightbar in delete node page

Please follow suggestion from this link for page https://www.drupal.org/docs/7/theming/template-theme-hook-suggestions

If you have created a page using views then you can call template for views like (page--viewname.tpl.php).

if you go with the content node, You need to call template like (page--node--nodeid.tpl.php)


Although there's actually no question, I've noted the last part of your code should look like:

<?php

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $rows,
);

return $form;


How do you link a view into a listing dropdown menu?

I'm not reputable enough to comment so I can only post here as an "answer".  But instead of telling you "how", I'm telling you that it appears you can't do this, not easily anyway.

It looks like the options you have available in the node edit form:

are provided by these field settings:

That screenshot of your field settings shows an error:
There is data for this field in the database.  The field settings can no longer be changed. which means you can't add a new value (a view in this case) to those particular settings.

That means you can't do this.  Everytime you click the save button it fails to actually save and displays that error message.

There are some options:

Edit the database directly -- it's dangerous, don't do it on your live site, only do it on a copy/clone of your site until you're sure it works without breaking things horribly, and you probably shouldn't try this at all.
Create a new field with the settings you want.  Then migrate all the data from the old field to the new field.  Delete the old field once the new one is in use and working.  This also should be tested safely on a breakable copy of your site.

Based on what you've shown in your screenshots, those are two possible solutions and neither of them are very good (the second one is better).

It's possible that there actually is a good solution for you, but you really need to provide more information like like @Christia said.  For example, going on your screenshots alone I don't see how this has anything to do with nodqueue or field_collection modules.  This "Listings" functionality in the vertical tabs is mysterious, does it use dgo.to/viewfield or dgo.to/viewreference or some other module?


The problem lies with your contextual filter. It is set to filter the uid of flag user. This means it will limit the selection to only flags made by the current user (who did not flag himself, thus the user's own content is not selected).

You can probably solve this by having each user flag himself (automatically), but that is kinda ugly.

The alternative would be to use two regular filters and an OR group (remove the contextual filter). You might have to add some additional relationships if below steps do not work, but we basically want to have relations from the content to the user (author) and from the flag to the user (I believe you added that one already).

Add the filter user: current and select yes twice! For the first dialog, make sure you select the author relationship from content to user. For the second dialog use the flag to user relationship.

Finally, from the dropdown button above the filters section, select And/Or Rearrange and Create two groups with Or between them:

Now make sure to place one of the filters in each group.

This should show all content where the author is the current user, or content where the author has been flagged by the current user.


I had an issue like you did and i solve it by changing my:
track_changes: true

on
  high_water_property:
    name: changed
    alias: n

But the problem with this way that you need to:

Manually delete, NOT update your database destination fields.
Import old data.(Before check your source plugin, it must have changed field!)
Update your database with new data.

(and only than high_water_property will work)

About this two Source Plugins
Declaring highwater property in Migrate
About track_changes


hook_form_alter function does not call the validate function?

as your validating just one field - at least, it seems like it; consider using:

function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['your_desired_field']['#element_validate']  = array('uniquefield_validate');
  }
}

on the fileds in your alter hook


"Class not found" error when attempting to access inbuilt DateTime class

You're just running into namespace problems. DateTimeZone is in the root namespace, so refer to it as:

\DateTimeZone

Same for

\DateTime


Add Emoticon at my Simplenews Newsletter's subject

If you're talking text-based emoticon (e.g. ":)", ":D") then the answer is yes. If you're talking Unicode emoji-character based emoticons (e.g. ) then the answer is maybe. While Drupal sends out UTF-8 encoded emails, support for display of the emoticons depends totally on recepient's email client so your results will vary.


Given you didn't install any contrib modules nor themes, dozens of Drupal core modules requires Jquery to function. You'll have to check what modules lists JQuery as a dependency.
Search in core/modules and core/themes directories for core/jquery and you'll find out what module/theme is adding it and disable it.

For example "contextual" module needs it.


Add this snippet to your query item:

$query->condition(X, Y, 'NOT LIKE');

where X and Y are two variables. You can also replace each of them with constants.


Problem creating a node with custom PHP code

It looks from your image like field_cmp_playerid is a user reference field, which means the column name won't be value, it will be uid. Try this code:

$node->field_cmp_playerid[LANGUAGE_NONE][0]['uid'] = $user->uid;

The field_cmp_attend_time field probably isn't getting saved because it's missing from your code. It's just a date field so the column name will be value. If the date field you're using is a UNIX timestamp type, for example, the code would look like this:

$node-> field_cmp_playerid[LANGUAGE_NONE][0]['value'] = REQUEST_TIME;

Just in case you want to update your field_cmp_id as well, it's a node reference so the column name becomes nid:

$node->field_cmp_id[LANGUAGE_NONE][0]['nid'] = $nid;


For removing the link all you have to do is click on REWRITE RESULTS
Then click on "Rewrite the output of this field"
and then check "Strip HTML tags" That should remove the link.

The easiest way to achieve the other one is a bit of a hackish solution. You need can go to webfor/views folder and look for the file webform_handler_field_submission_count.inc

with in that file check for the render function.

  function render($values) {
    global $user;

    $output = NULL;
    if ($this->count_type == 'node' && in_array($values->{$this->aliases['type']}, webform_variable_get('webform_node_types'))) {
      module_load_include('inc', 'webform', 'includes/webform.submissions');
      $node = node_load($values->{$this->aliases['nid']});
      //if (webform_results_access($node, $user)) {
        $count = webform_get_submission_count($node->nid);
        $output = l($count, "node/$node->nid/webform-results");
      /*}
      else {
        $count = webform_get_submission_count($node->nid, $user->uid);
        $output = l($count, "node/$node->nid/submissions");
      }*/
    }
    elseif ($this->count_type == 'users') {
      $output = db_select('webform_submissions')
        ->condition('uid', $values->{$this->aliases['uid']})
        ->countQuery->execute()->fetchField();
    }

    return $output;
  }

In this above code I have commented a section. You can do the same it should work now for anonymous user. As I said this is a hackish solution and wont advice to do the same. The cleaner method would be to create a custom module and add the handler you want in the custom module and use that instead.


If I need to display webform in popup, then I would use ctools modal.

You can use modal forms module which make use of the modal feature in the ctools module to open some common forms in a modal window.

Supported forms

Log in (modal_forms/nojs/login)
Request new password (modal_forms/nojs/password)
Create new account (modal_forms/nojs/register)
Contact (modal_forms/nojs/contact)
Comment (modal_forms/nojs/comment/reply/%node)
Webform (modal_forms/nojs/webform/%node)

May be this is not answer to your question as you are using colorbox, but I am adding this so that you can check other option.


How do I disable the "Group activity" tab on the organic groups page

The Tab tamer module is a quick and easy way to hide or disable extra tabs.


This is hard to answer, because it depends very much on how your menu is designed and which navigation method you're going to use.

There's a sandbox project for the omega theme though.

Maybe this will help as well: Complex Navigation Patterns for Responsive Design


How can I change the css classes on a menu's ul when it is placed in a particular region?

You don't need to change or add new classes because each region has already a class. You need to specifically reference each menu class () in your stylesheet by adding first your region class name:

#region-menu ul.menu li {display: inline...}

#region-sidebar-first ul.menu li {display: block...}

etc...

so check you won't interfere.

Make sure the main menu has a unique reference as #region-menu to avoid inheritance.


Content profile fields not showing up on user registration page

Can you see the fields when you create a user as admin (admin/user/user/create)? If so, this means that permissions are not properly assigned to authenticated users to create those fields. So you need to go to permissions page and edit permissions to each new field that you have created on profile node type.


You can draw some clues from this question: Views contextual filters for NULL value You should use Computed field or some other way of introducing custom PHP into your Views (custom module is the best option).

If you use more than one Contextual and need to have the OR operator between them you can use the Views Contextual Filters OR module.

There is also a patch for the D7 version you can expand on: Add an "OR IS NULL" option to contextual filters.

But since you're using two vocabularies and need to maintain the AND between the two contextuals you won't be able to use the "OR" module and you'll have to come up with a custom code solution for the second contextual that takes care of the both "there is specific term" and "there are no terms" in one contextual filter, so you can combine it with the contextual for the Vocabulary 1.


User_save is very slow for no apparent reason

I found the answer, well the reason. I had a in a module
hook_user_update()

that has a CURL that connects to remote site and beacuse of it took much time to save, well to connect and then to save.  Need a way to make this CURL connection not affect the user save.


Eureka!

So, I still am not sure what the issue was 100% but I am guessing that there was a name collision with multiple different forms and since Drupal uses name "op" for every submit button since the dark ages of the internet I guess the ajax was trying to get itself applied to the other form that had submit button as well(named op as well) but that did not work of course so that resulted in this weird behavior.

So the way I have fixed this was by setting the #name AND #id attributes on the submit button in my form. I have set the #id which I normally don't do in ajax forms because I would get wrong drupalSettings.ajax entry.

I didn't do this in the first place because the form was working just fine for logged-in users + just fine for anonymous users on entity listings so it didn't made any sense but hey, the more you know.


Update multiple rows (with different ids and different values) using one query

You can use below example to update:

    $items = array(1,2);
    db_update('your_table')->fields(array(
      'update_field_one' => $to_update_one,
      'update_field_two' => $to_update_two,
      'updated' => REQUEST_TIME,
    ))->condition('id', $items, 'IN')->execute();


How should I store a static key pairs list?

Regarding Using variable_get and variable_set

I would suggest storing them in variables tables using variable_set in serailized format.. Store your 200 pairs data in an array using variable_get function...

Variables are cached in cache_bootstrap table so that performance will be improved.

Regarding Custom Table

You will lose the cache ability and managing the rows like edit/insert will be a pain since you need to build logic to retrieve and update results.

Regarding Cache Table

It will be a temporary storage. If some one clears all cache you will lose the data.

Regarding Constant in Code

Yes.. You can use constants too..  I am not sure performance impact vs using variables.

Regarding Hardcoded in code

I believe it's same as using constants. But, If you are trying to hardcode everywhere then you will end up with redundant code which will result in update - data consistency problem.

If you think in Drupal way i will say variables is the way to go using variable_get and variable_set..


After wasting a few hours I resolve it with adding driver property to $databases in settings.php .

$databases['default']['default'] = array (
  'database' => 'XXX',
  'username' => 'XXXX',
  'password' => 'XXX',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '33067',
  'driver' => 'mysql',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
);

I hope this could save another guys time in future in the same problem.


Perform action once a form has been validated

You should add a submit callback instead of a validation callback. Submit callbacks are called after the form has been validated.

function yourmodule_form_FORM_ID_alter(&$form, &$form_state) {
  $form['#submit'][] = 'yourmodule_custom_submit_callback';
}

function yourmodule_custom_submit_callback($form, &$form_state) {
  // Execute here your code
}


Can I use Drupal plugin in managing news?

Yes you can use Twitter Feed! with Views & OAuth modules and you have to enable OAuth based access for Twitter, you must register your application with Twitter and add the provided in Twitter setting!


How can I create a Views list of all users with either a node OR a comment?

As far as I know you can't create Views for more than one entity type. You would have to create separate Views, one for nodes and one for comments; you CAN however make them appear in the same page by using Views Field View. You can sort each view by author, and get rid of duplicates by using the Aggregation option.

EDIT:
There IS a way to do two EntityFieldQuery (one for node and one for comment) and then create a single array of authors. Something like this:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node');
$node_list = $query->execute();

$query2 = new EntityFieldQuery();
$query2->entityCondition('entity_type', 'comment');
$comment_list = $query2->execute();

$author_ids = Array();

$nodes = node_load_multiple(array_keys($node_list['node']));
foreach ($nodes as $node) {
  $author_ids[] = $node->uid;
}

$comments = comment_load_multiple(array_keys($comment_list['comment']));
foreach ($comments as $comment) {
  $author_ids[] = $comment->uid;
}

$author_ids = array_unique($author_ids);
dpm($author_ids);

You can then do whatever you want with the list of uid's - for example load  the users and create a table programmatically for display.


How to rewrite the out put of field in view

I think in your view's Configure field section of Content: Title you already checked the following option.

Link this field to the original piece of content

If this option is checked then mostly your rewrite the output won't work. Please check that.

Hope this will help you..


Webform tokens - token to return the 'option value' not 'option text'

You need to suffix your token with :raw.

@see https://www.drupal.org/project/webform/issues/2990260


Trying to access modules page callback while authenticated

Make sure you define your new permission using Drupal 7's hook_permission().
Grant your new permission to authenticated user here: /admin/people/permissions/list

Try this:

function mymodule_permission() {
  return array(
    'access mymodule homepage' => array(
      'title' => t('Access My Module homepage'),
      'description' => t('View My Module homepage.'),
    )
  );
}


During which bootstrap phase hook_exit & hook_boot will be invoked?

hook_boot is getting invoked during fifth phase which is DRUPAL_BOOTSTRAP_PAGE_HEADER which set up the page header... This is for non cached pages..

/**
 * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
 */
function _drupal_bootstrap_page_header() {
  bootstrap_invoke_all('boot');

  if (!drupal_is_cli()) {
    ob_start();
    drupal_page_header();
  }
}

For Cached pages both gets executed at Second Phase of Bootstrap which is DRUPAL_BOOTSTRAP_PAGE_CACHE with little difference...

  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_boot.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

what make difference between these hooks is

  drupal_serve_page_from_cache($cache);

Which tells hook_boot and hook_exit is used before and after page requests for tasks like setup and cleanup respectively..

hook_exit also called in common.inc what makes difference is,  Invoke during DRUPAL_BOOTSTRAP_PAGE_CACHE phase applies where cached page requests are served..  In common.inc hook_exit is called for non cached pages..

function drupal_page_footer() {
  global $user;

  module_invoke_all('exit');

  // Commit the user session, if needed.
  drupal_session_commit();

  if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
    drupal_serve_page_from_cache($cache);
  }
  else {
    ob_flush();
  }

  _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
  drupal_cache_system_paths();
  module_implements_write_cache();
  system_run_automated_cron();
}

Above confirms even for non cached requests hook_exit is invoked..


Pinterest-style image presentation page?

For that, you need to use Masonry jQuery plugin. With Drupal you've this module but it's not available yet for Drupal 7.x, so you should either make your own template with the plugin or try to port the mentioned module into Drupal 7.


Problem in dependency injection in drupal custom module service

From the looks of the core middleware services, the HTTP kernel is automatically provided to the constructor. You don't have to specify it (and even if you did, @kernel is Drupal's kernel, so might not be what you meant).

As an example, ReverseProxyMiddleware's constructor signature:

public function __construct(HttpKernelInterface $http_kernel, Settings $settings) {

And its services entry:

http_middleware.reverse_proxy:
  class: Drupal\Core\StackMiddleware\ReverseProxyMiddleware
  arguments: ['@settings']
  tags:
    - { name: http_middleware, priority: 300 }

Note no explicit @kernel, yet it's the first constructor argument.

So in theory you just need to change you service definition and clear caches:

class: Drupal\mkt_tracking_v2\Middleware\TrackingMiddleware
  arguments: ['@config.factory','@request_stack']
  tags:
    - {name: http_middleware, priority: 1000}


You can add class for the row and add background for this class via the css

$row = array(
  array(
    'data' => array(
      array( 'data' => 'cell1'),
      array( 'data' => 'cell2'),
      array( 'data' => 'cell3' ),
    ),
    'class' => array('my-class'),
  )
);

print theme('table', array('rows' => $row));


FAPI text_format field value not being passed to submit handler

Just remove the #value:

$form['description'] = array(
  '#type' => 'text_format',
  '#title' => 'description',
  '#default_value' => '
The quick brown fox jumped over the lazy dog.
',
  '#format' => 'full_html',
);

#value permeates all the way through a form build/validation/submission, and doesn't get replaced with user input.

#default_value will cover the initial value when the form loads.


Does Drupal 8 entities have any events I can listen to?

You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity.

Here is the order of hooks and other events that happen during an entity save:

Entity::preSave() is called on entity objects, and FieldItemListInterface::preSave() on field objects.
hook_ENTITY_TYPE_presave()
hook_entity_presave()
Entity is saved to storage.
Entity::postSave() is called on the entity object.
hook_ENTITY_TYPE_insert() (new) or hook_ENTITY_TYPE_update() (update)
hook_entity_insert() (new) or hook_entity_update() (update)


MenuTreeParameters::$expandedParents are a list of menu tree ids (a composite key of the menu bundle and the menu content UUID). You can see its data in the menu_tree, menu_link_content, menu_link_content_data, database tables.

If you need to programmatically invoke the menu item for reference, you can load it via Drupal's entity manager:

// Load each menu content item per UUID
foreach ($parents as $menu_uuid) {
  $menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $menu_uuid)));
  // @TODO: Reference menu content properties for data
  // (e.g. $menu_content->get('title')->value / $menu_content->get('link')
}


How to speed up performance of taxonomy hierarchical select drupal

Using High-performance JavaScript callback handler will speed up it a bit while i recommend using Simple hierarchical select rather than Hierarchical Select , cause it is much faster in queries (off course less user friendly) .

this is the description High-performance JavaScript callback handler :

  JavaScript callback handler is an interim solution for high-performance server requests including (but not limited to) AHAH, AJAX, JSON, XML, etc.
  This project targets module developers and provides a "bare bone" callback handler which is intended to be addressed by modules wanting to improve response times for specialized tasks.


With Webform you can pre-populate form default values via the url with tokens:

Setting Default Values from the URL (7.x-3 and earlier)

The %get[key] supported by Webform allows form values to be populated from the URL.

Setting Default Values from the URL (7.x-4)

To set the default values of a component to use either:

Query Format: For urls formatted like http://example.com/node/120?key=bar use [current-page:query:key] to return key value.,

Args Format: For urls formatted like http://example.com/node/120/key use [current-page:url:args:2] to return key.

Taken verbatim from webform docs


Permission Conflict - Commerce Order - Please give me a guidance

You would need to produce a custom permission using hook_permission that grants permission for sellers to see orders of their customers.


It's perhaps not that obvious but all you need to do is empty the text field containing the value you want to remove. Once you save the entity the value will be gone.

Files need a remove button as there's no other way to 'empty' that particular field (a round-trip to the server is required to purge the file that was temporarily uploaded). Other, less complex fields (like text fields), don't need to contact the server via Ajax to do that, so I guess the remove button is deemed unnecessary.

If you're interested in the mechanics of this, have a look at the hook_field_is_empty function, which all field modules are required to implement.


How to translate a menu item in Main Menu with a path to a page View

I was a problem related to Superfish module which I'm using to generate the main menu. Here is the patch for the superfish module patch


I recommend you use Aquia Dev Desktop, easier to use than Xamp, one click install.

https://dev.acquia.com/sites/default/files/downloads/dev-desktop/AcquiaDevDesktop-2-2016-09-05.exe

Just use that, and it will all work 100% the first time.

Something else you might need to do with Xamp is adjust timeouts ect...with Aquia dev desktop the settings are usually already adapted to Drupal requirements.


What is the performance impact of modules that use Field API instead of a custom way of accessing the database?

That can't be answered in a generic way, I think. Some facts:

Each field does add a certain overhead to the system and it means more queries when loading and saving e.g. nodes.
Being able to store information as a separate entity that has the information as properties is obviously much faster than having everything in fields.
However, modules that stores additional information to entities on it's own tables results in additional queries as well.
The advantage of field API is that the storage is pluggable, so you could for example use it together with MongoDB which could possibly drastically improve the performance, with some drawbacks however.
Fields also have read cache built-in so that subsequent entity loads will use the cache to load the field content. A module that does not use fields might not have it's own custom caching.
There is still the generic overhead added by fields but work is ongoing to improve that situation in Drupal 8 and it might possibly be backported as well.

So a module isn't more performant just because it uses fields for storing data or not, there are many more factors and it also depends on how the site is configured.


Why could Drush not find the alias @local?

You are missing the <?php at the beginning of your aliases file. That's why the contents of your file are printing out when Drush tries to load them.


How to remove a line of HTML in webform?

You need to add to your css file this style:

div.field-widget-file-generic p.help-block{
    display: none;
}


Are there JavaScript events sent by Webform Conditionals?

The Webform module for Drupal 8 is using Drupal's States API, which triggers custom events that are prefixed with 'state:*'.

Events include...

state:disabled
state:required
state:visible
state:checked
state:collapsed


function mytheme_menu_tree__menu_mymenu($variables) {
  return '
' . $variables['tree'] . '
';
}

function mytheme_menu_tree__menu_mymenu_second($variables) {
  return '
' . $variables['tree'] . '
';
}

function mytheme_menu_link__menu_mymenu($variables) {
  $element = $variables['element'];

  $submenu = '';
  if ($element['#below']) {
    // You can set a theme wrapper here or put an empty array() only
    // and theme the second level directly by adding

 one line below.
    $element['#below']['#theme_wrappers'] = array('menu_tree__menu_mymenu_second');
    $submenu = drupal_render($element['#below']);
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $submenu . "
\n";
}


If you want unpublish all nodes, quick and dirty method is simple sql query UPDATE node SET status = 0; Then clear cache and its done. But if you use Views, they could still show unpublish content depends on settings.


Filters as rewrite results link path parameters

If the entity title of the row is a field on the view you can use the Override the output of this field as a custom link option and then create a link yourself using replacement patterns. So long as the field you are referencing the entity title of is beneath the field you are referencing in the field list.


Yes, implementing comet/long polling in Drupal is a bad idea.

There already is a node.js project that you could use: Drupal node.js integration.

The design principle of that module is that node.js does not contain any logic (to avoid duplication of logic in PHP and JS) but is only reponsible for keeping a connection open to your users. You then send notifications to node.js in the usual hooks (like hook_node_save()) which forwards it to your users.


How to do a hard redirect when in Ajaxified form?

In my case (D8), I just had to implement the RedirectCommand in my AjaxSubmit :

Code of the submit button :

$form['submit_' . $this->uniqueIdentifier] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => [
    'class' => ['btn', 'btn-primary']
  ],
  '#ajax' => [
    'callback' => [$this, 'submitModalFormAjax'],
    'event' => 'click',
  ],
];

Code of the submit callback:

public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  if ($form_state->hasAnyErrors()) {
    // Do validation stuff here
    // ex: $response->addCommand(new ReplaceCommand... on error fields
  }

  else {
    // Do submit stuff here

    $url = Url::fromRoute('page_route');
    $command = new RedirectCommand($url->toString());
    $response->addCommand($command);
  }

  return $response;
}

Do not forget to declare :

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Url;


Assign menu programmatically upon saving node

Please try this

/**
 * Implements hook_node_insert().
 */
function YOUR_MODUEL_node_insert($node){
  create_node_menu($node, 'insert');
}

/**
 * Implements hook_node_update().
 */
function YOUR_MODUEL_node_update($node){
  create_node_menu($node, 'update');
}

function create_node_menu($node, $action_type){
  if($node->type == 'YOUR_NODE_TYPE'){
    $category = $node->field_category[LANGUAGE_NONE][0]['value'];
    $menu_name = '';
    switch($category){
      case "A":
        $menu_name = 'menu-menu-a';
        break;
      case "B":
        $menu_name = 'menu-menu-b';
        break;
      case "C":
        $menu_name = 'menu-menu-c';
        break;
    }
    if(!empty($menu_name)){
      $item = array(
        'menu_name' => $menu_name,
        'link_title' => $node->title,
        'link_path' => 'node/'. $node->nid,
      );
// update already created menu link
      if($action_type == 'update'){
        $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path', 'node/'.$node->nid)
            ->condition('ml.menu_name', $menu_name)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();
        $item['mlid'] = $mlid;
      }
      $mlid = menu_link_save($item);
      menu_cache_clear_all();
    }
  }
}

Hope this will help.


CKEditor set its own CSS classes for text areas, but that would not explain why copying the CSS files from a theme to another doesn't change the visualized styles.

The problem here is that simply changing the files used by a theme doesn't change the used styles; you need to let Drupal know the theme has been changed, and this can be done in two ways:

you select a different theme as default one, disable the theme you modified, re-enable it, and select it again as default theme
you force Drupal to refresh the cache it is using, or you empty the cache tables

In the first case, you submit the theme selection form after each operations.


How To Create 'Node 1 vs Node 2' 'Node 1 vs Node 3' nodes etc as quickly as possible to compare their fields?

You could achieve this quite easily with a custom module. In this example I'll use Drupal console to simplify settings every thing up.

Create a module:

drupal generate:module

Call it whatever you want.

Create a controller:

drupal generate:controller

Sample answers for this may be:

Controller class name: ComparisonController
Method title: CompareNodes
Action method name: compare_nodes
Route path: test/compare_nodes/{id1}/{id2}

Now edit your newly created controller. At the top add a use for the node module:

use Drupal\node\Entity\Node;

Edit the compare_nodes method.

Here is some sample code:

public function compare_nodes($id1, $id2) {

  $node1 = Node::load($id1);
  $node2 = Node::load($id2);

  $fields_to_compare = ['body'];

  $build = [];

  foreach($fields_to_compare as $field) {
    $build['comparisons'][$field] = [
      '#type' => 'container',
    ];
    $build['comparisons'][$field]['value1'] = [
      '#markup' => 'Node 1 value: ' . $node1->get($field)->value,
      '#prefix' => '
',
      '#suffix' => '
',
    ];
    $build['comparisons'][$field]['value2'] = [
      '#markup' => 'Node 2 value: ' . $node2->get($field)->value,
      '#prefix' => '
',
      '#suffix' => '
',
    ];

  }

  return $build;

}

You can edit the list of fields to compare as required and also make any changes to the markup required.

Enable your module and now when you visit: /test/compare_nodes/1/2 you can compare the values of node 1 with node 2.

You can replace 1 and 2 with whatever ids you would like to compare.


Why do modules run multiple times on a single page load?

hook_init() is invoked by Drupal only once for each requested page; it is the last step done in _drupal_bootstrap_full().

  // Drupal 6
  //
  // Let all modules take action before menu system handles the request
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    module_invoke_all('init');
  }

  // Drupal 7
  //
  // Let all modules take action before the menu system handles the request.
  // We do not want this while running update.php.
  if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
    // Prior to invoking hook_init(), initialize the theme (potentially a custom
    // one for this page), so that:
    // - Modules with hook_init() implementations that call theme() or
//   theme_get_registry() don't initialize the incorrect theme.
    // - The theme can have hook_*_alter() implementations affect page building
//   (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
//   ahead of when rendering starts.
    menu_set_custom_theme();
    drupal_theme_initialize();
    module_invoke_all('init');
  }

If hook_init() is being executed more than once per each page request, there could be a module that calls module_invoke_all('init'). It could also happens that a module calls drupal_goto(), and redirects the user to another page; this would cause a new page request, and a new invocation of hook_init(), if the page is not served from the cache.

In Drupal 7, there is just a way to check if hook_init() is invoked twice per page request, and it is to implement hook_init() using the following code.

function mymodule_init() {
  watchdog('mymodule', 'Request time: !timestamp', array('!timestamp' => REQUEST_TIME), WATCHDOG_DEBUG);
}

As REQUEST_TIME is a constant that Drupal defines each times it bootstraps (which means each times a page is requested), if you see two consecutive watchdog() entries showing the same value, then hook_init() is being invoked twice, or it is invoked in two different page requests done in less than a second. If the difference is 2 seconds, for example, then hook_init() is invoked in two different page requests.


The White Screen of Death (Completely Blank Page) is a good starting point to takle down the problem.

For D7, extension=php_domxml.dll in php.ini must be commented out. With that dll enabled, I got a blank screen too in Windows.
Check with your php configuration in your linux server.


They way you describe your case_id it sounds like the primary key of your table (a number which increases by 1 for each new entry). Rather than increasing this number in the form (and spare your self the trouble of assure atomic results when more than one person are entering cases at once) you can just set the column as primary key in your schema and let the db manage it. That way you don't need the field in your form at all.

$schema['case'] = array(
  'fields' => array(
    'case_id'       => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
   //your other fields
  ),

  'primary key' => array('case_id'),
);

That said I would consider not using a custom table to start with and instead leverage the functionality Drupal is shipped with and use a node to represent your cases.

There is a contrib module called Serial Field which allows you to add a field to your content type which increases by 1 for each case you create. There is a file field in core which allows you to upload a file to the site as well. The name field is a little tricky as Drupal doesn't allow empty titles but you can easily work around it by adding a simple text field for the name and generate the actual title with Automatic Entity Label.

In this case you need to download the two contrib modules, install them, create a case node type, add and configure the fields and you are done. The advantage is you can still leverage a great number of existing modules working with nodes/fields and entities which is much harder/impossible with custom tables. And you can display the results using Views.


Menu links duplicated on node/%node/edit pages

I'm not sure i fully understand the question, but please take a look to this post:

https://drupal.stackexchange.com/a/96963/30465

It seems related to your question.

I this it will be related to the language configuration fallback (since there is no language suffix inlcuded)

You could for example try

http://www.example.com/en/node/%nid/edit

if that works correctly (and only shows the engish menu links), you know that it will be a problem with language fallback.

Hope this helps, feel free to let me now if you need more!! :)


How to I retrieve default checkbox values using Form API?

after you save it, it saves the value of the checkbox as #value (not #default_value).

When defining the field settings:
(pulled from D7 cck_table.module)

  $form['css_class'] = array(
    '#type' => 'textfield',
    '#title' => t('CSS Class'),
    '#description' => t('Specify a class to be added to the table element.'),
    **'#default_value' => isset($field['css_class']) ? $field['css_class'] : '',**
  );

Revised:

More likely you would want to do this:

If you want to grab the default values, you can call `field_info_field($field_name

  Returns data about an individual field, given a field name.


The Entity Reference module integrates with the Views module in a few ways.  One of these is a new display called Entity Reference.

Create a view, and filter it to your needs.  Then, add a new Entity Reference display.  Configure this.

Then, on your content type(s), edit the entity reference field.  Make sure you are using the AutoComplete widget.  You should see a fieldset called Entity Selection.  Change this from "Simple (with optional filter by bundle)" to "Views: Filter by an entity reference view".  You should then see a dropdown appear which will have all of the views you have created that have Entity Reference displays.  Pick your view and save.

Keep in mind, though, that views with large datasets can cause dramatic performance problems with autocomplete fields.


Some fields are not sorting properly in view

It's probably not a configuration problem.  Examine the nodes that aren't sorting correctly.  They likely have spaces at the beginning of their titles.


Programmatically get the list of fields of a custom content

You're mixing up entity types/node (content) types/bundles. Common mistake :)

Especially since the UI naming is... very unfortunate.

What is called Content in the UI is actually the entity type node. And Content types are node types (you figured out that much), which are bundles of the node entity type.

getFieldDefinitions() expects an entity_type ID and a bundle. In your case, that is:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'my_custom_content');

Note that this will also return base field definitions like nid, vid, title, status and so on.

Tipp: Once you have a node object, you can get the same definition from that object and other useful information too:

$node = Node::create(['type' => 'my_custom_content']);
$node->getFieldDefinitions();
$node->getFieldDefinition('body');
$node->hasField('body');

So if you want to dynamically do something like this, it can simplify your code a lot if you first create the node with the information that's always enable and then work with the methods on your entity object.

Default recommendation when working with entities in 8.x: http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet


Change drupal font color based on variables

Yes, you can achieve this with jQuery.

In a custom module add the following code.

function custommodule_form_alter(&$form,$form_state,$form_id) {
  if ($form_id == "yourcontent type form") {
    $form['field_field1']['#attributes'] = array('id' => 'field1_id');
    drupal_add_js(drupal_get_path('module', 'custommodule') . '/jsfilename.js', ));
  }
}

Put this in jsfilename.js.

(function($) {
  Drupal.behaviors.custommodule = {
    attach: function (context, settings) {
      // I suppose your field1 html elemet ID=field1_id
      $('#field1_id').change(function() {
        if($('#field1_id').val() < 50) {
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        else if($('#field1_id').val() > 50 && $('#field1_id').val() < 70) {
          $(this).css("color","red");
          $(this).css("color","yellow"); // you can add class to it and in css file style it  ex:$(this).addClass('class1');
        }
        // …
      });
    }
  }
}


It was simple after all in the table node__body there is body_format and you should set it to full-html


I want to use this script in Omega subteheme

Short Answer: themename.info or drupal_add_js().

Long answer: If you always want it to load just use the info file and add a [js] entry. Google can help you there.

Depending on when you'd like that JS to load you might want to define it only when nodes of a certain type are displayed, etc. This changes where you put drupal_add_js() in your template.php.

If you want it only when you display nodes then stick it in THEMENAME_preprocess_node() and you can use the $vars in there to conditionally load it on a particular node type only, etc


How do I dynamically modify a block's mark up at render time, in Drupal 7?

I think you are looking for hook_block_view_alter(). It provides both the alterable $data, as well as $block, which contains the module and delta.

To determine which blocks are available, you could start off with:

function MYTHEME_block_view_alter(&$data, $block) {
  kpr($block->module);
  kpr($block->delta);
}

Then once you find the module:

/**
 * Implements hook_block_view_alter().
 */
function YOURTHEME_block_view_alter(&$data, $block) {
  if ($block->module == 'block' && $block->delta == 1) {
    $data['content'] = '
New content
';
  }
}

Or even:

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function YOURTHEME_block_view_block_4_alter(&$data, $block) {
  $data['content'] = '
New content
';
}


How do you render the View, Edit, Delete, and Revisions tabs in a specific location on node/page?

The tabs are in a block now. Go to the block layout (/admin/structure/block) and move the block Tabs to another position.

If you don't find an existing region for what you want to do, add a new region to your theme and place this region in the page template page--node.html.twig, so that you can integrate the tabs inside of your html structure. If you need the tabs in different positions you can add multiple instances of the tabs block and configure the visibility.

Try not to put tabs in nodes, combine those two on the page level in a custom page template for nodes if possible.

But, in case you need them between the content of the node. you can do it on node.html.twig. It is not the best practice but can be done if required, but you need to take care, that the caching is working and that the tabs don't appear when the node is used in other places.


Commerce Create Cart/Order without product

You are unsetting $new_order and then calling commerce_order_save($new_order); when $new_order is null. It should use $order there.  i.e.

not:

commerce_order_save($new_order);
unset($new_order);

$order = commerce_cart_order_load($user->uid);
$order->data['suburbs'] = $_REQUEST['suburb'];
$order->data['truck'] = $_REQUEST['truck_size'];
commerce_order_save($new_order);

but instead:

commerce_order_save($new_order);
unset($new_order);

$order = commerce_cart_order_load($user->uid);
$order->data['suburbs'] = filter_xss($_REQUEST['suburb']);
$order->data['truck'] = filter_xss($_REQUEST['truck_size']);
commerce_order_save($order); // here

It also looks like there's no need to save and reload the order there when one save would suffice.

Edit: OP has changed the $new_order code typo.

No need to save and load the order, the order_id is already in $new_order->order_id after saving in commerce_order_save($new_order);

Your problem is probably a NULL or empty $_REQUEST var.
Alternatively, you could add the fields to the order entity itself via the Fields UI.


Why there are two payment for one order with same remote ID

For some reason the IPN for that payment triggered the creation of a second payment transaction within Drupal Commerce. Couldn't tell you exactly why it happened, though it could've been the result the customer's page request and the IPN request being processed simultaneously. The module ought to filter out IPNs to not duplicate transactions like this, so if you see it again, file a bug report in the module's issue queue.

To answer your direct questions, the order cost $17, the balance is now negative (meaning it appears overpaid within Drupal Commerce, even though it wasn't), and it would be safe to delete one of the transactions (but you'd need to be logged in as an administrator).


Change dropdown value depending on URL clicked

Prepopulate module will take values from the URL and populate a field.
This page has an example for D7.


Drupal 7 at shared hosting behind Cloudflare

Why don't you install the CloudFlare - Free Reverse Proxy, Firewall, and Global CDN module? The module comes with instructions on how to solve this problem:

Installation Instructions:

  Install and Enable this module. Add one line of code at the end of
  your settings.php file:

$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"] ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];

  Save your email address and CloudFlare API key to the CloudFlare administration screen on your Drupal web site (admin/settings/cloudflare).


How to theme the $content variable's contents?

If all you want to do is change the order, you do that in the edit content/manage fields form where you can drag and drop the fields in whatever order you want them to be output.

If that's not exactly what you want, you can also change how they are displayed in the "display fields" form.

If all of the above doesn't do exactly what you want, you can print out each field however you want inside the template itself, eg, instead of printing $output, you can print out each field you want when and how.

So, if for example, you have a text field called field_description, you can output it by putting a  print $node->field_description[0]['safe']; in there since the entire $node is available inside the template to play with.

To see all there is to work with in your specific case, a quick drupal_set_message('<pre> . print_r($node,true) . '</pre>'); in your template will show you lots of information.


Use Advanced Poll module. I think this may help you to solve your query.


Save the #default_value of custom fields when editing comments

I finally solved my problem, has created a field using field_create_field and attached it to the essence of my comment present the type of material
My code for the solutions in the Custom Module:

/**
 * Реализация hook_enable().
 */
function comment_author_enable() {
    foreach (_comment_author_select_field_create() as $field) {
        field_create_field($field);
    }
    foreach (_comment_author_select_field_instances() as $instance) {
        $instance['entity_type'] = 'comment';
        $instance['bundle'] = 'comment_node_zayavka';
        field_create_instance($instance);
    }
}
function _comment_author_select_field_create(){
  $fields['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select an option from the list'),
    'type' => 'list_text',
    'cardinality' => '1', // change this to -1 to enable ctrl+select
    'foreign keys' => array(),
    'indexes' => array(
      'value' => array(
        0 => 'value',
      ),
    ),
    'module' => 'list',
    'settings' => array(
      'allowed_values_function' => '_comment_author_options_list',
    ),
  );

  return $fields;
}
function _comment_author_select_field_instances()  {
    $instances['brigade_select'] = array(
    'field_name' => 'brigade_select',
    'label' => t('Select brigade'),
    'description' => t('Please select the team that was sent to you with reference to this application.'),
    'default_value' => NULL,    // add a default value here that matches your key => index values
    'display' => array(
      'default' => array(
        'label' => 'above',
        'module' => 'list',
        'settings' => array(),
        'type' => 'list_default',
        'weight' => -1,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => -1,
      ),
    ),
    'required' => 1,
    'settings' => array(
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'options',
      'settings' => array(),
      'type' => 'options_select',
      'weight' => '-1',
    ),
  );
  return $instances;
}
function _comment_author_options_list(){
global $user;
$query = db_select('node', 'n')
    ->fields('n', array('type', 'uid', 'title', 'nid'))
    ->condition('n.type', 'brigada_type', '=');
 $result = $query->execute();
 $brigade_list = array();
    foreach($result as $value){
        if($user->uid != 1){
            if($value->uid == $user->uid){
             $brigade_list[$value->nid] = $value->title;
            }
        }else{
        $brigade_list[$value->nid] = $value->title;
        }
    }
    return $brigade_list;
}


This is achieved by setting the Permission of the View to Role and selecting the role required.


How to add 'odd' or 'even' class in each row of a Views Table output?

This can be related to Drupal, since you want to add classes to table rows, here is how you do it:

Copy the core/themes/classy/themplates/views/views-view-table.html.twig to your theme's template folder, and change the following lines (line 95):

  <tbody>
    {% for row in rows %}
      {% set parity = cycle(['odd', 'even'], loop.index0) %}
      <tr {{ row.attributes.addClass(parity) }}>


How to get the value / URL of a Link field in a Twig template?

You can get the URL and the value (text) this way:

{{ content.field_link.0['#url'] }}

{{ content.field_link.0['#title'] }}


Rather than checking the block's config in the existing instance, delete it and re-insert it, checking the settings again in the insertion screen. It now shows up for me after doing it this way.


JS batch progress bar: possible to force refresh more frequently than every 1500 ms?

Turns out none of us (neither I or nor the commenters) were completely "right", nor completely "wrong". There IS an arbitrary limit hardcoded in D8's core, for JS batch progress bar refreshes, but it's not 1500 ms as I thought -- it's 1000 ms.

And it's harcoded in a different place than any of us thought.

As @MarioSteinitz stated, yes, the batch API inserts only a very short pause between two Ajax requests -- 10 ms. (The Ajax API is different with its 1500 ms default pause and I mixed up the two.)

However, try as I might, I couldn't get the progress bar to refresh more often than once every approximately 1.1 or 1.2 seconds. No matter how fast I finished my simulated batch work (by reducing my usleep() in the batch code), the relevant DOM objects, such as progress__bar, were never refreshing more frequently than just over once a second.

You can easily see their "throbbing" in Inspector's DOM view and count onethousand-one, onethousand-two as they pulse away... even when my batch function did absolutely nothing, the fastest I could get these DOMs to flash was just over once a second.

So what gives?

Well the batch API is just weiiiiirrrrrd... instead of giving the programmer the say in how much work ONE Ajax request is supposed to do, the function _batch_process() in core file /core/includes/batch.inc has a loop harcoded that calls the batch function again and again until at least 1000 ms have passed (or the batch is finished):

// If we are in progressive mode, break processing after 1 second.
if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {
  // Record elapsed wall clock time.
  $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  break;
}

Weird because a batch is ALREADY supposed to be a large process chopped into small bite-sized chunks. So the entire batch already IS a loop, but there's, in fact, a secondary inner loop, whose break conditions are outside of the coder's control!

You think this kind of policing of the programmer's wishes is not weird, arbitrary and unnecessary? Well consider that that the batch API (after what feels like decades), still doesn't allow progressive batches (i.e. batches that are all processed in one swoop, for example from the shell) -- see https://www.drupal.org/project/drupal/issues/638712.

But I digress.

So for sh*ts and giggles I changed the > 1000 to > 100 in the above core code and what do you know, the progress DOMs refreshed like crazy!

Of course I can empathize with the idea that no batch should hammer its host server with heavy requests every 10 ms, for obvious reasons. So the developers decided to loop and re-loop the batch function until at least 1000 ms have passed, before the next Ajax call is triggered.

Well-intentioned? Yes! Arbitrary and inflexible? Absolutely. As the programmer of a batch, I believe it should be MY choice how much exactly I want to do in one Ajax call. Any Drupal code has the potential to crash or deadlock the server, or overwhelm the browser. Why police this particular part?

Drupal maintainers: Why not default to 1000 ms if that is a trusty value for most applications or unaware coders, but for batches that require a more dense flow of output, let's say, once every 100 ms, give us the power to do that!

So how to get rid of the pesky > 1000 condition - without hacking the Drupal core of course!?

if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {

If this were D7, we'd just manipulate the global $timers array: Just before our batch function exits, set its start value back to the stone age (01/01/1970), and the calling _batch_process() will always "think" at least one second has passed, and give control back to Ajax immediately.

Just that this isn't your grandma's Drupal; we are now all fancy object-oriented and stuff.

Looking at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Timer.php/8.2.x we notice that we can't just poke whatever we want into the Timer::$timers array any more. It is declared protected, i.e. no outsider, such as my batch function, is allowed to mess with its internal values.

So we're back to square one... or are we?

Well thankfully this is PHP and not a "real" programming language! (ducks)

Meaning, there's always a loophole to bypass any new-fangled OOP restrictions that those eggheads at Software Engineering University demanded. To hell with them!

After some googling, I wrote the following function. And by "wrote" I mean I all but stole it from people who know much more about PHP than I do: https://stackoverflow.com/questions/6448551/is-there-any-way-to-set-a-private-protected-static-property-using-reflection-cla

  /**
   * Revert Timer::$timers['batch_processing'] back to the stone age
   * to trick batch.inc / _batch_process() into thinking at least 1 second has passed
   */
  protected static function revertTime() {

    $obj         = new Timer();
    $refObject   = new ReflectionObject($obj);
    $refProperty = $refObject->getProperty('timers');
    $refProperty->setAccessible(true);
    $myTimers = $refProperty->getValue();
    $myTimers['batch_processing']['start'] = 0;
    $refProperty->setValue(null, $myTimers);

  }

I now call revertTime() at the very end of all my "batch on crack" functions, juuuuust before they exit. It sets the start time of _process_batch()'s Timer::$timers['batch_processing']['start'] to 0.

And 0 is always more than one second ago.

The effect is that _batch_process() never loops; the Ajax call terminates after exactly one call to my batch function.

10 ms later, the batch API initiates another Ajax call to my batch function, resulting potentially in a rat-tat-tat machine-gunning refresh cycle for my progress bar.

NOTE OF CAUTION: When I first ran this, with all checks and balances disabled, it overwhelmed Chrome with its rapid-fire Ajax calls every 10 ms. Today was a hot day (I live in the southern hemisphere) and my Mac slowed down to a crawl under the load of the Ajax calls... the built-in overheat protection kicked in!

When you use this hack, it is your responsibility to make your batch functions either do a LOT of slow stuff in one iteration, or waste sufficient time with usleep(). Otherwise the batch staccato may overwhelm your visitor's browser or your server.

Thanks again to all the contributors here and elsewhere who finally led me to a semi-clean (non-core hack) solution! ❤


Drupal Feature Recreate Module - what next

From Modifying, updating and reverting Features:

  The "recreate" button in the web-based administration interface is the equivalent to "update". However, the modified code will be provided for download as a .tar archive, instead of overwriting the existing feature module. It is up to the site builder to manually unzip and re-upload the modified module, replacing the original.


Entity access controler not called from custom route

I guess you need to do a route parameter upcasting:

entity.politician.about_me:
  path: '/politician/{politician}/about-me'
  defaults:
    _controller: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::build'
    _title_callback: '\Drupal\pw_basic\Controller\PoliticianFrontend\AboutMe::title'
  requirements:
    _entity_access: 'politician.view'
  options:
    parameters:
      politician:
        type: entity:politician


How to get token of parent entity in paragraph?

There's nothing out of the box (see this issue for the details). Implementing your own token isn't too tricky.

I haven't had a chance to test this but I'm pretty sure it'll work:

function MODULE_token_info_alter(&$info) {
  $info['tokens']['paragraph']['parent_entity'] = [
    'name' => 'Parent entity',
    'description' => 'Parent entity of the paragraph',
  ];
}

function MODULE_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type == 'paragraph' && $paragraph = $data['paragraph']) {
    $parent = $paragraph->getParentEntity();
    $bubbleable_metadata->addCacheableDependency($parent);

    foreach ($tokens as $name => $original) {
      if ($name == 'parent_entity') {
        $replacements[$original] = $parent->label();
      }
    }

    $token_service = \Drupal::token();
    if ($parent_entity_tokens = $token_service->findWithPrefix($tokens, 'parent_entity')) {
      $replacements += $token_service->generate($parent->getEntityTypeId(), $parent_entity_tokens, [$parent->getEntityTypeId() => $parent], $options, $bubbleable_metadata);
    }
  }

  return $replacements;
}


Exposed filter for data and select field

According to the docs here drupalgap.org/node/498 the filter should be added to your app when you create it in your view and then publish it. If those instructions do not work to create a simple filter, I suggest raising and issue over there.

As to Date filtering, I expect that only the select list exposed form items will transfer to your app out-of-the-box. If you want some custom UI elements such as jQuery mobile date picker to match the rest of your app UI, you will have to use a text field in the views exposed filter then edit the code on you app to call the UI element.

A lot of the time with similar things, I end up creating icon links in the header that act like filters and sorters e.g.

<?php
print l("<i class='icon icon-cancel-circled'></i>", "my/view", array('html' => TRUE, 'query' => array('sort_by' => 'created', 'sort_order' => 'ASC')));
?>

This makes an arrow up icon link (if you're implementing icons somehow) which will go to the view sorted by "created" "ascending".

Having an exposed filters form in an app is often too much for a small screen when a few icons will do, and this should transfer to your app in the header ok.


Export exposed fields into a block with Views

This functionality is now built into Views itself.  See How To Display Views' Exposed Filter In A Block And Theme It for details.


form_set_error message delayed one page refresh

I had the same, here is the solution and explanation:
The key of this problem is the drupal_get_form('FOO') is called in theme layer. For example _preprocess_WHATEVER or directly in BAR.tpl.php

The messages are prepared in _process_page()  After that it's unchangeable in deeper theme functions, like FOO_preprocess_node. (That's not exactly true, but it's out of scope of this topic.)

I bet, you prepared a variable by drupal_get_form('FOO') in _preprocess_node, maybe later.

You should use hook_entity_view_alter or hook_node_view_alter, maybe hook_page_alter if necessary, anything else than theme hooks.

Just for the record: The last time you are able to set a message by drupal_set_message() is _preprocess_page


How to make sure that /taxonomy/term/24/WHATEVER gives 404?

I've done something similar, but there might be some edge cases where this solution might not be suitable.

You can use hook_taxonomy_term_view() and within that check if the amount of arguments in the URL ($_GET['q']) is more than three.

/**
 * Implements hook_taxonomy_term_view().
 */
function custom_module_taxonomy_term_view($term, $view_mode, $langcode) {
  if (count(arg()) > 3) {
    // This will throw a 404.
    drupal_not_found();
  }
}


You could hack the includes/bootstrap.inc file
The very first line of code will be something like:

define('VERSION', '7.11-dev');

Set it to 7.7, and drush should accept that 7.8 is a never release.
I know that hacking core is strongly discouraged, but since the upgrade itself will remove the hack, I think it's more than ok.


When I try to modify a view, I get a screen full of odd text

This is caused by a JQuery AJAX failure.  Several different things could be causing this.  You will probably need to research the current active theme and any modules that you are using in or around that view (especially ones that use AJAX) to see if they have a history of AJAX related failures (and related fixes or patches.)  A few things to try:

Enable, disable or change the settings within the jQuery Update module (some versions of jquery are not compatible with some modules.)
Change the theme used on admin pages to a generic theme (included in the Drupal download)


Yes you can but you shouldn't.

When adding a stylesheet, Drupal does not tamper the file names. So regardless of the way you add it, your PHP file or whatever file name you use will be added to the import clauses or to the link tag.

However, note that Drupal can combine those CSS files, and it uses file_get_contents() function to get the file contents. In that case, Drupal will get the source code of your PHP file, making this approach fail.

If you want to add dynamic CSS, you can go for some workarounds though.

Add all possible styles to one stylesheet under different classes, and only change the class name of the HTML that you want to change styles of.
Have a predefined set of stylesheets, and only add the ad-hoc in a preprocess function or something.
Add the styles as inline CSS.

Other than that, the core Color module has some similar approaches that you might find useful.


Select People -> Permissions, scroll down and adjust the permissions of Contact.


Drupal CMS - Find Content - how to drop the ?destination=admin/content in the edit link?

This is a result of the content editing screens returning the user to that. If they edit content from the front-end, the destination is the node.

You can override that default content manager with a View configured the way you want it. The 'Edit' link won't have a destination in the URL, and if I recall, it will return the user to the content after editing.

Also, if this is D6 and they have access to this page it sounds like they have administer nodes access. You might want to tune the permissions differently and setup a view so you can override admin/content path(s) with your View to override the content manager.


Dynamically change the "access denied page" title and body

Access functions are only for calculating access results. You can't do anything else because this function is called multiple times, not only for incoming routes but also for outbound links.
To set a response use on403() of an ExceptionHtmlSubscriber. You can also set the result of a sub-request if you want a themed 403 message. See How can we catch the acces denied exception?
Edit: Answering further questions

1-Unfortunately my custom on403() method is never called (on the other
hand, the on403() method DefaultExceptionHtmlSubscriber is called):
What I am missing?

You need to register the service in mymodule.services.yml:
services:
  mymodule.exception_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleExceptionHtmlSubscriber
    tags:
      - { name: event_subscriber }

2-Let say that my custom on403() method is called: what should be the
code to redirect the user on my custom 403 page containing my custom
message (ie: it could be nice to display the reason of the
AccessResult AccessResult::forbidden("a good reason");

You find the message in the exception object:
public function on403(ExceptionEvent $event) {
  // ...
  if ($my_condition) {
    $message = $event->getThrowable()->getMessage();
    $event->setResponse(new Response($message, 403));
  }
}

BTW you don't need to call parent::on403($event) because the parent registered with a lower priority will be called automatically when your event subscriber doesn't set a response.


How to make blocks contextually aware of current webform page

This is currently not possible through the default UI due to the URL of all webform pages being the same.

There are two possibilities as far as I know.

(1) If your blocks only show help texts or any other static information, you should probably not use blocks at all but add markup components and place them after each page break.

(2) If you are indeed using dynamic blocks (e.g. coming from views), you would need to create a custom theme file (e.g. webform-form.tpl.php) in which you may enter the logic defining which block should appear. The currently viewed page number of your webform should be available through $form['details'].


How can I prevent users from inputting URLs into a field?

The Field validation module let you set up your own regexp or PHP code to validate (or not) what user puts into a text field.  However to reject e-mail addresses, your validator must be clever enough to not only recognize regular e-mail addresses such as spammer@example.com but also obfuscated e-mail adresses such as spammer(at)example.com.

Added note (about filtering): If, instead of rejecting input that do not validate, you want it filtered by having email addresses and links removed (or replaced with some string indicating redaction), you can use the Plain text input filter as a starting point, and just replace the code that currently turns email-adresses and URLs into live links, with code that redacts these things instead.  Then, just rename the result of hacking the code, and add it to your configuration as a custom filter.


How to print all Webform messages outside the form?

Yes, Webform is working on drupal default message

<?php if ($messages): ?>

    <?php print $messages; ?>

<?php endif; ?>

You need to put this code according to your requirement on the template (page.tpl.php).

Finally, webform submission thank you message will be shown on your content section which is coming on node.tpl.php

<?php print $links; ?>


How can I disable image resizing in CKEditor?

According to How to disable the image resize handles ? this is supposedly solved with CKEDITOR.config.disableObjectResizing = true;.

But even when I change it directly (for testing purposes) in /core/assets/vendor/ckeditor/ckeditor.js

CKEDITOR.config.disableObjectResizing=!1 to

CKEDITOR.config.disableObjectResizing=!0
// OR
CKEDITOR.config.disableObjectResizing=1
// OR
CKEDITOR.config.disableObjectResizing=true

It doesn't make a difference, I can still resize.

So I guess you will have to solve this via CSS.

If you want them to still be responsive, you could do:

.some-div img { max-width: 100% !important; }

OR

.some-div img { max-width: 400px !important; }

Obviously, this would mean the size in the editor may not reflect the size on the page, but this will do at least in the meantime if you're not satisfied with this answer/approach.


How to make a block visible only to one page

There are Visibility settings for blocks in Drupal. One of options is "Show block on specific pages". Select "Only the listed pages" and input user/*/galleries


Displaying custom module content in a popup from other page

You may want to use the Lightbox2 module.
It will display it in the same window but look like a pop-up in page, like in Facebook.


Moved Site - Can't find original CSS for look other than in the ADVAGG

AdvAgg is used to improve the standard Drupal Core aggregation.
Just disabling AdvAgg won't disable aggregation.
You will need to disable CSS aggregation under the Performance settings, then flush caches, and you should be able to inspect the button CSS again.


Multiple forms for one content type using one module

You can use drupal Webfroms for this purpose.

Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.

Some good examples could be contests, personalized contact forms, or petitions. Each of these could have a customized form for end-users to fill out. If you need to build a lot of customized, one-off forms, Webform is a more suitable solution than creating content types and using CCK or Field module.

here is the way you can create a multi step form which solves your purpose


Basically, drupal_get_form doesn't render the array - it just returns the renderable array from the form function. You need to render it yourself.

Try this:

function custom_shortcodes_shortcode_form($attrs, $text) {
  $form = drupal_get_form('custom_shortcodes_shortcode_form_attributes');
  $attrs = drupal_render($form);
  return $attrs;
}


Drupal 8, "view ui query" to drupal code query api ?

No, there is not.

You're also not supposed to write a query directly against entity or field tables yourself. Use the entity query API instead:

https://www.sitepoint.com/drupal-8-version-entityfieldquery/

$uids = \Drupal::entityQuery('user')
  ->condition('uid', 0, '<>',
  ->range(0, 50)
  ->execute();


How to remove a unique key in an update hook

All of the core schema classes (mysql, pgsql & sqlite) check for the existence of the constraint before actually dropping, so you don't have to check yourself. If you do you're actually doubling up on a DB op unnecessarily.

To cover all eventualities your code could look something like this:

try {
  if (db_drop_unique_key($table, $name)) {
    // Constraint was found and removed.
  }
  else {
    // Constraint was not found, nothing was altered.
  }
}
catch (PDOException $e) {
  // Constraint was found, but something went wrong, see $e->getMessage() for more info.
  throw new DrupalUpdateException($e->getMessage);
}

Incidentally, a unique constraint is treated the same as an index by the core schema classes, so db_index_exists() can be used to check for them too.


Okay, I am going to Explain you in a very simple way using a Postman Software.
 1. Enable the restui Module.
 2. Add the basic_auth authentication.
 3. Get the X-CSRF-Token from /rest/session/token.
 4. Follow things by this image:

 5. Add the following text into your Body.

And hit the Send Button Its Done!


How to show registration page in another language, maintaining its natural behaviour?

Navigate to /admin/config/regional/language within your site, and verify these things (and correct where appropriate):

Use "English" as your default language
use the "Edit" link for "English" on that page, which will bring you to "/admin/config/regional/language/edit/en". On that page, make sure the value for "Path prefix language code" is "blank".


How to create a table without uninstalling and reinstalling the module?

This link answered my question: Updating tables: hook_update_N() functions.

For example:

In Drupal 7:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_7101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  db_create_table('mytable2', $schema['mytable2']);
}
?>

and in Drupal 6:

<?php
/**
 * Create new database table {mytable2}.
 */
function mymodule_update_6101() {
  $schema['mytable2'] = array(
     // table definition array goes here
  );
  $ret = array();
  db_create_table($ret, 'mytable2', $schema['mytable2']);
  return $ret;
}
?>


You can retrofit your custom theme to make it responsive. Emma Jane Hogbin has written a great tutorial for this (available for purchase at http://www.responsivewebdesignguild.com/). I have used it to retrofit a couple of drupal sites that use the zen base-theme, the principles should work for any theme.

The basic principles/steps are:

Add a new style sheet to your css directory (and .info file)
Determine break points in your theme depending on the content - what do you want to display wide - medium - narrow views, how do you want to reorganize the page
Add media queries to the stylesheet reflecting the break points, like this:

@media screen and (max-width: 960px) {
  #main {width: 100%;}
}
@media screen and (max-width: 750px) {

}
@media screen and (max-width: 500px) {

}

Basically, adjust the width/etc. for the elements and width determined earlier.
The navigation menu is a special case. At the max-width that makes it most likely that the user is using a table or a phone, the menu should be "fat-finger" enabled, by changing the ul and li styles so that each link has a larger width and height. For me, links changing from horizontal to "one link per line with padding" works best.

Then, copy the core html.tpl.php file into your theme/templates directory, and add the following to end of the header section:

<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<meta name="HandheldFriendly" content="true" />
<meta name="MobileOptimized" content="width" />

Emma Jane demonstrated this approach for the Domicile theme, the result is available at:
https://drupal.org/project/domicile_responsive


Take a look at https://www.drupal.org/project/webform_conditional

Just make both e-mail & phone mandatory, but only show the relevant field, based on what was chosen in 'best form of contact'.

The module takes into account the 'state' of the form. It doesn't force mandatory, even if the field is set to be mandatory, but is hidden due to a certain select option ( in your case, the 'best form of contact' ).


How to hide revisions tab in quiz module?

It is provided by the Diff module: Disable the new check-box on workflow settings, "Enable revisions page."


Superfish menu is not responsive for mobile screens

Superfish has a pretty extensive settings/configuration area, all of which, do take away any necessary programming for menus, and make setting up a complex menu simple.

You are probably missing a mobile declaration somewhere in the settings/config, I would read up on the Superfish documentation here: https://www.drupal.org/node/754652

This also has other useful links that may assist with your situation.


How to insert a text field inside boolean (single on/off) field in node form

You could implement hook_form_alter() and add a suffix or prefix to your field. The suffix and prefix may contain html.

    $form['terms'] = array(
      '#prefix' => '
Something before the field
',
      '#suffix' => '
Something after the field
',
    );

For a detailed instruction how to write a module that implements hook form alter see this blog post.

There is also a module that can add markup widgets to forms. Checkout Markup.


Does it mean I can use it safely on Drupal 8?

This is subject to the code written to port the module, and might be prone to some issues. The best way to find that out is by testing the patch and reporting back (on the same drupal.org thread) if you find it to be working or if you come across any issues.

  Is it ok to use patched up Drupal 7 contrib modules on Drupal 8?

Again, IMHO the best way is to work with collaboration here:

If you are a developer, help contribute the code.
If you are a tester, help with testing the solutions; and contributing to tests.
If you are good a documentation, write about the solution.
Many more ways to contribute... Check the "contributed projects" section from https://www.drupal.org/8/ready for good resources.

As per your main question:

  Will Zopim Chat work with Drupal 8?

It surely will, if those who require it help make it work!


How to generate commerce add to cart form on a page with full functionality?

use the inline entity form module to enable product variations. in the node you only have a product reference field, where you reference all your desired product(-variations)

then the user still can input the quantity, but also choose the product-variation. in your case the different ml-units.


Drupal 7 db_insert() execute() error when table contains unique keys

PHP has exception handling in the form of try...catch blocks:

try {
  $insert = db_insert('mymodule_mytable')->fields($fieldarray)->execute();
}
catch (PDOException $e) {
  drupal_set_message(t('Error: %message', array('%message' => $e->getMessage())), 'error');
}

So rather than ignore the error completely, you can actually respond to different types of exception and react accordingly.


In which cases should hook_process() and hook_process_HOOK() be used?

I'll try to stay away from explaining the whole theme system. The order and use of the functions is best explained here.

Preprocessor functions run before process functions. You should run hook process for cases where you want to affect every theme call after all the preprocessors have run. (Well, I believe it is only every theme call with a .tpl file.)

RDF is a good example as it wants to insert meta data into every theme template. But in most cases it is not something you would want to do. Another example would be something like the Pirate module.

Preprocessors are more targeted. If you only want to change lists for example you could use a preprocess hook there. I believe that hook_preprocess_HOOK()s are run for templates and functions.

hook_preprocess() can be used in a theme if you wish to preprocess something which is not overridden in your theme, as the theme_preprocess_HOOK() won't trigger unless you do.


You'll just have to add another JOIN to the weight_weights table on your query.

The weight_weights table stores the entity_id, entity_type and the weight value.

EDITED

Here goes an example:

$sql = "SELECT * FROM `node`
        LEFT JOIN `field_data_field_anasayfa_catwalk` ON `field_data_field_anasayfa_catwalk`.`entity_id` = `node`.`nid`
        LEFT JOIN `weight_weights` ON `weight_weights`.`entity_id` = `node`.`nid`
        WHERE type = 'designers_albums'
        AND `node`.`status` = 1
        AND `node`.`language` = '".$language->language."'
        AND `field_data_field_anasayfa_catwalk`.`field_anasayfa_catwalk_value` = 1
        ORDER BY `weight_weights`.`weight` ASC";


What you are wanting to do is re-theme cck's theme_content_multiple_values() call that creates the html table with the input on top instead of the bottom.  Quick and dirty in drupal 6 at least, I went into content.module and pulled out that function as well as the helper function that does the sort, copied them into my theme's template.php and named them appropriately with this being the result:

function YOURTHEME_content_multiple_values($element) {
  $field_name = $element['#field_name'];
  $field = content_fields($field_name);
  $output = '';

  if ($field['multiple'] >= 1) {
    $table_id = $element['#field_name'] .'_values';
    $order_class = $element['#field_name'] .'-delta-order';
    $required = !empty($element['#required']) ? '*' : '';

    $header = array(
      array(
        'data' => t('!title: !required', array('!title' => $element['#title'], '!required' => $required)),
        'colspan' => 2
      ),
      t('Order'),
    );
    $rows = array();

    // Sort items according to '_weight' (needed when the form comes back after
    // preview or failed validation)
    $items = array();
    foreach (element_children($element) as $key) {
      if ($key !== $element['#field_name'] .'_add_more') {
        $items[] = &$element[$key];
      }
    }
    usort($items, 'YOURTHEME_content_sort_items_value_helper'); // MOD 1

    // Add the items as table rows.
    foreach ($items as $key => $item) {
      $item['_weight']['#attributes']['class'] = $order_class;
      $delta_element = drupal_render($item['_weight']);
      $cells = array(
        array('data' => '', 'class' => 'content-multiple-drag'),
        drupal_render($item),
        array('data' => $delta_element, 'class' => 'delta-order'),
      );
      $rows[] = array(
        'data' => $cells,
        'class' => 'draggable',
      );
    }

    $output .= drupal_render($element[$element['#field_name'] .'_add_more']); // MOD 2
    $output .= theme('table', $header, $rows, array('id' => $table_id, 'class' => 'content-multiple-table'));
    $output .= $element['#description'] ? '
'. $element['#description'] .'
' : '';

    drupal_add_tabledrag($table_id, 'order', 'sibling', $order_class);
  }
  else {
    foreach (element_children($element) as $key) {
      $output .= drupal_render($element[$key]);
    }
  }

  return $output;
}

function YOURTHEME_content_sort_items_value_helper($a, $b) {
  $a_weight = (is_array($a) && isset($a['_weight']['#value'])) ? $a['_weight']['#value'] : 0;
  $b_weight = (is_array($b) && isset($b['_weight']['#value'])) ? $b['_weight']['#value'] : 0;
  if ($a_weight == $b_weight) {
    return 0;
  }
  return ($a_weight > $b_weight) ? -1 : 1; // MOD 3
}

There are only three modifications to the code:

MOD 1 : changed the second argument to point to "my" sort function instead of CCK's

MOD 2: moved the add-more button to display before the table instead of after it

MOD 3: changed < to > to it sorts "backwards" from the default

Clear your theme registry cache and if all is well and good in the world of my thursday brain, you should now have your add more and enter buttons on top of the table instead of below.