Attaching additional queries to webforms

Webform has already this option, that you can find in the Submission settings. Otherwise, if you need to check something more you still can use some Webform hooks.

But if you need more complex submission checking, the best way from my point of view is to add a validate callback with the help of hook_form_alter().

Edit

Here is an example how to use the hook_form_alter(); For it, you must install the module Devel before.

// First you have to create your module
// you will find more information about it
// here http://drupal.org/node/231276
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // To add your validate callback to any form, you must find
  // the right form_id before
  // the form_id is an id that identify the form
  // from all that drupal can generate.
  // My solution to find it quickly its to show
  // all form_id with the help of Devel
  dsm($form, $form_id);
  // This will show you a drupal_set_message with something like that
  // form_id_form => Array()…
  // When you found the form that you want add the validate callback you
  // change it like that
  if($form_id == 'the_form_id') {
    $form['#validate'][] = 'mymodule_myvalidate';
  }
}

function mymodule_myvalidate(&$form, &$form_state) {
  // Here you can see want you receive
  // by checking the content of $form_state
  // still with Devel, like that
  dsm($form_state);

  // You should see the values in $form_state['values']
  // After you can make your additional checks and retur errors like that
  if($error) {
    form_set_error('field_error', t("You can balbla"));
    return;
  }
}


How do I filter a view by the node taxonomy you're currently on?

To visualize what J. Reynolds said above.
Add Contextual Filter - Content: Has taxonomy term ID with following settings

then add contextual filter - Content:Nid (provide default value -> Content ID from URL) and in "More" section of that filter check "Exclude" checkbox, which will remove the currently viewed node from the list of nodes related by taxonomy term.


How can a user choose items from a view?

Use flags module along with the default view it provides.

  Flags may be per-user, meaning that each user can mark an item
  individually,

You can create two flags one called Marked and an other one called Delivered. Reader should be able to flag a Book as Marked but only Site Admin should be able to mark a Book as delivered.

If you are looking for more control consider using Workflow and then defining the states Marked and Delivered. You can set the access levels accordingly for the status change.


Add Color field into view.
Now click on formate setting.
Select the Color field as a Grouping field.


How to display the comment form of a node in a popup?

There is Dialog API for Drupal 6, and Drupal 7 (although only the development snapshot for Drupal 7 is visible in the project page). This module contains sub-module Dialog Comment.

For Drupal 7, as I can see, there are some problems with modules for popup dialogues.


Is it possible to combine a Bootstrap theme with an existing custom Drupal 6 theme?

There is the Bootstrap base theme for D7 (and even an upcoming D8 version), which bridges the gap between Drupal and the Bootstrap Framework, with also quite a few (contributed) sub-themes available for it already.

So if your question was about D7, then it seems such combination that you're looking for should be possible. As you may know already, the Bootstrap base is not available for D6. But maybe you can use the D7-version of it as inspiration to somehow make such combination also work for D6. Ultimately even come up with a backport of the Bootstrap base theme for D6?

Note: as mentioned by Molot's in the comment to this answer, there is "some" D6 backport of it available on github ... Via Drupal.org there doesn't seem to be any D6 versions, however there "is" some D5 version of it also ... Maybe upgrading the D5 version to D6 is another approach to consider? Using Browse code repository only results in D7/D8 versions though ...


Modules installed with composer do not have a version number

I am using https://packagist.drupal-composer.org/ as Packagist repository for Drupal modules, and I get the version information inside the .info.yml file of the modules I require with composer require.

I first added the new repository with composer config repositories.drupal composer https://packagist.drupal-composer.org/. After, I can add any modules, for example the Focal Point module with a command like the following.

composer require drupal/focal_point 8.1.*@dev

The command install the module and its dependencies, producing the following output.

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drupal/crop (8.1.0)
    Downloading: 100%

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Installing drupal/focal_point (8.1.0-beta3)
    Downloading: 100%

> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
drupal/crop suggests installing drupal/media_entity (Required by drupal/crop_media_entity)
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

If then I check the content of modules/focal_point/focal_point.info.yml and modules/crop/crop.info.yml, I get the following output.

name: Focal Point
type: module
description: Allows users to specify the focal point of an image for use during cropping.
# core: 8.x
package: Images
# version: VERSION
test_dependencies:
  - crop
dependencies:
  - image
  - crop (>=8.x-1.0-alpha2)

# Information added by Drupal.org packaging script on 2016-09-01
version: '8.x-1.0-beta3'
core: '8.x'
project: 'focal_point'
datestamp: 1472695440

name: Crop API
description: 'Provides storage and API for image crops.'
# core: 8.x
package: Media
type: module
dependencies:
  - image
  - user

# Information added by Drupal.org packaging script on 2016-05-25
version: '8.x-1.0-rc1'
core: '8.x'
project: 'crop'
datestamp: 1464160143

In both the cases, the information added from the Drupal.org packaging script is present for both the modules (the one I directly required, and it's dependency). I am using this method for all the module I need in my site, and I have never had problems with the version strings.
To update the modules, I just run composer update, and Composer updates all the modules with a new version that respects the restriction I set for each module.


Here's a possible solution. In your view, exclude all fields add field 'Global: Custom text'. You may also have to add fields to generate the appropriate path to the user profile.

Then, add the token replacement patterns for the excluded fields. You can either 1) wrap this output in an anchor with the appropriate path /user/[uid] (a field you may have to add, or you may be able to use the user's alias), or 2) in the rewrite section, tick 'Output this field as a link' and specify the path there (also use replacement patterns from UID or the alias).


You can manually edit this limit in the search_api_views module source file.

You find this here in the commerce kickstart bundle:

/profiles/commerce_kickstart/modules/contrib/search_api/contrib/search_api_views/includes/display_facet_block.inc

Then you correct the limit of 10 on line 167 of display_facet_block.inc

$limit = empty($this->view->query->pager->options['items_per_page']) ? 100


Response::$headers is a public property, which means you can access it with $response->headers, where contains an object of the ResponseHeaderBag class or some inherited class of it.

Essentially, it means you can access the headers using either ResponseHeaderBag::all or ResponseHeaderBag::get($key).


hook_user_update() is invoked before saving the user account, not after

Actually, in Drupal 7 user_save() first invokes hook_user_presave(), then saves the user account in the database, and invokes hook_user_update() or hook_user_insert().
It is not possible that hook_user_update() is called before the user account has been saved.
hook_entity_update() and hook_entity_insert() are invoked right after hook_user_update() and hook_user_insert(). Eventual field updates should be executed with those hooks.

// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

// …

if (is_object($account) && !$account->is_new) {
  // ...
  $success = drupal_write_record('users', $account, 'uid');
  if ($success === FALSE) {
    // The query failed - better to abort the save than risk further
    // data loss.
    return FALSE;
  }

  // …

  user_module_invoke('update', $edit, $account, $category);
  module_invoke_all('entity_update', $account, 'user');
}
else {
  // …

  $success = drupal_write_record('users', $account);
  if ($success === FALSE) {
    // On a failed INSERT some other existing user's uid may be returned.
    // We must abort to avoid overwriting their account.
    return FALSE;
  }

  // …

  user_module_invoke('insert', $edit, $account, $category);
  module_invoke_all('entity_insert', $account, 'user');

  // …
}

// …

In Drupal 6, user_save() invokes hook_user('update'), saves the user data in the database, and then invokes hook_user('afer_update'); if the user account didn't exist before, it saves the data in the database, and then invokes hook_user('insert').


Here is a patch that should fix your problem. Comment #10


You could create a custom region in your theme, then include a block with unaltered text that directly makes a call to the Google Maps API. This allows you the most flexibility since you work directly with the API - however this is only practical with a static location. If you are using something like a geo location module to assign destination parameters or other, you will need to adjust this.

EDIT:

in hindsight, depending on your needs, you probably don't need to create a dedicated region in your theme.

To create an unaltered text area (D7):

1) goto admin/config/content/formats

2) 'add text format'

3) Name: unaltered, Roles: Administrator ONLY! - giving others access to this has MAJOR security issues, so make sure it is admin only.

4) Save, and move it to the bottom of the list, Save Changes (this makes sure it's not the default

Get the google maps API address:

1) go here: https://developers.google.com/maps/web/

2) setup a google developer account (all google api's require this - its free).

3) goto Google Maps Embed API on that page

4) read the page, and setup your api call as you want.

5) copy the code

In admin/structure/blocks:

1) 'Add block'

2) title: < none > (with spaces removed) or as desired

3) Body: paste code from google API - adjust the dimensions as desired (width and height as given by the API call)

4) Text format: unaltered

5) save

6) put the block in the appropriate region


Turns out you need a patch. Field was multi-value.
https://www.drupal.org/project/services/issues/2224803


Using 2 code repos, one Acquia and one private gitlab server for Drupal code base tracking

Definitely possible and it's what I do. Acquia provides some documentation  on this. As Kevin mentioned you can do this by setting up two remotes for your local repository clone, one at GitHub/GitLab/Bitbucket, and one at Acquia Cloud.


How to get a drupal path in a modal form?

you want to display node on popup I guess. The modal form itself does not provide node to display on popup. You need create custom module for it and set its template page.

If you are using colorbox there is one module colorbox node which provides you built in setting to display node on popup.

only need to set class="colorbox-node".


How to send system mails in html format (with Swift Mailer)?

My edit to the accepted answer got reverted, so I'll contribute it as a separate answer, for two reasons: 1) several grammatical and formatting errors in the accepted answer make it hard to read and understand and 2) the comments to the accepted answer (and the "Update" section) explain why the proposed solutions do not work. This answer adds an additional working solution, credited to the author of said approach, at the very bottom of the post.
The Swift Mailer Drupal module works in combination with the (contrib) Mail System module.
1. Setup Mail System

Check the settings here: /admin/config/system/mailsystem

Make sure Swift Mailer is set as the Default Mail System > Formatter.

Select the theme you wish to render your HTML emails — typically your front-end theme — where you have the ability implement a custom swiftmailer.html.twig template with any wrapper HTML (eg email header and footer text that appears on all templates) and sub-templates.

Alternatively, under Module specific configuration, add the user module to explicitly use Swift Mailer as the Formatter for the User module. Hint: Leave the key field empty to affect all emails from the specific module. This way, other system or contrib module emails are not affected.

2. Configure Swift Mailer to use HTML for Core User Templates

Swift Mailer lets you choose the HTML format to use from a list of Text Formats you have defined in Drupal on the Message settings page: /admin/config/swiftmailer/messages.
So you could theoretically create a new Text Format yourself, such as "HTML Email", but this setting does not let you output any meaningful HTML because the text format needs the "Display any HTML as plain text" filter activated (see Issue #3122389: Bugs with format conversion).
In short, this option in the UI is a red herring and is only intended for upgrading Plain Text to a basic HTML format, by converting line breaks to
s and URLs like https://example.com to clickable links like https://example.com.

Alternatively, you can create a custom Twig template per module, like swiftmailer--user.html.twig, or per email key, like swiftmailer--user--password-reset.html.twig and replace {{ body }} with your HTML message, however you will not have access to the same Drupal Tokens that are available to the user account email templates in Drupal's admin UI. For a list of all user mail keys, see the $op parameter of _user_mail_notify().

Therefore, the currently known best approach is to enter your custom HTML into the Drupal administrative UI, then use hook_mail_alter to add text/html to the Headers and convert the text to a valid Markup object.

use Drupal\Component\Render\FormattableMarkup;
/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  switch ($message['key']) {

    // User module templates from admin/config/people/accounts
    case 'cancel_confirm':
    case 'password_reset':
    case 'register_admin_created':
    case 'register_no_approval_required':
    case 'register_pending_approval':
    case 'register_pending_approval_admin':
    case 'status_activated':
    case 'status_blocked':
    case 'status_canceled':

    // Contact module templates from admin/structure/contact/manage/sitewide
    case 'page_mail':
    case 'page_copy':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      foreach ($message['body'] as $key => $body) {
        $message['body'][$key] = new FormattableMarkup($body, []);
      }
      break;

  }
}

Hat tip to blog post from flocondetoile.fr for the code snippet.


How to programmatically fetch the results of a view with facet filtering

Kinda old question but i just needed the same thing and here is how i did it.

use Drupal\views\Views;
use Symfony\Component\HttpFoundation\Request;

$view_id = 'VIEWID';
$display_id = 'rest_export_1';
$filters = [
  // Filters results with title `Hello` as expected.
  'field_title' => 'Hello',

  // The programatically executed View ignores
  // the following facet based values for filtering.
  'field_facet' => ['A', 'B'],
];

$view = Views::getView($view_id);
$view->setDisplay($display_id);

// Here comes the part that did the trick for my REST JSON request.
// Create a new request with your filters / url query and set that.
$request = new Request($filters);
$view->setRequest($request);

$view->execute();

//TMP debug the json decoded value
$view_result = \Drupal::service('renderer')->renderRoot($view->render());
$view_json_decode = json_decode($view_result);

The rest export view puts the exposed filter inside the view request so instead of setting the exposedfilters i made a request with the query args and it worked fine.

The documentation is missing a lot so if anyone finds a better way then let me know.


Creating dynamic pages for content-type/taxonomy-term

I think you can do something like this:

Create one page view and give him a path like: %/%
Add contextual filters
Create a module
Implement hook_menu.

..

function test_menu() {
  $items['test/%term_name/%node_type_name'] = array(
    'title' => 'My test page',
    'page callback' => 'test_page_callback',
    'access callback' => TRUE,
    'page arguments' => array(1,2),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function test_page_callback($term_name, $node_type_name) {

  /**
   * here we are getting arguments from _to_arg() functions and processing them to
   * get $tid and $SECOND_ARGUMENT
   */

  return render(views_embed_view('test_veiw', 'test_display', $tid, $SECOND_ARGUMENT));
}

function term_name_to_arg() {
  // return term_name as argument
}

function node_type_name_to_arg() {
// return node_type_name as argument
}


How to remove a term programmatically from entity reference field using entity browser on translation form?

To remove them from the user interface, you would have to empty the items array of 'current'

$form['field_category_terms']['widget']['current']['items'] = [];

This would however only hide them in the user interface, to actually remove them you also have to NULL target_id

$form['field_category_terms']['widget']['target_id']['#default_value'] = '';

If the users are allowed to add new terms during the translation, you'd also need to make sure the emptying of the terms only are done initially, because if not, they would always appear empty since Entity Browser uses AJAX and change the form when you add a new term. Something like:

  if (!$form_state->isProcessingInput()) {
    $form['field_category_terms']['widget']['target_id']['#default_value'] = '';
    $form['field_category_terms']['widget']['current']['items'] = [];
  }


Views - Wrapper Fields in DIV after ROW class

If you start editing your view, on the right side under the advanced options you will find Theme: information. You will see the currently used template files and the candidate files.
My solution would be to overwrite the default template files with your own. That way you could simply add a wrapper around $rows.


Organic Groups - how to display a summary view of members of the group based on a "company" field added to the user profile

I took the default OG Members view and cloned it (keep the original) and changed from user: name to my field user:company - added aggregation - in advanced settings in the other section - then had to change the contextual filter to use the GID from the active node. then played around with the aggregation to get it to work ... overall it does what I needed.

Lesson learned ... use the views you get from adding modules - smart people built them ;-)


As @4k4 commented, I don't think that works.

I'd suggest you either use Page Manager/Panels, which allows to create a page with multiple displays and conditions like based on the user role.

Alternatively, you could create your own controller and return the desired page.

I don't know what you want to do exactly, but yet another option would be to keep two separate pages and redirect authenticated users to the different frontpage. That's similar to how drupal.org works, where you can configure whether your front page should be the default or your dashboard as an authenticated user.


How can I use a replacement pattern in a custom field?

Take a look to \Drupal\views\Plugin\views\field\FieldPluginBase::renderText

/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
  $tokens = $this->getRenderTokens($this->options['text']);
  return [
    '#theme'  => 'custom_button',
    '#target' => $this->options['target'],
    '#class'  => $this->options['class'],
    '#text'   => $this->viewsTokenReplace($this->options['text'], $tokens),
  ];
}


In the form submission of the first page you can copy the values in $form_state['values'] into the session for the current user; the page callback of the other page can then access them.

function mymodule_page1_form_submit($form, &$form_state){
  $_SESSION['mymodule_page1_submission_timestamp'] = time();
  $_SESSION['mymodule_page1_submitted_values'] = $form_state['values'];

  $form_state['redirect'] = 'The path for the second page';
}

function mymodule_page2_view() {
  $delay = 300;
  if (!empty($_SESSION['mymodule_page1_submitted_values']) && !empty($_SESSION['mymodule_page1_submission_timestamp'])) {
    $submitted_data = ($_SESSION['mymodule_page1_submission_timestamp'] > time() - $delay) ? $_SESSION['mymodule_page1_submitted_values'] : array();
    unset($_SESSION['mymodule_page1_submission_timestamp']);
    unset($_SESSION['mymodule_page1_submitted_values']);
  }

  // ...
}

I use $_SESSION['mymodule_page1_submission_timestamp'] just to avoid the second page gets the values submitted on the form present in the first page more than 5 minutes before. If you don't want such restriction, then remove any reference to $delay.

You could also pass the values through the URL, but there is a restriction on the URL length the browsers can handle, and that restriction depends on the browser, as long as I know.


Make multiple templates for site (new one for many pages)

Drupal has flexible theme system. You can create different sections of your site and theme and select dedicated template according to path. This is what I am suggesting you.

e.g. your site has different pages(paths) targeting different sections.

example.com/music                   (page-music.tpl.php)
example.com/artist                  (page-artist.tpl.php)
example.com/artist/profile/%        (page-artist-profile.tpl.php)
example.com/store                   (page-store.tpl.php)


How to get a value from block configuration's form control?

What you need is completely covered in example module: block_example.module

Have a look at following hooks:

block_example_block_configure
block_example_block_save
block_example_block_view


How to limit the results of a view with flagged content to the flagging user only?

ok i understand, you should add contextual filter like given below..

i hope this helps you.


Comment not respecting line breaks (Drupal 7)

When I found this problem it was because the results of the filter were being stripped by another filter.

Go to /admin/config/content/formats and check your filter processing order. The 'Convert line breaks into HTML' should be the last one.


Migration from csv problem (Incorrect string value: '\xAB Nove...')

maybe related to the source file encoding format (try with UTF-8). Check also for string issues (special characters) on the source file.


To find where a specific stylesheet is coming from, scan your Drupal directory for that file's name. This is the easiest way to find it.

To disable a stylesheet, you can either use preprocess hook, or add the following to your theme's .info file:

stylesheets[all][] = css/removed/GOw.css

Just make sure that the file does not exist, and Drupal won't include it.

Hope this helps.


Robust handling of the pager in an Ajax controlled View, when URI is shared with another user?

With Javascript, I could manipulate the # value of the URL without triggering a page reload. Using this, a custom Javascript pager could be implemented, that will override the ?page value with any #page value instead. Unfortunately that would mean loading two images. This way, paging with JS will update the #page value, and this url can then shared and get the intended behavior.


URL paths in optimized CSS sometimes are https instead of http

I don't think the behaviour is random.

These files are regenerated periodically, and the regeneration is mainly going to be triggered by visits to pages. I would guess that the urls in the CSS files get http when the page that triggered the regeneration has http, and https when the page that triggered the regeneration has https.

Prepending the URLs in CSS with the full protocol and domain is not a stock Drupal behaviour, so something in your setup is doing it–probably whatever module you're using to set up the CDN. You don't mention which module you're using for this, so it's difficult to say. I would begin by looking in the module settings.

It's also possible that your CDN service itself rewrites the urls in CSS files. Cloudflare, for example doesn't do this, but does have configurable options that rewrite certain files (such as, e.g., minifying css, js, or html).


How to remove View/edit option of a node in admin menu?

Go to Configuration -> Administration -> Administration Menu.
Under System Tweaks, uncheck Move local tasks into menu.
Flush the cache and clear browser cache.


Drupal Users while developing: Methodology

I would suggest using Features to deploy your changes if you aren't already. That way there shouldn't really ever need to be any database changes going upstream, so this problem will be averted.

Any database changes that do ned to be made can go into hook_update_N functions in your Feature module's .install file

EDIT

In favour of other popular opinions, there is also the Configuration Management module which attempts to backport the CM functionality from D8 back to D7.

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.


How to display entity label using entity reference field checkbox form display

I assume the context_question is your custom entity or coming from a contrib module?

There are two options:

Add label key to context_question entity definition under entity_keys so that Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection pick it up. See Aggregator item for reference.
Add a @EntityReferenceSelection plugin. You have to define one. Check TermSelection for how it is implemented for terms. It looks like this:


Running updatedb fails with UnknownExtensionException error

Drupal can't find the module when it's scanning the codebase. You'll have to debug to figure out why. Run drush eval 'print_r(array_map(function ($ext) { return $ext->subpath; }, \Drupal::service("extension.list.module")->getList()));' to have Drupal dump what modules it can see and try see why it can't find the install location location (file permissions?).


Mink failing to run JavascriptTestBase tests

There's an annoying bug with the Selenium2Driver code with regards to specifying the correct browser. If no capabilities are specified, it uses the defaults:

    public function setDesiredCapabilities($desiredCapabilities = null)
    {
        if (null === $desiredCapabilities) {
            $desiredCapabilities = self::getDefaultCapabilities();
        }

Note in the error it hase browser defaulted to firefox while the browserName is correctly set to chrome:

Capabilities {browser: firefox, browserName: chrome,

In order to workaround this issue, change your capabilities to also specify browser:

<env name="MINK_DRIVER_ARGS_WEBDRIVER" value='["chrome", {"browser": "chrome"}, "http://selenium:4444/wd/hub"]'/>


Yes it is possible.

I have done something similar in Drupal 7 some time ago. Here is how to do it:

Create your View

Create a Fields style View with your required filters and sorting

Add the relationship to the Translations

Add a relationship to the translations: Content translation: Translations
As Translation option choose All
Add a filter Content translation: Language and choose Current user's language

Add the Fields

Add the field Content: Title with no relation and with Link this field to the original piece of content disabled
Add the field Content translation: Language with the Translations relation added before and with Link this field to the original piece of content enabled
In the Format Settings choose Content: Title as Grouping Field

Format the list

The horizontal list of the languages can be achieved by CSS formatting


Webform response: "Illegal information. Data not submitted."

It seems that message is triggered by the _webform_submission_spam_check function. Looking at the code, it seems to check the following regular expression:

'/(b?cc\s?:)|(content\-type:)/i', $to . "\n" . $subject . "\n" . $from . "\n" . $headers

Maybe some of the submissions contain "cc" or "bcc" or "content-type"?


How can I create a customised add/node form in D7?

you may try using Webform module.

Webform is a module that aids in making various one-off forms such as contact forms, surveys, order forms, reservations, CRM requests, and more.
To install the module, download the module and add it to your sites/all/modules directory. Enable it under /admin/build/modules.
You will now have a new node type called "Webform". From there you simply give the webform a title, description, confirmation message, set up email settings and the like.
Finally, you can add several components (think fields). There are several component types available: fieldset, pagebreaks, grid, textarea, textfield, select (checkboxes, pulldown lists), email addresses and more.

Here's the documentation.
Let me know if you need more information.
-------------------- UPDATE ----------------------
To customize the HTML of the form you can copy the file webform-form.tpl.php and copy it into you template.
Inside there is the array $form['submit'] that contains the compontents of the form.
write dsm($form['submit']) and it will print the compontents.
Then you may do something like
<div class="my_class" id="my_id">
<?php print render($form['submit']['YOUR_FIELD']); ?>
</div>

Then you may want to assign this template to that node, so it will be
webform-form-NID.tpl.php


Add the trim limit for the content field what you want.
Add the link to content field in the view and put the display content.


How to use nested select queries in Drupal 7

Since you're going cross-database I think using db_select() could get quite complicated. I might be wrong though, it might just work.

Either way, you could always just run the query directly with db_query():

$sql = '
  select max(cnt) from
  (select COUNT(*) as cnt from Det a,
  dbo.Mem b where a.no=b.no
  group by b.no)';

$count = db_query($sql)->fetchField();


colorbox does not seem to work anymore after upgrade from 7.x-1.6 to 7.x-2.9

i think you need to update the colorbox library too !

right now - the JS lib is not included in the page ...


I forgot the password to the admin account

If the email you used to register the account is still active, or you still have access to it, then the easier way to change the password is using the "Request new password" link that appears in the login block, or the login page.

If you don't have access to the email you used to register it, you could change it in the "users" database table, and then request a new password.

If you don't have access to the database, but Drush is installed, then you can use the following command.

drush user-password <username> --password=<password>

Alternatively, you can use this command, which allows you to login as a user for once; once you are logged in, you can change the password for that account.

drush user-login <username>

The command return a link that can be used in the browser to access the site. If the username is omitted, the link is for the user #1.

If Drush is not installed, then you need to write a PHP file to change the password for the account. For Drupal 7, the following code works.

$account = user_load_by_name($username);
$edit['pass'] = $newpassword;
user_save($account, $edit);

Place the code in a file with extension .php, in the same directory containing the index.php file that comes with Drupal. Replace $username, and $newpassword with the username of the account you need to change the password, and the new password.

The following code work with both Drupal 6, and Drupal 7, but it requires you to know the user ID of the account.

$account = user_load($uid);
$edit['pass'] = $newpassword;
user_save($account, $edit);


If you don't have this button, try to enable the module Update manager.
Maybe this makes the button show .. What backend theme are you using ?

Here's the path to the module installation page: http://localhost/admin/modules/install


Default Billing Information on PayPal site using WPS

Thanks for your helping clues.
I'm using Drupal Commerce V7.x-1.8 with drupal 7.26 and commerce_paypal WPS 7.x-2.3.

I made a custom module named my_module. Code Below :

function my_module_commerce_paypal_wps_order_form_data_alter(&$data, $order) {
  $user = user_load($order->uid);
  $profile_id = $order->commerce_customer_billing['und'][0]['profile_id'];
  $profile = commerce_customer_profile_load($profile_id);

  $data['first_name'] = $profile->commerce_customer_address['und'][0]['first_name'];
  $data['last_name'] = $profile->commerce_customer_address['und'][0]['last_name'];
  $data['address1'] = $profile->commerce_customer_address['und'][0]['thoroughfare'];
  $data['address2'] = $profile->commerce_customer_address['und'][0]['premise'];
  $data['city'] = $profile->commerce_customer_address['und'][0]['locality'];
  $data['zip'] = $profile->commerce_customer_address['und'][0]['postal_code'];
  $data['night_phone_b'] = $profile->commerce_customer_address['und'][0]['phone_number'];
  $data['email'] = $user->mail;

}

Now the customer billing informations are automatically filled up in the Paypal Form.
Notice for phone field : I used "night_phone_b" field for European phone format.
I also hope this helps someone else.


Using existing term reference field vs. creating new ones

Yes it would make sense to have only one field that you attach to multiple content types.

If you're using a MySQL backend then a table is created for every field you create in the UI (it's probably similar for other storage backends). If you create a single field and attach it to several different entity/bundle types then only a single table is created with the values for all entities. Fewer tables is definitely more desirable.

Also if you wanted to query the database for all nodes that are within a certain vocabulary (using EntityFieldQuery or even Views) then the query generated would have two less JOINs to make which is just much better for performance on the whole.

I think it was the intention of the developers that fields be used in this way, there's a complicated mechanism in place for managing different instances of fields and I don't think that logic would need to exist if they weren't supposed to be used like this.


How to modify the commerce price formatter label to match shipping service?

I think this is equivalent - not sure there's a better way than loading all the line items.

function HOOK_commerce_price_formatted_components_alter(&$components, $item, $entity) {
  foreach ($entity->commerce_line_items['und'] as $line) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line['line_item_id']);

    if ($line_item_wrapper->type->value() == "shipping") {
      $shipping_data = $line_item_wrapper->value()->data;
      $service_title = $shipping_data['shipping_service']['title'];
      break;
    }
  }

  if (isset($service_title)) {
    $components['shipping']['title'] = $service_title;
  }
}

(The title is coming from the price component type - maybe one could use hook_commerce_shipping_service_info_alter() to change the price_component to something per shipping service, and set the title in hook_commerce_price_component_type_info(), but that probably isn't any neater.)


Session values are getting populated only when the page is refreshed

It sounds like your problem is how/when the session variables are set (they are not available on the initial form load). You don't mention how this is done.

Some code example and greater details in your question will allow for a more detailed answer.


Group users and display the group on the profile page

Roles have a set of permissions, so they are ideal if you will have a set of users  editing certain types of content,
 like blog posts, and another group of user commenting on the content.
 You can create both new roles and permissions.

Roles: /admin/people/roles
Permissions: /admin/people/permissions

You can also add fields to the users, like a taxonomy where they choose whether they are a dog person or a cat person.

Manage fields: /admin/config/people/accounts/fields
Manage form display: /admin/config/people/accounts/form-display

Then, you can choose which fields will be displayed on the user profile page

Manage display: /admin/config/people/accounts/display


If you're using the private file system, you can make use of hook_file_download, it is normally used for granting access but I don't see why not you can use it for flagging stuff.

See an example of this in Example of hook_file_download

If you're using the public one, it will be way trickier, you're going to need to wrap the download link to react with your custom code, this could be done by replacing the download link like the Public Download Count module does, or providing your own hook_menu callback that is called via ajax to flag the content, but then you depend on whether the user has js enabled or not.


hook_form_FORMID_alter select list default value

Change 'All' to ''. The key should be blank. The default value is not matching the option list.


Programmatically load the page variant being used on path or node object

In order to get the variant being used by the node I was able to retrieve the info inside the array returned by

$node->panelizer->getValue()

And to get the page I used

$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);


How to disabled Drupal builtin "poormanscron" cron when using Ultimate cron?

You don't need to uninstall any module. The setting you are looking for is on admin/config/system/cron/settings/poorman.

Change Launcher to -- Disabled -- from the default Serial, and Poormanscron should not run anymore.

If you disable or uninstall the Ultimate cron module, Drupal shows the equivalent settings in admin/config/system/cron, at the bottom of the page.

In this case, change Run cron every to Never.


Is there any module for picking photos for image field on mobile platforms like iphone

No, you'll need to write an iphone application to do the photo upload (using a web service).

There is an older post with more info.

With Android phones the regular photo upload works, at least that's what I heard from a couple of users.


This is more of a PHP question, I believe, as you use PHP functions to accomplish this.

<?php
  $dob = $submission->data[11]['value'][0];
  $time = strtotime($dob);
  $oracle_format = date('d-m-Y', $time);
  // OR
  // $oracle_format = date('d-m-Y', strtotime($dob));
?>

This uses the functions date() and strtotime()


Is it safe to manually delete the "field_deleted_*" tables and state API data?

Try deleting them cleanly first with drush eval 'field_delete_field("yourfield")' and run cron afterwards.


I think choice is in between EntityQuery and db_select and EntityQuery seems to be a better choice for Entities as it takes care of joining different fields for you.

Reference Link: EntityFieldQuery vs Db_select() -

@Bart says: -

  I think that the main reason prefering EntityFieldQuery over db_select
  is that you don't have to know about the lower-level structure, in
  other words: how stuff is stored in the database. This improves loose
  coupling.

@Berdir comment:-

  This is correct, although it goes even further. The field storage is
  pluggable. The default implementation stores field data in a separate
  table per field in the database, but it can be replaced, there is for
  example an implementation which allows to store field data in MongoDB.
  If you want your code to be portable and not just work on your
  specific site configuration, you must use EntityFieldQuery.


Define the variables in your theme and the pass them as "#variable" = value. E.g. in YOUR_MODULE.module have something like:

function tb_megamenu_theme($existing, $type, $theme, $path) {
  $items['tb_megamenu'] = [
  'template' => 'tb-megamenu',
    'variables' => [
      'menu_name' => NULL,
      'content' => NULL,
      'section' => 'frontend',
      'block_theme' => \Drupal::config('system.theme')->get('default'),
    ],
  ];
}

In your controller use:

$render = [
  '#theme' => 'tb_megamenu',
  '#menu_name' => $this->getMenuName(),
  '#block_theme' => $this->getThemeName(),
  '#content' => $this->getContent(),
];


Using taxonomy terms alias in views contextual filters

Finally my work around this was as it follows:

I created a custom taxonomy vocabulary which has an extra field "human friendly tag".
I changed the name of all the taxonomy terms for being seo-friendly (not spanish accents, nor brackets and so forth).
I use term name for the internal stuff in my view (term names are part of the url). You can see how to get this here as @RobW pointed out.
I use the first field (the "human friendly tag") when content is rendered (in the view). I need to use "rewrite results" options when creating the view.

I hope it is clear enough. :-)


How do I change the default theme with Drush-master

Try this:

drush config-set system.theme default bartik

You might need to clear or rebuild your CSS/JS and theme caches (drush cr).
If the problem still appears, check that it has not been forced in your
settings.php file.

Source: https://www.drupal.org/node/200774


icon_map in PHP annotation instead of layouts.yml

You can do this via the layout alter hook ( hook_layout_alter(&$definitions) ).  The definitions variable is an array of all the defined layouts keyed by the layout machine name.
The value here is a Drupal\Core\Layout\LayoutDefinition object.  This has a setIconMap method.  You can pass this an array of arrays that define the icon.
E.g. if the yml format is:
- [top]
- [first, second]
- [bottom]

the value is something like:
$map = [
  ['top'],
  ['first', 'second'],
  ['bottom']
]


Welcome to stackexchange doug! :)

This is what I believe to be the most popular solution. It's good because it's fairly easy to set up, yet very flexible. You will need the Views module.

Add a textfield to the same bundle (content type) as the one holding your images.
Create a View
Add your link field to the field list, and check "Exclude from display".
Add your image field to the field list, scroll down to rewrite results, check "Output this field as a link", and add the link "token", in the "Link path" field. The list of available tokens are listed further down under "Replacement patterns". .
Save the View, and add it where you want. :)

If you want to know more about Views, you can see a video tutorial series here.


Dropdown Menu with 20+ items gets cut off by a views content rotor

This is an awfully localized question, but I got this to work fine in Chrome and Firefox by adding:

position: relative;
z-index: 1;

to the slideshow block (
) or any of its containers (
,
, etc)


Add #ajax callback to an entity_autocomplete field

You can adjust the behavior with

'#ajax' => array(
  'event' => 'change',

This can be any javascript event. The default for a select is on 'change', for a normal field this is on 'blur'. But you can try any other event.

Reference: https://developer.mozilla.org/en-US/docs/Web/Events


Rules to clear commerce cart on adding new item of a different product type

Found answer to my own question. I discovered the conditional rules module and came up with this rule component for each product type:
{ "rules_empty_cart__consumer_g" : {
    "LABEL" : "Empty cart - consumer g",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "commerce_cart", "commerce_order" ],
    "ON" : { "commerce_cart_product_prepare" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "store_item" } }
    ],
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "commerce_order_contains_product_type" : {
                "commerce_order" : [ "commerce_order" ],
                "product_type" : { "value" : {
                    "product" : "product",
                    "book" : "book",
                    "food" : "food"
                  }
                },
                "operator" : "\u003E=",
                "value" : "1"
              }
            },
            "DO" : [
              { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } },
              { "drupal_message" : { "message" : "cart cleared!" } }
            ]
          }
        ]
      }
    ]
  }
}

What this does is it every time an item is to be added to cart it checks if there at least one item in the cart that is not of the same product-type as the product that is about to be added. If there is, the cart is cleared before the item is added, if not the cart remains unchanged and the new item added to the existing list on the cart.
For this check to happen irrespective of the type, a similar rule is created per product type.


How to offset an EntityFieldQuery when using pager?

First question, you've asked if you can offset the results, without having to set the limit for the total results. Logically it would make sense to be able to set $limit = FALSE, to return all results. But I believe range($offset, $limit) requires you to enter both the offset and limit. A workaround is to enter range(3,9999999999);.

Second question, you've mentioned that the -range() is not working when -pager() is set. It's a known limitation. I would assume you can run a separate query to create a pager, but that would require additional SQL requests.


Price not updating on custom theme template

What you've heard is correct: Drupal Commerce adds classes around product fields that allow the Add to Cart form to target those rendered fields for replacement when attributes are selected. This is why in their absence you won't see prices updated at all.

The simplest way to illustrate it will be to simply look at the HTML on a site with a working theme and your custom theme to see what those classes look like.

The classes exist in the render arrays for these fields, so you simply need to ensure your theme is properly including the HTML element attributes for these rendered fields. Again, for that I'd simply advise you to look at working theme code to see how it's done elsewhere.


Customize Ubercart checkout page CSS when certain products are in cart?

I have two ideas:

1) render the code of the article in the class attribute of the cart div. you can do that "intercepting" the render function in your template.php file.

2) using jquery


Show activities on users' posted content

There's a module called Heartbeat that should achieve what you're looking for.

Here is a quote about it (from the module's project page):

  ... displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.


Limit Taxonomy Term references to special vocabulary

I see two mistake in your code, first ->setSetting('target_type','taxonomy' ) is mistake and try ->setSetting('target_type','taxonomy_term' )  and try to set handler_settings with  setSetting I mean  ->setSetting('handler_settings',['target_bundles'=>['book_cat_agency'=>'book_cat_agency']] ) (although there is a way to set handler_settings in setDisplayOptions  )

and finally try  following

$fields['book_cat'] = BaseFieldDefinition::create('entity_reference')
   ->setLabel(t('Book Category'))
   ->setDescription(t('Book Category Name'))
   ->setSetting('target_type','taxonomy_term' )
   ->setSetting('handler','default' )
   ->setSetting('handler_settings',['target_bundles'=>['book_cat_agency'=>'book_cat_agency']] )
   ->setTranslatable(TRUE)
   ->setDisplayOptions('form', array(
       'type' => 'options_select',
       'weight' => -1,
       'settings' => array(
           'size' => '60',
           'placeholder' => '',
       ),
   ))
   ->setDisplayConfigurable('form', TRUE)
   ->setDisplayConfigurable('view', TRUE);


How can I catch the current node object and make changes into it before it is rendered?

hook_node_view_alter

This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.
If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post_render callback. Alternatively, it could also implement hook_preprocess_node(). See drupal_render() and theme() documentation respectively for details.


Using Ctools, how do I render a managed_file from system form?

Okay, it's not my day today :D

Here's how to do what you were asking:

// Load the managed file. You need this so you can get the URI.
$file = file_load(YOUR_FILE_ID);
// Generate the output.
$output = theme('image', array(
  'alt' => t('Your image alt title'),
  'title' => t('Your image human title'),
  'attributes' => array('src' => $file->uri),
));


Make website visible only to registered users - create invitation system to allow registration

See, the Request Invitation module will likely do your job
For this one, first create a new user role @ admin/people/permissions/roles (something like "Premium Users" or "Special Group" or "Only Friends" or something that makes sense). Then use the Content Access module to only allow people from the above mentioned user role to see particular contents.

Then copy the contents of page.tpl.php into a new file named page--front.tpl.php and start editing. This will theme for the front page only, where you can now add a form for the requests and so on.


Show right node revision for View Draft, View Publised links

Make a clone of the view that workbench itself uses, and use that as a base to work from.


Yes that's wrong, you need to put it inside a hook function.

Which one depends on where you're trying to use it. To add it to a render array, for example a form, you might use

$form['#attached']['library'][] = array('system', 'ui.accordion');


Why does not hook_block_view_MODULE_DELTA_alter work?

That hook is called right before a specific block is rendered. If the block isn't present in the page, the hook is not invoked. Replace that hook with hook_block_view_alter(), and it will get invoked for every block shown in the page.

Bear in mind that Drupal caches the hooks implemented from a module; if you alter the code of an enabled module, Drupal will not know the module has a new hook. Disable the module before editing its code, and re-enable it after editing its code; in that way, Drupal will clear its cache, and notice there is a new hook, using it when necessary.


Limiting nodes returned per group in a view

If I were trying to accomplish this, I'd create multiple views attachments to do this. Then you can limit the number for each easily in the pager settings.


The views module actively queries (and caches) a database table for results; trying to make the results static or somehow retrieving deleted content would be much work fighting against views' design. I'd say if you're already using unpublishing to designate former entrants, you're better off using the View Unpublished module to give roles the ability to see unpublished entrants.


You can check what page you are on by looking at $_GET['q'] (or using the arg() function) so you could base your alter on that.


I have found a working solution for that, even if there might be a more clean solution, at least it works.

In the template.php file of my theme in use I put the function :

  function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'commerce_price') {
    // dpm($vars);
    $price = $vars['element'][0]['#markup'];
    $parts = explode(".",$price);
    $parts[0] = str_replace('HK$', '',$parts[0]);
    $markup = 'HK$'.$parts[0].'.'.$parts[1].'';
    $vars['items'][0]['#markup'] = $markup;
  }
}

Once this saved, a markup on which it is possible to act is generated.
The "per month" par is supplied by a field suffix using Display Suite.
The rest is some easy CSS to style the output.

Another method is possible. At uncommenting the dpm($vars) line in the code above, some candidate template files names for the field are provided.


hope this will help you..

function mymodule_views_pre_render(&$view) {

  if ($view->name == 'view_name') {

    // Here you can do any php you want to get the title you need for your view.

    $view->build_info['title'] = "
My custom title!
";
  }

or by views-view-unformatted--viewmachinename.tpl.php file

 <?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>


IF statement to check if loaded entity is of type

Like @Kevin pointed out, $type was never set. That was helpful.
I believe this works:
if($entity->type == 'course') {
  $entity->some_boolean = 0;
  $entity->content_status = 665;
  $entity->course_number = 3;
  $entity->tag_line = "some other tag line here";
}

If you can improve this, please let me know. Much appreciated.


An easier approach without really coding a lot would be to create your search with Search API and/or Facets.

Facets are designed to expose only options that will return results.

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

While you would have to rebuild the View, it probably is not a huge deal - and you won't have to write a bunch of code every time you expose taxonomy or similar fields as facets.


You van achieve this with hook_field_access (https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_access/7). You can check the date value against current date from the $entity object and then set permissions.


How do I create an instance of an entity with all its fields attached?

for nodes we can do below codes to load all fields and display formatters aplyed on them:

$node = node_load($nid);
field_attach_prepare_view('node', array($node->nid => $node), 'teaser');
$fields = field_attach_view('node', $node, 'teaser');

similar way should be exists for commerce


How do I distinguish menu items without children and display different content in panels or views?

This is an excellent example of a custom Ctools plugin. In this case, our plugin type is "Access". The below is copied from "term_has_parent", and adopted to search for the reverse. It could probably be improved with some more robust error checking.

In Panels, you will get a new "Selection Rule", so that you can distinguish between terms that have children, from those that don't.

<?php
/**
 * Plugins are described by creating a $plugin array which will be used
 * by the system that includes this file.
 */
$plugin = array(
  'title' => t("Taxonomy: term has child(ren)"),
  'description' => t('Control access if a term has children.'),
  'callback' => 'term_has_child_ctools_access_check',
  'default' => array('negate' => 0),
  'summary' => 'term_has_child_ctools_access_summary',
  'required context' => new ctools_context_required(t('Term'), array('taxonomy_term', 'terms')),
);

/**
 * Check for access.
 */
function term_has_child_ctools_access_check($conf, $context) {
  $children = db_select('taxonomy_term_hierarchy', 't')
    ->fields('t')
    ->condition('parent', $context->data->tid)
    ->range(0, 1)
    ->execute()
    ->fetchAssoc();

  return count($children) > 1;
}

/**
 * Provide a summary description based upon the checked terms.
 */
function term_has_child_ctools_access_summary($conf, $context) {
  return 'Returns true if the current term has children';
}

If you don't know how to use a custom Ctools plugin, I suggest that is the topic of another question.


Features are sweet but what about content?

Features are useful to export (and import) configurations, but is not useful for "entities": users, nodes, files, terms, and so on.

A great module to export and import is Node Export


is there supposed to be a default folder in sites/default?

It depends what you mean by 'supposed to'.

Drupal core doesn't place that folder there, no. But that doesn't mean that someone/something else hasn't. You'd have to give us that information, we couldn't possibly know.

What I will say is that no module should be writing to that path unless you've explicitly told it to, and if you have your permissions set up correctly, then the web server won't have been responsible for creating the folder.

Again, though, impossible to say from here.


Turn on php filter module shipped in core, so to get option to add php codes option to set block visibility at the block configuration.

Remember you have to make sure, php code should be appropriate else it will not allow to access the site till you delete the added php codes from database for the block.

Code which might help you

<?php
  if ($_GET['q'] == 'view' && count($_GET) == 1) {
    return TRUE;  // block will be shown
  }
  return FALSE;
?>


If I recall, SecurePages has an easy config to enforce HTTPS for everyone on all paths. Check the README.

You could also ditch SecurePages and force all traffic to HTTPS via .htaccess.


How create a role that only can create users?

Go to admin/people/permissions/roles and create your role. Then go to admin/people/permissions and uncheck all the permission for the new user and check the Administer users permission in the User section:

To uncheck all the permission I can sugest you the use of the Permission Select module.

  Permission Select is a module that allows for quicker editing of role
  permissions on /admin/user/permissions.

And as Pierre Vriens says in his comment:

  "do not grant ANY permissions to authenticated users". Because any
  user with permission to create users is also an authenticated user.


Drupal config error "module.settings" depends on the module that will not be installed after import

This usually happens when the module isn't enabled in core.extension.yml but you are trying to import the config for that module.
It can usually be fixed by adding it to core.extension.yml
E.g.
  dblog: 0

Note that the "zero" indicates the "weight" of the module, and does not indicate a 0/1 enabled/disabled boolean.


How to add slider to show multiple view's product in a slider in commerce site of drupal 7?

you can achieve your requirement using views_slideshow module.

Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View.

News item slideshow (such as the title, image etc).

The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).

Rotate any image, based on any filters you can apply in views.

Hottest new products for any ecommerce drupal site.

Rotate contact links, share links, etc.

Implementation :

Steps:

Enable view slideshow module.

Create a view using existing content type(ex-product).

View format: Slideshow

Add item for slideshow (such as the title, image etc).

For getting Next & Previous link

Goto view slider settings

Enable the controls as text.

It displays 'next','pause' and 'previous' link

Later you change the css as per requirements.


using hook_update to add a new cck field

After hours of searching, I finally found a post by Drewish that solves this.

http://drewish.com/node/118

The key to this is letting drupal core know you want to create a new field instance using

content_field_instance_create()


The missing editor is most likely a bug.  You should see what is being logged in the browser's JS console.

@see https://drupal.org/project/webform/issues/2936147


JSON:API to Migrating Taxonomy References isn't mapping

Entity reference fields need to fill their target_id column

field_photo_category:
  plugin: sub_process
  source: field_photo_category
  process:
    target_id:
       plugin: migration_lookup
       migration: import_drupal_taxonomy_photo_categories
       source: id


Is there a Drupal way to loop over Webform fields in form alter function?

For D7 use element_children:

Identifies the children of an element array, optionally sorted by weight.
The children of a element array are those key/value pairs whose key does not start with a '#'. See drupal_render() for details.

E.g.
foreach (element_children($form['submitted'] as $key) {
    $form['submitted'][$key]['#prefix'] => 'foo',
}

For D8, use the equivalent Element::children in the same manner.


how to see which user has assigned a content_profile content type?

According to the code of the content profile module (I didn't test this) you can use views relations between profile nodes (ordinary cck node types) and users.

I'm not sure whether you have to base your view on the cck node type for the profile or users. But with one of these you should get an option to add the other side as a relation and then use fields of the user and the profile in the same view.


How To Pass Taxonomy Term (Name) to Filtered View (ID) - Drupal 7

I don't think it is possible to pass term name,instead of term id, as value for exposed filter. But if you are fine with passing term id in your second view then while rewriting the output check the replacement patterns available there you will see the term id.

Like if your field name is field_book_taxonomy then in your replacement patterns you will see two patterns like [field_book_taxonomy] and [field_book_taxonomy-tid], choose the later one.


Drupal 7: entity field as single/multivalued based on content type

Shortly, no.

Take a look at project Field instance cardinality and an issue #1029298.

  This currently only works with fields that use options widgets (ie select list or checkboxes), and only allows them to be overridden to be single-valued.

Theoretically, you can create field as multi-valued and limit cardinality for content type X programmatically.


How do I add custom keywords in the URL?

You can alter your paths by using hook_url_*_alter() hooks.
Have a look at hook_url_inbound_alter() and hook_url_outbound_alter().


View Rewrite results Inline CSS for Newletter

I've been looking into this problem myself for several days, and my conclusion after going through the views code is that views is absolutely dead-set on sanitizing certain data (specifically twig template fields for custom field rewriting) not even writing your own templates can fix that.

Ultimately, my work around for this was to use Display Suite to build a custom display for my node type (which lets me use tokens in custom display suite fields) and then telling views setting up views to output Display Suite content instead of Fields.


That's a session encoded string (different from a PHP serialized string). There's no built-in way to decode it directly into a variable, so you'll have to use a custom function.

Here's one nicked from the docs page for session_decode().

function unserializesession( $data ) {
  if(strlen( $data) == 0) {
    return array();
  }

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value ) {
    $offset = $value[1];
    if(!is_null( $lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    }
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;
  }

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}

It works well with the example in your question, returning a nested array of values.


How can I ensure this block is properly cached?

Why not cache it yourself? The Cache API in Drupal 7 is fairly easy to implement and it sounds as if your problem might warrant it. I had this issue with a very expensive function that was used to generate relatively static data and did a quick cache implementation to avoid having to constantly rebuild the query.

Let's say your existing function is something like this

function myfunction() {

   $output = (my calculations and logic);
   return $output;

}

A rough way to wrap this in using cache layer would be

function myfunction($reset = FALSE) {

  static $output;

  //some unique idenitifier for your specific record, ex. content type+nid
  $cache_key = (your logic here)

  if (!isset($output) || $reset) {

      // check whether or not output has already been cached and if so, use it
      if (!$reset && ($cache = cache_get($cache_key)) && !empty($cache->data)) {

        $output = unserialize($cache->data);

  } else {

        $output = (my calculations and logic);

        cache_set($cache_key, serialize($output), 'cache', 3600);

        return $output;

    }
}

The cache_set function is the key to this, here's what each of the parameters is doing:

$cache_key - your unique identifier for you content
$output - the output from your function
'cache' - the specific cache bin you want to use. Most likely, you'll want to use the  default 'cache' bin
3600 - the time in seconds that the item should live before being reset. In this case, this content is set to live for one hour. You can also set it to "CACHE_PERMANENT" to never needing reset or "CACHE_TEMPORARY" to reset the next time the general cache is clear.


Get Username from UID with Preprocess for Template

It's better to use the route instead of the path, where you'll find the already loaded user entity:

if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
  $user = \Drupal::routeMatch()->getParameter('user');
  $username = $user->getUsername();
}


How to add tables relations into custom entities content type?

First, forget about tables. Drupal 8 mostly takes care of that for entities.

Think about data structures instead: entities and fields.

What do you want?

Two separate entities, both possibly extensible with additional fields, maybe different bundles (e.g. product and shipping line items). Then make two entity types, with a reference field from line items to the order.
Simpler, non-extensible line items. Then you can design them as a custom field type and add that as a base field with unlimited cardinality. (In this case, they will be stored in a separate table, but you don't need to know about that for the most part).


How to add a META tag in head conditionally to entity content

It's definitely possible, you could do this using hook_entity_view() for example:

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  if ($type == 'my_entity_type' && $view_mode == 'some_view_mode') {
    // Check the field items.
    if ($items = field_get_items('my_entity_type', $entity, 'field_visibility')) {
      if ($items[0]['value'] == 'private') {
        $element = array(
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'robots',
            'content' => 'noindex',
          ),
        );
        drupal_add_html_head($element, 'robots');
      }
    }
  }
}


There is no alternative, saving an entity is the only supported API.

Saving will only update the configurable field tables if it detects a change, and we plan to implement similar logic for the base tables as well.

But the hooks are still called and there is no supported way to prevent that.


Why is Solr throwing exceptions on unfound text files after insttalling Apache Solr Multilingual config files?

Is the configuration of such files not the purpose of the Apache Solr Multilingual module ?

Seems the answer is 'no'.  I manually created 6 text files per language in my solr config and solr started without complaint.

Each language needs each of these text files:

compoundwords_<lang>.txt
mapping-FoldToASCII_<lang>.txt
mapping-ISOLatin1Accent_<lang>.txt
protwords_<lang>.txt
stopwords_<lang>.txt
synonyms_<lang>.txt

where 'lang' is the Drupal language code which can be confirmed by looking over the schema.xml kicked out by Solr Multilingual Module . for example: 'en', 'es', 'de' ...

I copied the contents of each of said files from the Solr Multilingual Module config. forms


How can I include a dropdown in menu_local_tasks tabs?

For the drop-down menu you need include drop-down JavaScript in the "page callback". See drupal_add_library() function.

And I recommend for you pay attention to "CTools module".

"Drop-Down Menu" Code from CTools module:

  // Show examples of ctools javascript widgets
  $output .= '
' . t('CTools Javascript Widgets') . '
';

  // Create a drop down menu
  $links = array();
  $links[] = array(
    'title' => t('Link 1'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 2'),
    'href' => $_GET['q'],
  );
  $links[] = array(
    'title' => t('Link 3'),
    'href' => $_GET['q'],
  );

  $output .= '
' . t('Drop Down Menu') . '
';
  $output .= theme('ctools_dropdown', array('title' => t('Click to Drop Down'), 'links' => $links));


Why does drush en give differerent results than enabling mymodule in the ui?

One gotcha between the UI and Drush is the user. Drush commands are run as anonymous by default. Where as in the UI you are user with greater rights (normally the admin user).

Some parts of Drupal will check for rights before doing things, node_save is one such place. Depending on how you are creating your roll you may find there is another.

A work around for this is to use the -u flag with Drush.

drush -u 1 en my_module

I can't say for certain that this will fix your issue, but there is a fair chance that it will help.


An Atomic Question about Views Modules and Templates

This is rather strange. The fact that the correct file name is highlighted in the Views theming information section suggests it's set up correctly. However, I'll add some more things to check and see where we end up.

You should also have the views-view--page.tpl.php file in your sub-theme's folder. Strictly speaking, anytime you are overriding a template file with a more specific template file, the default template file should reside in the same directory. So just copy views-view--page.tpl.php to your fusion_my_subtheme/ folder. Then clear your theme registry[1] and try again.

I would also suggest using the Devel Themer module to help figure this out. It will tell you for sure which template file is being used for the View's display.

I usually choose to clear ALL caches instead of just the theme registry. Occasionally I've seen strange problems disappear when I do this.


How to set programmatically multiple arguments for views contextual filters

First you should set this option:
View → Advanced → Your Contextual Filter → More → Allow Multiple Values.
Then when passing array should be with '+', so, your example:

$array = array('3250+32');
$view = views_get_view('myview');
$view->set_display("myblock");
$view->set_arguments($array);
$view->pre_execute();
$view->execute();
$content = $view->render();


To alter or remove the favicon URL Drupal 7 points to by default (not just add another favicon link) try this:

function YOURTHEME_html_head_alter(&$head_elements)
{
  // Search the head elements for the Favicon
  foreach ($head_elements as $key => $element) {
    if (!empty($element['#attributes'])) {
      if (array_key_exists('href', $element['#attributes'])) {
        if (strpos($element['#attributes']['href'], 'misc/favicon.ico') > 0)
        {
          // Change the URL
          $head_elements[$key]['#attributes']['href'] = '/'.drupal_get_path('theme', 'YOURTHEME').'/path/to/favicon.ico';

          // Or, delete the favicon link entirely
          unset($head_elements[$key]);
        }
      }
    }
  }
}


Solr is a server and you must set up the parameters to this server correctly in your site at this address: admin/settings/apachesolr/settings.

Is there any errors in the status report ?


How should I upgrade a customized theme?

You asked "Is there a better way to approach this in the future?".

An alternative to modifying the theme you're basing things on (which I favour) is subthemeing, with which you extend the existing theme by overriding only the aspects you wish to change. This allows you to upgrade the original theme and retain your code separately.

http://drupal.org/node/441088 Quick and Dirty Subthemeing
http://drupal.org/node/225125 Subtheme structure and inheritance

This approach isn't entirely a free pass against maintenance, though.

If a fix is applied to the core theme and you've copied the (previously broken) code to your subtheme, then you'll retain the broken code as an override.
If a change is made to the base theme which your subtheme doesn't account for, you'll need to handle that.

So - you will still need to review updates to the core theme, but this approach (for me) makes the most sense, means I'm maintaining the smallest amount of code, and provides a fairly straightforward way to build on the existing themes Drupal offers.


How to run code after hook_node_delete has completely run?

You may want to look into hook_field_attach_delete().  This runs after all fields have been removed from a node/entity.  So, if all the file fields (and the actual files) have been removed, and all of them in such a node are all in one directory and they are the only files in that directory, removing that directory in this hook should succeed.


How to set up a View in Drupal that shows recent posts relative to post date of node it is on?

No idea if possible in Views, but I created a custom block to achieve this.

function relative_posts_block_info() {
  $blocks['relative_posts'] = array(
    'info' => t('Relative Posts'),
  );

  return $blocks;
}

function relative_posts_block_view($delta = '') {
  switch ($delta) {
    case 'relative_posts':
    $block['subject'] = t('Block Title Goes Here');

    $node = menu_get_object();
    $formatted_date = date('m/d/Y H:i:s', $node->created);
    $start_date = strtotime('+2 weeks', strtotime($formatted_date));
    $end_date = strtotime('-2 weeks', strtotime($formatted_date));

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'story')
    ->fieldCondition('taxonomy_vocabulary_1', 'tid', $node->taxonomy_vocabulary_1['und'][0]['tid'])
    ->propertyCondition('created', array($end_date, $start_date), 'BETWEEN')
    ->propertyOrderBy("created", "DESC")
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->execute();

   $block['content'] = '
';

  foreach($entities['node'] as $obj) {
  $node = node_load($obj->nid);
    $block['content'] .= '
' . l($node->title, "node/" . $node->nid) . '
';
  }
  $block['content'] .= '
';

   break;
 }

 return $block;
}


My first reaction would be to create 10 roles (Level 0 to 9) and to restrict access to the pages using Content Access to control access to the pages by role. Then use Rules to assign roles based on the tasks you set out in the learning game.


I had a similar issue, I just reset and added to the PHP limits in my configuration. After that, worked like a charm.


Try the below module.

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

Install the module and Add filter in view by selecting(content translation:select translation) field

And select this option : use current language ; if not available use original language


I've found a solution myself. Seems after the ajax callback the attach function is called again, so I surrounded by a jQuery .once() method:

(function($){

  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      $('#my_div', context).once('my_div', function () {
        var elem_settings = {};
        elem_settings.url = '/my_module_ajax_callback';
        elem_settings.event = 'load';
        elem_settings.keypress = false;
        elem_settings.prevent = false;

        var base = 'myModule';
        var ajax = new Drupal.ajax(base, this, elem_settings);
        Drupal.ajax[base] = ajax;

        $(this).trigger('load');
      });
    }
  }

})(jQuery);

This prevents calling the ajax once and over again.

https://drupal.org/node/756722#jquery-once

https://drupal.org/node/2192041


Is there a way to manage public API documentation?

So far as I know for community driven modules only the Services module has support to autogenerate API documentation via the Services Documention module. If you've been the D7 public API without using Services ... then you may be out of luck.

  The Services Documentation module generates API documentation for your
  site’s Services resources. Most of the documentation is generated
  automatically, using the resource information provided by Services.
  However, this module provides you with the ability to easily extend
  that documentation.

  We make the following assumptions about your usage of the Services
  module:

  You are providing an API to a third party, which allows them to access
  your data via Services.
  You would like to provide a page to API
  consumers that documents your API endpoints, resources, etc.

  Documentation will be made available on your Drupal site at
  /developers.
  It will be organized by API version (arbitrarily defined
  by you), and subsequently displayed hierarchically according to
  resource, method type, method name, arguments, etc.


modify submit on user login so that only admins can log in through this route

You are getting this because you did not include the use statement at the top of your file:

use Drupal\Core\Form\FormStateInterface;

function xxx_form_alter(&$form, FormStateInterface $form_state, $form_id) {

 if ($form_id=='user_login_form') {

    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

You can use the full path, but it is preferred for developers to do use statements.


How to count the children (elements) inside a fieldgroup?

If you use the following code you will see the value that you need.

/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
   //you need the devel module to use dpm() function
  //My field group name is group_g2
  dpm(count($form['#groups']['group_g2']->children));
}

Is easy to track values if you use the Devel and Search Krumo modules


How to access session variables in Twig template?

You can inject new variables into templates by using the appropriate preprocess hook in your theme:

function mytheme_preprocess_page(&$variables) {
  // code to get value...
  $variables['myvariable'] = $value;
}

Then in the corresponding template:

{{ myvariable }}

You might have caching issues with this though.


Unexpected class in ControllerResolver.php on line 151

My localhost is running PHP 5.5.9. I hope this is not the problem because there won't be anything I can do about it.

Well there is something you can do - change your hosting provider :)

The error is indeed caused by your version of PHP - it's too old. It doesn't understand the newer method of class name resolution, introduced in 5.5. A quick search through core reveals 350+ uses, and I think there is/was an issue around somewhere to convert any uses of static strings as class names to the new way, so it's not something you could realistically work around with patches.

The PHP requirements do list 5.5.9 as a minimum version (until Drupal 8.7.0), so trying to install on anything lower than that is doomed to failure unfortunately.


Check if the connection to the database is available

is there any method to check if the connection is available or not?

If you mean class method, then no, because it wouldn’t be necessary. You can simply catch the exception, which will tell you immediately that the connection was not successful:
try {
  // Code using a database connection
} catch (ConnectionNotDefinedException $e) {
  // No database for you
}


Depending on your project and goals there are a few solutions. Drupal 8 core itself generates very little markup, the field markup is now coming from a theme, and the markup from those base themes is much lighter-weight than D7's core. To get started you may want to review the new theme guide, and MortonDK's session from DrupalCon New Orleans.

Given the control you seem to be seeking, you should probably create a theme that's based on Stable (which is the default if you don't set a base theme). Then enable theme debugging, and as you find templates you don't like the output of, copy them from core/themes/stable/templates/... into your theme's templates folder. If you explore either stable or classy you'll see a variety of field templates in the field directory, and you can target them on a case-by-case basis in your theme as needed (theme debug will provide you the name suggestions you need to create the properly targeted file).

Some people are copying the entire stable theme so they have all the templates on hand from the start. If you did that you may also want to set the base theme to false so stable is disabled entirely.

You can also use the hook_theme_suggestions_field_alter() and hook_preprocess_field() in your theme's .theme file to make changes before reaching the twig files.  If you use the Drupal console to generate your theme, the boilerplate code will come with a large collection of the preprocess functions already defined.


How do I use an image as term reference in Drupal 7 and Commerce Kickstart?

[Acknowledgement: The solution given in comments to self by Saurav works.  Since Saurav hasn't been seen in nearly a year, and comments are ephemeral at SE, I've taken the liberty of expanding the solution suggested in these comments into a full answer, so that the question and answer shall not be deleted as "abandoned" as defined on SE.]

First, install and enable the Commerce Fancy Attributes module.

Then, follow the steps suggested under "Example usage" on the Commerce Fancy Attributes project page, but instead of adding a text field, add an image field for Vocabulary and add the image you want to display:

Create an Image vocabulary. Add an image field that shall hold the images you want to use.
Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the Image field (with the label hidden).
Create several terms with images associated. Use the image small icon size so that the display wont be distorted.
Add an Image taxonomy_term_reference field to a product type.
When you add the Image field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms". For the "Attribute selection widget", and choose the type "Rendered term".

Example:


How can I log the flags users put, then auto unflag them?

The Log

Userpoints transactions are automatically "logged" in that Views can display them with all required data. So if I understand the question correctly, flags is irrelevant here in terms of logging as you just want the userpoints transactions.

Create a "userpoints transactions" view.. Not "content" or "user".

Add a relationship for Userpoints Transactions: User
Add fields for
(Users) User: Uid (Uid),
Userpoints Transactions: Timestamp (Timestamp),
Userpoints Transactions: Points (Points) and
Userpoints Transactions: Entity ID (Entity ID) (according to your link, this should be the node id)
If you have more than one category of userpoints, you can add a filter for Userpoints Transactions: Category

Automatic Unflag

It sounds like in your link, Business Rule 2: Unflag an item is unneeded in your case? I'd just change this to a rule where the the flag is unflagged and then redirect to the node / page if needed. I'm not really sure what the requirements are here.


How to change relative path in hyperlinks?

You may need to:

Check the setting for RewriteBase in .htaccess (e.g make RewriteBase /)
Check the $base_url setting is correct (Should be automatic in D8).
Clear all caches ( Admin > Config > Development > Performance > Clear cache )

If you have inline links in body content with incorrect URLs, that's a different story, but the above may help with the standard stuff.


Metatag does support custom tags by implementing hook_metatag_metatags_view_alter(). See the following hook implementation to add the Open Graph video:duration metatag from a custom entity:

/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 */
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $entity = mycustomentity_load(someid);
    $duration = $entity->duration;
    $output['video:duration']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#theme' => 'metatag_opengraph',
        '#tag' => 'meta',
        '#id' => 'video:duration',
        '#name' => 'video:duration',
        '#value' => $duration,
      ),
      'video:duration',
    );
  }
}


Download a File Outside of Web Directory

Drupal 6 doesn't support having both private and public files enabled, but there are some modules that provide this, for example http://drupal.org/project/private_download.

If that modules doesn't do what you need, you can also write your own, see file_download() for inspiration. This is the page callback that serves private files through PHP by checking access with hook_file_download().


How to properly add multiple form elements in a loop?

Could you do something like the following:

$form['openingdiv'] = array(
  '#markup' => '<div>'
);

//Do all your foreach stuff here

$form['closingdiv'] = array(
  '#markup' => '</div>'
);

(Sorry it's a bit simple..I'm tired :-p)


How can I rebuild an image field with values in an Ajax callback?

You cannot alter the form in the Ajax callback. Instead, you must put a check in your form if an Ajax action is triggered and if so, set the default value.
I did this once in D7 and managed to get it to work by doing the following:

Give the Ajax button a name attribute.
Somewhere in the form, check if $form_state['input']['_triggering_element_name'] is set and when it matches the name of the Ajax button, alter the $form.

In D8, I think you can get the clicked button with $form_state->getTriggeringElement().


How update programmatically node entity with empty field_image?

i got it in the update :

i set my image_field in the update:

  $nodeEntityUpdate = \Drupal::entityTypeManager()
                    ->getStorage('node')
                    ->load(273);

     $nodeEntityUpdate->title="blabla";
     $nodeEntityUpdate->field_image_video =array();
     $nodeEntityUpdate->save();

I try to set this field in the create, but that change nothing.

As i can see, we need to set image field in the update if she is empty at the creation.


How do I insert site information data into another table?

You can use a hook_form_alter to add a submit function to the form, see http://drupal.org/node/222158 (for D6 but should be the same for D7).

In your new submit function you can do whatever you want...

You can query other database following this doc http://drupal.org/node/18429

  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));


How can I translate the field group description?

As far as I know there is no proper UI for this yet, but field groups are config, so you should be able to translate all strings by creating/editing translated versions of those config files.

First, export your current config, e.g. drush config:export

Then, in your config/sync directory look for files like core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml. In those files you will see a structure like

langcode: ISO2CODE
status: true
depenencies:
  config:
    - ...
third_party_settings:
  field_group:
    GROUP_ID:
      children:
        - field_foo
        - field_bar
      label: MY_GROUP_LABEL
      format_settings:
        description: 'MY DESCRIPTION'
...some more stuff...

The third_party_settings/field_group contains your group labels in your primary language. To translate a label, create a file language/LANGCODE/core.entity_form_display.ENTITY.BUNDLE.FORMMODE.yml below your config/sync directory.

This file must contain the same structure as the one in the main config file, but remove everything that is not translateable:

third_party_settings:
  field_group:
    GROUP_ID:
      label: MY_TRANSLATED_LABEL
      format_settings:
        description: 'MY TRANSLATED DESCRIPTION'

Finally, reimport the config with the translated labels, e.g. drush config:import


Drupal 6 not playing nice with jquery 1.11.1

I would comment this, but I'm new to drupal stack exchange. Try wrapping this method around your javascript/jquery:

(function ($){
   $(document).ready(function(){
      //code here
   });
})(jQuery);

Sometimes the $ symbol alias for jQuery causes conflict.

Or you can replace all $ symbols with jQuery and see if that works.


$ is not a function but jQuery is loaded when adding JavaScript to a custom theme

The Drupal js documentation states

  Note: Since Drupal uses jQuery.noConflict() and only loads JavaScript
  files when required, to use jQuery and the $ shortcode for jQuery you
  must include jQuery and Drupal as dependencies in the library
  definition in your MODULE.libraries.yml and add a wrapper around your
  function.

You should also use behaviors instead of document.ready() which is stated earlier in the above documentation.

  However with Drupal there is an alternate better method [to document.ready()]; using the
  functionality of Drupal.behaviors and once(). If used properly this
  will ensure that your code runs both on normal page loads and when
  data is loaded by AJAX (or BigPipe!) - but not jQuery methods like
  load() which should be avoided as Drupal behaviors will fail to load
  for loading functions other than ajax().

So your snippet should look like:

(function ($, Drupal) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function (context, settings) {
      $(window).once().on('load scroll', function () {
        // ...
      });
    }
  };
})(jQuery, Drupal);

If your selector is something other than window, e.g. a class, you should update it to be something like $('.my-class', context).once().etc. Passing context like this ensures that your js only fires if the element exists in the currently being loaded context, i.e. if a small chunk of the page is loaded via ajax context will only contain that small chunk of the page. .once() ensures the js will only be added to the element once. It will prevent scenarios where you single click an element but it acts as though you double or triple clicked it. Here is the documentation for .once().


How do you change rules settings on the fly?

There are likely several ways of peeling the proverbial potato, depending on what you're actually trying to do:

See if the rule's callback function has some sort of hooks to allow you to change the data there. This is the easiest way to do anything and the least invasive.
Implement hook_rules_config_execute(). This hook gets called during the invocation of the rule and it appears to give you a chance to modify the rule before everything gets executed.

Not generally recommended but also possible:

Alter the rule's callback to call a new custom callback which wraps or replaces the original function and sets the configuration that you want.


Update a field without changing the node

Let's try this code:

function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->set('FIELE_NAME', 'FIELD_VALUE');
}

OR

use Drupal\node\NodeInterface;

function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';
  }
}


The function theme_field_multiple_value_form($variables) is used (by default) to generate the HTML for the multi-value field. In this function the 'Add another item' button is hardcoded after the table:

$output = '
';
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => $table_id, 'class' => array('field-multiple-table'))));
$output .= $element['#description'] ? '
' . $element['#description'] . '
' : '';
$output .= '
' . drupal_render($add_more_button) . '
';
$output .= '
';

So, what you could do is override the theme function, and print the rendering of '$add_more_button' before the rendering of the table.

As a side note: if you want to override the theme function using a custom module, you could use hook_theme_registry_alter(&$theme_registry) and set $theme_registry['field_multiple_value_form']['function'] to your customized "theme" function.


Panels creates different pane number for any mini-panel inside a panel-node

I recommend using the pane configuration itself under CSS Properties to provide semantic class names for each pane. Create some sensible defaults for .panel-pane and extend it by adding classes. Eg users or themed-list list-striped. If necessary extend the concept using CSS ID's. But I think that's taking it a little far.

If that isn't enough then sometimes I create a custom panel layout with additional wrappers, classes and regions.


Expose a computed field (or external data) to Views

I found answser on this site:
http://barcelona2012.drupaldays.org/sessions/displaying-external-data-fly-views-and-ctools

This simple module give a clear example on how to expose external data (webservice) to a views.


How to set variables in an installation profile?

You should be able to set these in the .install file in your profile. I've struggled with this well, and the .install seems to be the best way to do it.

<?php
/**
 * Implements hook_install().
 *
 * Performs actions to set up the site for this profile.
 *
 * @see system_install()
 */
function customProfile_install() {
  /*
    Other cool functions...
   */

  variable_set('site_403','<front>');
  // etc....
}


The latest dev releases of Drush (both 8.x-6.x and 7.x-5.x) now provide a better error message when attempting to select a specific cache type (e.g. css-js) without first selecting a working Drupal site.  c.f. http://drupal.org/node/1954552

Note also that when selecting a Drupal site, cd /path/to/drupal/root only works if settings.php is stored in a directory called "default".  Otherwise, you will need to instead cd /path/to/drupal/root/sites/mysite.com before using drush cc css-js.  You can also use the --root and --uri parameters, e.g. drush --root=/path/to/drupal/root --uri=http://mysite.com cc css-js


Is there a built-in "None of the above" checkbox option in webform? and how to create one?

This code was fine but wasn't working due to iCheck enabled and then checkboxes "aren't" cleared when the "None of the above" is checked although the counting of checked ones was updating correctly (actually the checked state IS cleared but their iCheck-added class is not and that's why their apparent checked state keeps looking as checked). I'll try find a fix to keep iCheck and make it work with maybe later but for now the following works as expected.

So for anyone that may need this.
Create a single checkbox element after the one with multi checkboxes and call it "None of the above" and give it an element custom css ( I called it 'nota' ) to use in the jQuery code to toggle checked status between the 'nota' and all other checkboxes.

 $("input.mywfq).change(function() {
 $("input.nota").not(this).prop('checked', false);
  });

$("input.nota).on('change', function() {
$("input.mywfq").not(this).prop('checked', false);
 });

IMPORTANT: make sure iCheck is set to "none" for this element in case its enabled for the form by default.


Is there a way to pass selected date from date_popup to another view in URL?

Definitely. When you expose a filter, it listens for a specific $_GET ID in the URL. This ID can be set by expanding the "More" settings of the particular filter item and entering/modifying the string in the "Filter identifier" field.

In your case, you'd copy the first View's filter identifier and paste it into the second View's filter identifier, thus allowing both of them to use the same item in the URL.