How to make certain nodes available to anonymous users?

Just add a field to your nodes, similar to the "checkbox" as described in the question "How to allow users to post content and easily overrule its default access settings?". That field is used when creating a node, to indicate if the node should be viewable by anonymous users also (the default probably being "no").

With that, you could use the Rules module and the Content Access module to implement what you're looking for, similar to what I described in my answer to that same question mentioned above.

This approach should work for brand new nodes being created, while it should also work if you add such field to existing nodes. Though you'd have to experiment a bit to see which Rules "Event" is the bet fit in your case (I'd assume that node create and/or node update is what you'd need).

If you only want "some of those data" to be available to anonymous users, then you may want to add the Field Permissions module also (so that only the relevant fields can be viewed by anonymous users.

Video tutorials

If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters.


If the part of the form you're altering doesn't exist when you're altering it (if it's put there by some other form-altering module) OR if some other module is altering the form after you and wiping out what you're doing then you can indeed have a module weight problem. The way to find out is to put a dsm() (see devel module) in your code and see what the form looks like before your alter. Or use a debugger of course (recommended!)


Calendar: How to add additional month specific calendar views

A view of the calendar should have previous and next buttons to link to views of the previous and next months. each of these have a specific url that you can reference or use if you need to access them other than through the buttons.


Regex field validation producing false (?) negative

When using the PCRE validator you need to add delimiters to your regular expression. For example:

/^63[8-9]\d{9}$/


How to add Clear button for views exposed filter?

Go to you view and Exposed form style settings. (You can find it right side Advanced settings of the view)

and check the 'Include reset button' option . You can also change the Reset button label. Find below.


send REQUEST_URI with header location redirect via settings.php

While it's technically possible to use Drupal contrib to perform the redirect, it's faster and more efficient to redirect without having to fully bootstrap your web application.

For web only actions, like redirects, check for the existence of $_SERVER['PANTHEON_ENVIRONMENT'] - if it exists, it will contain a string with the current environment (dev, test or live).

To perform redirection for the pattern you've supplied, make sure to only match for it at the beginning of the URI in order to avoid an infinite loop problem:

// Pantheon - web only.
if (isset($_SERVER['PANTHEON_ENVIRONMENT'])) {
    // Check if you only want redirection from the live web environment.
    if ($_SERVER['PANTHEON_ENVIRONMENT'] == 'live') {
        if (preg_match('/^\/article\/[0-9]?[0-9]\/[0-9]?[0-9]\/[aA-zZ].+/', $_SERVER['REQUEST_URI'])) {
            header('HTTP/1.0 301 Moved Permanently');
            header('Location: http://answers3x-ec-core-community.gotpantheon.com/catchall/?dest=' . $_SERVER["REQUEST_URI"]);
            exit();
        }
    }
}

Sources:

Configuring settings.php

PHP preg_match() Examples

preg_match


How to make a case sensitive entity query?

Like you already said, I think you should set case_sensitive to true in the field settings, like here. This can also be set in the config.
When digging in the code, I found that the condition function at some point leads to translateCondition which checks if a field is case sensitive and automatically applies the binary option to the sql query.


Modules or install profile for scholarly peer review

Depending on what you would like to do, there are two potential approaches.

On the simple end, you have fields on content types that only certain roles can edit.  For example, you can have a field called vetted and two roles, author and expert.  When an author makes a new node, vetted would get set to some default value, like not verified.  Your expert users can then read and review the nodes, and sets the vetted field as appropriate, say verified or needs further review.

One the more complex end, you can use workflow.  Two modules that do this are Workflow and Workbench.  With this, you can set up just about any editorial review process that you want.  Both can also be combined with Drupal actions to occur on state transitions.  Just keep in mind that workflow can be a pain to set up, and often there are real work scenarios that don't always work into rigid workflow rules.

As for existing systems, Open Atrium may potentially fit the bill.  It is more designed for team collaboration, but based on what clients have said, it may work for something more conference oriented.


Including your versions of Drupal core and Views module might be helpful.

Any chance you're using the Global Redirect module? I had the same problem when I took a dev site live (Drupal 7.26, Views 7.x-3.7 and 7.x-3.7+22-dev, Global Redirect 7.x-1.5), and this patch in globalredirect.module addressed the issue.

https://drupal.org/node/1789546


How to remove marker from openlayers map

Finally I managed to deal with it. In case someone else needs the answer:

you choose the selection tool (the one with the cross)
click on a point and press DEL


How to get list of module folders which can be deleted safely?

Use this:

drush pmi --fields=type,project,title,status,path --format=table|sort

This gives you a module list with five columns:

First is the type of project: module or theme.
Second one is the module project, for exampe views, logintoboggan, admin_menu, etc.
The third one is the installation status: enabled (in use), disabled (not in use but install info in DB) and not installed (it hasn't been installed yet or it have been already uninstalled).
Fourth column is module name. A module downloaded from drupal.org can have several modules inside (the downloaded module is the project and the inside modules are the real modules).
The fifth column is the path to the module.

With this information you can safely remove every project (second column) that all of its modules are in 'not installed' state.

For example, see this fragment list:

module  job_scheduler  Job Scheduler                enabled        sites/all/modules/contrib/job_scheduler
module  job_scheduler  Job Scheduler Trigger        not installed  sites/all/modules/contrib/job_scheduler/modules/job_scheduler_trigger
module  jquery_update  jQuery Update                enabled        sites/all/modules/contrib/jquery_update
module  l10n_client    Localization client          enabled        sites/all/modules/contrib/l10n_client
module  l10n_update    Localization update          enabled        sites/all/modules/contrib/l10n_update
module  languageicons  Language Icons               enabled        sites/all/modules/contrib/languageicons
module  ldap           LDAP Authentication          not installed  sites/all/modules/contrib/ldap/ldap_authentication
module  ldap           LDAP Authorization - Roles   not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_drupal_role
module  ldap           LDAP Authorization           not installed  sites/all/modules/contrib/ldap/ldap_authorization
module  ldap           LDAP Authorization - OG      not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_og
module  ldap           LDAP Feeds                   not installed  sites/all/modules/contrib/ldap/ldap_feeds
module  ldap           LDAP Help                    not installed  sites/all/modules/contrib/ldap/ldap_help
module  ldap           LDAP Query                   not installed  sites/all/modules/contrib/ldap/ldap_query
module  ldap           LDAP Servers                 not installed  sites/all/modules/contrib/ldap/ldap_servers
module  ldap           LDAP SSO                     not installed  sites/all/modules/contrib/ldap/ldap_sso
module  ldap           LDAP Test Module             not installed  sites/all/modules/contrib/ldap/ldap_test
module  ldap           LDAP User Module             not installed  sites/all/modules/contrib/ldap/ldap_user
module  ldap           LDAP Views                   not installed  sites/all/modules/contrib/ldap/ldap_views
module  libraries      Libraries                    enabled        sites/all/modules/contrib/libraries

You can safely remove the ldap module because all modules are not installed but not job scheduler because one of its modules is enabled.


you can use menu_tree to override your menu :

try this code in your template.php :

function THEMENAME_menu_tree__MACHINENAME($variables) {
$menuTree = menu_build_tree('MACHINENAME');
$output = '
';
foreach ($menuTree as $item)
{
    $output .= '
' . $hasSub;
    if (count($item['below']) > 0)
    {
        $output .= '
';

        foreach ($item['below'] as $subItem)
        {
          $output .= '
' . $subItem['link']['link_title'] . '
';
        }
        $output .= '
';
    }
    $output .= '
';
}
$output .= '
';
return $output;
}


Webform confirmation message alternate source

You could use an approach similar to that outlined here: http://drupal.org/node/1245298

Steps:

Use hook_menu to create your confirmation page path
Set confirmation page in webform ( e.g path is confirmation/%nid/%sid to pass parameters )
Load relevant webform and/or submission in menu callback
Display confirmation message as required.


What I suggest you do is use Token filter instead of depending on PHP in fields. Tokens look like [node:field_names], and can help you achieve putting one field value inside another.

The php module depends on bad judgement for a reason, so I will skip trying to help you hurt yourself.


How can I understand when a node is being edited or viewed?

In this case you'd want to look at parts of the url. The easiest way to do that would be passing in additional classes from a preprocess function in the .theme file, and by looking at the URL path:

$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

if ($path_args[0] == 'node' && $path_args[2] == 'edit') {
  // add classes
}

This would be similar to using the arg() function from previous versions.


Within your subtheme settings drill down to the specific region you have problems with and make sure the prefix and suffix settings are correct.


Looking for an entityreference widget that allows to preselect an entity bundle

This module does it: Entity Reference Dynamic Select
https://www.drupal.org/project/entityreference_dynamicselect_widget


Entity types can't be generically deleted. First of all, node is entity type and can't be deleted using node_type_delete. You can only delete content type - and that's a bundle of entity called node.

To delete bundles that belongs to other modules, module providing entity type needs to provide drush command to delete bundle. You will find that command in module's documentation. And to remove entity type altogether, you need to disable and uninstall module that provides said entity type.

An Introduction to Entities may be a good read for you now. I advise caution, because it's status is "Needs technical review", but it covers basics nicely.


You're already using it, default text-only shows up when there is no other choice.

If you add another format: ie: "test", now you will see in the drop down CKEditor and test.

Also, you probably did not select CKeditor as your text editor. Did you enable the CKeditor module?

I highly recommend not using minimal installation. I just tried it and a lot of the modules are disabled, just figuring this stuff out it's quite the headache.

Normal installation is the way to go IMO.


Cannot see user_stats module logs in drupal site

Apart from some pages available under admin/reports/ip_tracking, which are visible when the Views module is enabled, and the "Track IP addresses" option is enabled on admin/settings/user_stats, the module doesn't show those values. You need to do one of the following:

Install the Advanced Forum module
Use user_stats_get_stats() in a template file

Reference

The module's README file (Drupal 7)
The module's README file (Drupal 6)


You could try with the distinct() method for dynamic queries and see how it goes with your query.

There is an example to follow on the taxonomy module of the Drupal core, on the following line:

$node_types = db_select($revision_name)
->distinct()
->fields($revision_name, array('bundle'))
->execute()
->fetchCol();


500 error: Output filter: Response body too large

ModSecurity is an Apache module (a Web Application Firewall) that protects sites from i.e SQL injectiosn, XSS attacks, prevents php shell execution and so on. You must contact your hoster and let them know because they need to change modsec rules maybe.


Proper way to delete Images uploaded in Image fields

If you want to make sure that the image files are definitely deleted (regardless of whether or not another part of the system has declared a vested interest in that file), what you're doing looks spot on to me.

There's already a function run by core on cron (system_cron() specifically) that deletes files marked as  FILE_STATUS_TEMPORARY in the file_managed table, but that function consults the file_usage table and doesn't delete if the file is reported as being in use (which it will be if the field values haven't been removed from the entity yet).

Passing TRUE as the second parameter to file_delete() like you're currently doing is the cleanest way to force the deletion (any records in file_usage are also cleaned up so there's no stale data).

The image derivatives will be deleted automatically, as the image module implements hook_file_delete() and flushes the image cache for the file URI (see image_file_delete()).

The deleted column in the field tables is just there to mark the fields for deletion at a later date (I imagine so the subsequent page load isn't affected if there's a lot of data to delete). There are identical columns in the field_config and field_config_instance tables for the same reason.

The field module purges any data marked for deletion in the cron run (field_cron()).


Where to start with creating the theme for selling?

Themeforest audience is mostly end users. So, it does not matter what base theme you use as long as it makes you more productive.

That said, unlike Wordpress where you just upload the theme files zip, you will have to create your own distribution with the latest stable Drupal core, the set of contrib modules you want to theme, the base theme(if you are using one) along with your theme files and assets.

I suggest you start with a base theme of your choice rather than roll out from scratch. Its a huge time saver and most base themes come with sensible defaults, especially Omega 4.


How can I create an excerpt for each of a node's taxonomy terms?

This is an interesting feature. I have never seen a  module which does it.

If you look at the Open Calais module, you can see some custom extensions to the way taxonomy works. While it doesn't do what you want precisely it may be a  good guide for you.

In short, you can assign meta data to a node-term relationship which contains your excerpt. It would require a custom module and a fair amount of coding.


Where is the "Send mail to all users" action?

Yes it is normal that you do NOT see "Send mail to all users", because there is no such Rules Action in D8 (nor in D7). In D7 there is a Rules Action like "Send an eMail to all users of a selected role", but that one is not (or not yet?) available in D8.

However, within group "System", there is the Rules Action "Send eMail". If you  use that one, with "Send to", you can specify 1 eMail address per line. So if you enter the eMail address for each user on a single line, you have a kind of work around for what you're trying to do.

What you probably want to do later on (when the Rules module is more mature), is to use some type list of all your users, and use that list in combination with a "loop" (a typical Rules Action). If this was a D7 question, you could use the Views Rules module to create a view of all your users, and use that for such list.

With that, either you have to be patient a bit, or use the work around suggested above ...


Captcha doesn't come out in my multiform webform

admin forms is not the same as webforms. You need to manually add the webform to the captcha settings.

Go to admin/config/people/captcha/captcha/settings in the blank text box under "Form Protection" enter the form_id of the webform and save the configuration. Go to the webform page and you should be able to see the captcha there.

To quickly find the form_id of the webform, take the node id and append it to "webform_client_form_", for example if the node id is 3 your webform form_id will be "webform_client_form_3". If this is not your case, you can always use firebug to inspect the hidden form_id field.


How to embedding Comment form for each individual item in drupal's view?

In Drupal 7, function comment_form() is expecting an object parameter instead of array. This code should work for you:

$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);


Call to undefined function db_set_active()

The 2 things that come to mind: your installation is  not bootstrapping properly (improperly configured .htaccess or settings.php) , or you installation is corrupt.

I would recheck the apache logs, watchdog logs to see if any errors are mentionned, if all fails I would see if the application works with this module disabled, because this function is defined in core on line 2519 in includes/database/database.inc and should be available from all your custom module code.

Hope this helps, cheers!


Change Workbench state from Draft to Published programatically

There are two solutions which I have found will work:

The First:

$nid = 1234;
$node = node_load($nid);
$node->body['und'][0]['value'] = 'new body';
$node->revision = 1;
$node->log = 'State Changed to published';
node_save($node);
workbench_moderation_moderate($node, 'published');

NOTE: I intentionally put workbench_moderation_moderate() after node_save() because in my case node_save() will trigger a new draft.  After the draft is created, I publish that draft.

The second:

$nid = 1234;
$node = node_load($nid);
$node->body['und'][0]['value'] = 'new body';
$node->workbench_moderation_state_new = workbench_moderation_state_published();
$node->revision = 1;
$node->log = 'State Changed to published';
node_save($node);

I am going with the first solution over the second solution because of the status messages. The first shows the two messages under the current revision:

From Draft --> Published on...
From Published --> Draft on...

whereas the second solution only shows one message which doesn't really make much sense:

From Published --> Published on...


Create a user profile on user creation in drupal 6

Changed Code:

    function user_services_create_user() {

    //the user name of the new user
    $user_name = $input['user_name'];
    //the users email address
    $email = $input['email'];
    if(array_key_exists('password', $input)){
        $password = $input['password'];
    }
    else {
        $password = user_password(8);
    }
    user_services_check_user($input);
    //set up the user fields
    $fields = array(
        'name' => $user_name,
        'mail' => $email,
        'pass' => $password,
        'status' => 1,
    );
    //the first parameter is left blank so a new user is created
    $user_account = user_save('', $fields);
    if(!empty($user_account) && $user_account->uid != '') {

        $node = new stdClass();
        $node->uid = $user_account->uid;
        $node->type='profile';
        $node->title=$user_account->name;
        $node->name=$user_account->name;
        $node->field_receipt_suppress_name[0]['value'] = user_fill_value_from_request('receipt_suppress_name');
        $node->field_receipt_suppress_points[0]['value'] = user_fill_value_from_request('receipt_suppress_points');
        $node->field_phone_number[0]['value'] = user_fill_value_from_request('phone_number');
        $node->field_first_name[0]['value'] = user_fill_value_from_request('first_name');
        $node->field_last_name[0]['value'] = user_fill_value_from_request('last_name');
        $node->field_user_phone_number[0]['value'] = user_fill_value_from_request('user_phone_number');
        $node->field_points[0]['value'] = user_fill_value_from_request('points');
        $node->field_date_points_last_checked[0]['value'] = user_fill_value_from_request('date_points_last_checked');
        $node->field_last_reward_issued_store[0]['nid'] = user_fill_value_from_request('last_reward_issued_store');
        $node->field_last_reward_issued_date[0]['value'] = user_fill_value_from_request('last_reward_issued_date');
        $node->field_last_reward_redeemed[0]['value'] = user_fill_value_from_request('last_reward_redeemed');
        $node->field_last_reward_redeemed_store[0]['nid'] = user_fill_value_from_request('last_reward_redeemed_store');
        $node->field_last_reward_redeemed_date[0]['value'] = user_fill_value_from_request('last_reward_redeemed_date');

        node_save($node);

        user_services_send_response('New user has been successfully created', 1, 200, $user_account);
    }
    else {
        user_services_send_response('New user cannot be created. Please try again later', 0);
    }
}


How to make URL arguments available as tokens in Rewrite Results of a Field in a View?

If you do not want to actually use a contextual filter, you can use a "Global: Null" contextual filter, use the Contextual filters options to assign the value from the argument position you are interested in and then that becomes available as a %1/!1 replacement token without actually affecting the query.


How to create a machine name for custom table field with transliteration available

I don't think core has any such function, but the Pathauto module does.

pathauto_cleanstring():

  Clean up a string segment to be used in an URL alias.

  Performs the following possible alterations:

  Remove all HTML tags.
  Process the string through the transliteration module.
  Replace or remove punctuation with the separator character.
  Remove back-slashes.
  Replace non-ascii and non-numeric characters with the separator.
  Remove common words.
  Replace whitespace with the separator character.
  Trim duplicate, leading, and trailing separators.
  Convert to lower-case.
  Shorten to a desired length and logical position based on word boundaries.

Emphasis mine.


This is standard Drupal behaviour, but you can change it using one of the following modules:

http://drupal.org/project/fences
http://drupal.org/project/ds

they both allow you to override the amount of outputted html tags


You can use..

function custom_conditional_form($form, &$form_state) {
  $form['form1']['drupal_love'] = array(
    '#title' => t('Do you love Drupal?'),
    '#type' => 'radios',
    '#options' => array('yes' => t('Yes'), 'no' => t('No')),
  );
  $form['form1']['how_much_love'] = array(
    '#title' => t('Great! Tell us more:'),
    '#type' => 'textfield',
    '#states' => array(
      'visible' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
      'required' => array(
        ':input[name="drupal_love"]' => array('value' => 'yes'),
      ),
    ),
  );
  $form['form1']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}


How to use CKEditor for basic HTML formatting with webforms automatic emails?

I think the main goal is to receive HTML-formatted emails triggered by Webform module, right? This is how I achieved it:

Create and tune a new Text Format, specifically for emails (admin/config/content/formats)
Install Mime Mail module. It enables you to send HTML-formatted emails. Make it use the just-created text format in settings.
Install Mail System module. It provides you the UI for changing mail system globally or per module, if needed. Simply speaking, with this module you can easily configure HTML mail e.g. for Webform, but leave plain-text format for system emails.
You can use HTML tags in Webform > E-mails > Edit > E-mail template textarea. Mails from the website will be HTML-formatted.

Yes, it does not bind CKEditor to E-mail template textarea, but do you really need it? (If yes, I believe it is possible by creating a custom module that overrides the webform-email-edit-form form changing the element type from "textarea" to "text_format", see e.g. this topic).

Upd. I have just found a separate module for doing the latter thing: Webform Email Input Filter.


Admin pages are not nodes, so you would need to use the page template rather than the node template. You can copy your theme's page.tpl.php file and rename it to page--admin.tpl.php to create a template just for all admin pages.  If you need these changes to extend for node edit pages, then you would need to also create a page--node--edit.tpl.php file.

Another option is the ThemeKey module; it allows you to specify which theme to display based on path (i.e. you could change it for all admin/* paths) and/or based on user role (change theme for super users and low-level admins). You could choose a contributed admin theme to display on these conditions, or create a sub-theme of your front-end theme to display.


How to get the Commerce Product type from the order object. D7

I ended up just querying the database, here is what worked for me

$product_type = db_select('commerce_product', 'cp')
    ->fields('cp', array('type', 'product_id'))
    ->condition('cp.product_id', $product_id, '=')
    ->execute()
    ->fetchAll();


Do I have to validate() user entity saved programmatically?

If you want to first verify the user you programmatically created passes validation, which means (for example) that its username and emails are unique, you can check if there are validation violations. You don't need to fist call isValidationRequired() as that method returns the value set with setValidationRequired(), which is called only from ContentEntityForm::buildEntity() and ContentEntityForm::validateForm(). (In other words, if the entity isn't created via its entity form, isValidationRequired() will return FALSE.)

$violations = $user->validate();
if (count($violations)) {
  // The user account didn't pass the validation.
}

Note also that you can pass to User::create() an array containing the values to assign to the user fields, instead of calling each setter as your code does.

You could also create the user account with \Drupal::entityTypeManager()->getStorage('user')->create($values), where $values is the same array accepted by User::create().


I figure out later the link I was adding were actually the nodes I was creating programmatically as a new group is created and I was creating the path alias programmatically as well, when i check the db table menu_links I found there was no router for these node menu links,so to make them work I am putting the default links as external urls for example http://yoursite/node/test, I believe there must be a better way to get this done,good for now.


How to deal with 'internal:' in your link->uri?

just kidding. To help future devs with this issue, check the logs *duh and you'll see this:

  PHP message: Uncaught PHP Exception InvalidArgumentException: "The URI '' is invalid.

So, check for the uri value first!

$node->my_field->uri ? Url::fromUri($node->my_field->uri)->toString() : null,


The cron key is generated by Drupal core then stored as state data (system.cron_key) when Drupal is first installed. system_token_info() doesn't expose this key as a token.
You could just make a static menu link with the /cron/$KEY path as the key will remain static as long as the system.cron_key entry remains in the state table.
If the end goal is to only envoke the Backup Migrate cron handler and custom development is an option, creating your own custom route that invokes the specific backup code (e.g. backup_migrate_cron()) would be a more direct method and have a less chance of side effects from regular arbitrary runs of all cron handlers


URLs aren't working after site migration

This indeed sounds like a clean URL problem.

Standard Drupal URLs use query strings like: www.example.com/?q=string/string/site
Clean URLs rewrite this to www.example.com/string/string/site which is better for SEO.

Check the browser's adress bar to see if clean URLs are working. If not and if you used them on the previous install, you need to either deactivate them in drupal or get them working again. You need to activate it in settings and use correct .htaccess with Clean URLs rewrite rule.

The reason why the home page is working is that there is no query string in www.example.com/


Inserting space/gap between two main menu links

You can use menu attributes module to specify ids for those both menu then you try


Choose specific format for hms field token

To answer my own question: I succeeded in showing the correct formatting as m:ss by enabling the module Token and using this token (with low hyphens) [entityform:field_length] instead of [entityform:field-length].


Unlimited values field - how to hide extra field on node edit

This would work for all node edit forms:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $field_name = 'field_YOURFIELD';

  if (empty($form[$field_name])) {
    return;
  }

  $field_language = $form[$field_name]['#language'];
  $max_delta = $form[$field_name][$field_language]['#max_delta'];
  unset($form[$field_name][$field_language][$max_delta]);
}


You can do this in lots and lots of ways. This is 1 way without Views.

I did this for a homepage. I made 5 variables that hold FIDs for files uploaded using FAPI file_managed fapi element in an admin settings form.

Then using hook_page_build if I'm on the homepage I created a render array that simply calls theme_image using a random file id by loading my 5 variables into an array and using PHP's array_rand() to extract 1 random array value.

Lastly, if you can get this far -- and you have page caching turned on ... you'll only get 1 image ever and it'll never be random. For the render array inserted using hook_page_build you have to set #cache => FALSE within the render array so Drupal will not cache your images and it will be random every pageload.


Path configuration in media gallery module

The solution that Letharion posted will work fine, but making integration with path auto is a better solution like (s)he writes.

Doing this in not that hard, but it can be a bit tricky to do the first time.

To do it you need a few steps.

First you need to implement hook_pathauto in order to get the setting for how the alias should look like. Here you can give info about which type of token can be used for path replacements etc.
Second you need to create a function which can be used to generate an alias. It should look something like this.

function foo_pathauto_update_alias($file, $op, array $options = array()) {
  module_load_include('inc', 'pathauto');
  $path = media-gallery/detail/' . $file->bid . '/' . $file->fid
  pathauto_create_alias('aug_product', $op, $path, array('file' => $file));
}

Path auto is based on entities. So you need to be able to generate the path from a single entity. In this case the file that's created. By using the above function structure you can use a single function and utilize it for bulk updates as well as regular updates while keeping path auto functionality intact.
Lastly you need to call your update function when file is created or updated. This will handle path alias creation. Doing it this way, you can also get path auto to update path alias if the data is changed and the alias should be different, if you want to do so. There is settings for this in the path auto module.
For bonus you can choose to create a bulk update function, that will enable you to the alias for any file created. It takes a bit of work, but should work nicely.

Note doing it this way, it will be a good idea to use the file entity module, as it allows you to handle files like entities, which fits path auto a lot.


views_query_alter apply "%LIKE%" condition

You can do it using code similar to the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', $_GET['query'], 'LIKE');
  }
}

The first argument that is required from $query->add_where() is the group for the WHERE to add. The documentation says to pass 0 as argument, to use the default one.

The code I shown works if $_GET['query'] contains an SQL regular expression. If $_GET['query'] contains a string that is not a regular expression, and that is used to build the regular expression for example as '%' . $_GET['query'] . '%', the code to use should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  if (!empty($_GET['query'])) {
    $query->add_where(0, 'title', '%' . db_like($_GET['query']) . '%', 'LIKE');
  }
}

Notice what reported in the documentation for views_plugin_query_default::add_where():

  The caller is responsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query.

References

hook_views_query_alter()
The list of functions/methods invoking hook_views_query_alter()
db_like()


Kint works in pre_process but not in Twig

In php you use kint like this, kint($variable), but in twig you use kint like this, {{ kint(variable) }}.

This is the only problem I can spot by looking at your question.

Hope it helps.


How to bulk update entities using the Feeds module, without existing mappings to a "unique target"

You could use a custom text field as unique target by using the "Unique values" validator of the Field validation module.

You could also implement hook_feeds_processor_targets_alter() in a custom module to add a "unique callback" to a target. In that callback you can implement your own logic for retrieving an existing entity.

See https://www.drupal.org/node/1307732#field_as_unique_id_7 for a list of steps for both solutions.
See also feeds.api.php for more information about implementing "unique" callbacks.


get path of uploaded picture for custom parallax effect

You'll have to set a $src var from the corresponding preprocess hook.

function myModuleOrTheme_preprocess_block(&$variables){

if(isset($variables['elements']['content']['field_parralaxBgImage']))
//or any other way to test if you are in the right block

   //Get the Image id :
   $imgListItems = $variables['elements']['content']['field_testimages']['#items'];
   $imgId = $imgListItems->getValue()[0]['target_id'];
   //load the entity :
   $image = \Drupal\file\Entity\File::load($imageId);

  // now you can simply return the original image's url :
  $variables['parralaxBgSrc'] = image->url();

  //or return a styled image's url (croped or resized) with a image style configured in the BO
  $imageStyle = \Drupal\image\Entity\ImageStyle::load('imageStyle_id');
  $variables['parralaxBgSrc'] = $imageStyle->buildUrl($image->getFileUri());

}

After that, you'll be able to use it in your twig tpl :

 <div class="parallax-window" data-parallax="scroll" data-image-src="{{$parralaxBgSrc}}">

(Dont forgot to flush your cache after adding the hook)

Et voila! :)


How to add an attribute to CkEditor 4.x iframe tag

As a quick and dirty work-around, I used jquery to add a parameter to the url (which always has at least one parameter already, thus the ampersand).

$('iframe').each(function() {
      $(this).attr("src", $(this).attr("src") + '&wmode=transparent')
  });

But I want to later refine this to only target urls starting with https://www.youtube.com at the very least and use an attribute instead of a parameter. If anyone can suggest the code for that based on what's above, that would be appreciated. If not, I'll eventually update this post with that code when I have more time to figure it out. Thanks.


Optional field in admin panel to filter nodes in view

Not a problem... Drupal does have its own jargon but after a while you will get it.
Very simple solution whenever you want to offer user an option of refining the view or sort... Expose the relevant filter(s), in this case the vocabulary or taxonomy term...
You might also think about using the global null function so as to reduce load on your server ... This will basically produce no results until the user chooses a vocabulary or taxonomy term (category)... Here is an excellent walkthrough on how to do this: How to prevent views from loading the results upfront

Cheers,
gg


This has recently been implemented in Fire generic events when transition are applied [#2832415].


Webforms when created are nodes by default. In drupal 6 there was a module called webform block (http://drupal.org/project/webformblock) this got encorprated into webform with webform 3 (which as your using drupal 7 you will be using, I dont think its even possible to get webform 2.x on D7)

To get the webform as block:

Create your webform in a node.
Edit the node.
Select the Webform tab.
Select the Forms settings tab.
Select the Forms settings tab.
Select Advanced settings.
Switch on Available as block.
Save configuration.

Source: http://drupal.org/node/1447436


In Drupal 8 view.html.twig file how do I access the view content such as individual field title and/or field content?

In views-view.html.twig is not appropriate to style your row and fields.

To style them first you need override template "views_view_'format_style'" (format style specified when you edit/create a view). Here you can style row and access 'fields' variables (use kint(row) to see them).

Something like:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {{ kint(row) }} {# devel #}

 {{row.content['#node'].getTitle()}}
 {# access fields #}

    {{ row.content }}

{% endfor %}

For style fields its better override field template.

For example field--node--body--article.html.twig:

{% set mode = element['#view_mode'] %}
{% if label_hidden %}
  {% for item in items %}
    {% if mode == 'full' %}

{{ item.content }}

    {% elseif mode == 'teaser' %}

{{ item.content }}

    {% endif %}
  {% endfor %}
{% else %}

{{ label }}

    {% for item in items %}

{{ item.content }}

    {% endfor %}

{% endif %}


How to use service renderer with context theme?

Use the theme.manager service to set the active theme to what you desire, render the block and set the original active theme back.

/** @var \Drupal\Core\Theme\ThemeInitialization $theme_initialization */
$theme_initialization = \Drupal::service('theme.initialization');
$active_theme = \Drupal::theme()->getActiveTheme();
\Drupal::theme()->setActiveTheme($theme_initialization->getActiveThemeByName($theme));
// Render your block...
\Drupal::theme()->setActiveTheme($active_theme);


@Duncanmoo: You're quite right, the response to this was incredible. It's nice to have the opportunity to explain how I came up with the current working solution.

The solution has a number of parts and is not entirely elegant, so feedback and advice is still very welcome!

Here is my custom drupal module:

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers_switcher/openlayers_switcher.module

The default html generated by openlayers for the switchers wasn't very easily changed with css, so I have hacked the openlayers.js file to give it some structure (for example wrapping each switcher in an anchor tag).

Take a look here for the amendments I made (search for lambeth.coop):

https://github.com/LambethCouncil/opencouncil/blob/master/sites/all/modules/custom/openlayers_switcher/OpenLayers-2.11/OpenLayers.js

... a very important hack here was to add the click event to show/hide the layers (at time of writing this is line 2850):

// bind the click event to the aSwitcherBlock a element
OpenLayers.Event.observe(aSwitcherBlock,"click",OpenLayers.Function.bindAsEventListener(this.onInputClick,context));

... this meant I could by-pass all the horrible jQuery problems I was experiencing and made me very happy!

... I would like to do the same with the openlayers-2.12 js file but got stuck. I'd love to find a way to do this - currently I'm stuck on openlayers-2.11 which is the old version as far as the Drupal Openlayers module is concerned. So that's a bit dumb.

Finally, see here for a method of taking the entire layer-switcher out of the default right-hand-side-of-map position and assigning it to a div outside the map:

http://drupal.org/node/1475316#comment-6945728


How to get product URL or URL alias using product ID?

After trial and error I found a solution. Here's what I did.

        //$product is the product object that I mentioned above
        $wrapper = entity_metadata_wrapper('commerce_product', $product);
        $nodes   = $wrapper->field_product_node->value();
        $path    = drupal_get_path_alias("node/".$nodes[0]->nid);
        $product->path = $path;


Views help from Advanced Help isn't being displayed or I can't find it

Install the advanced help module

  When this module is installed, users with the view advanced help index
  permission can access the advanced help index by going to Administer
  -> Advanced Help (http://www.example.com/admin/advanced_help). Additional view advanced help popup and view advanced help topic
  permissions enable them to access the actual help pages and popups.


If you click on Content: Path it will give you the a field that repesents the path of the node.


How to use dd(debug_backtrace()); for an error debugging?

You can run:

dd(debug_backtrace());

which prints the output to drupal_debug.txt file by default in your temporary folder which can be found in your tmp folder (See: Where Drupal creates temporary files?). You can specify different file, but in Drupal settings related to file system.

The call to dd(debug_backtrace('drupal_debug.txt')); is invalid, since debug_backtrace() accepts int $options, not the file.

Regarding this warning:

  Only 0 of 1 bytes written, possibly out of free disk space in drupal_debug(). Devel was unable to write to /tmp/drupal_debug.txt.

it says you're likely to be out of free disk space on your hard drive. So you should remove this file from your temporary folder at /tmp, then try again.

To make it more light, use the following version:

dd(debug_backtrace(FALSE, 5));

which won't populate all objects (FALSE) and limit number of stack frames returned to 5.

If your function is called too many times, try adding die() or exit(); to avoid multiple calls.

You can also use the following one-liner:

array_walk(debug_backtrace(),create_function('$a,$b','print "<pre>{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']});</pre>\\n";'));

which will print even more minimalized version of the backtrace to avoid out-of-space issues.


Instead of casting an array into a stdClass object, you could try creating a new stdClass() object and then using node_object_prepare() to prepare the object for creating a new node and then finally manually changing the values of uid, name, title, language, body, etc. Also, be sure to use node_submit() before saving the new node to the database.

Example: http://drupal.org/node/1173136


Deleting migrate module tables post migration

So, I deleted the tables (actually truncated them) on my dev server and there have been no side effects that I have noticed, so will try deleting the tables in their entirely. The migrate tables made up around 600mb in a dump.


How to use my own video and be able to play from a specific time?

May be you can try with javascript

document.getElementById('YOURVIDEOID').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

In jquery

var vid = $("#video")[0];
$("#button").click(function(){
    skipTime(100);
});

function skipTime(time) {
    vid.play();
    vid.pause();
    vid.currentTime = time;
    vid.play();
};


So after a lot of digging, I realised that this issue was due to the Panels module.

I had only added the field the usual way you would; through the content type when it turns out you need to configure it through the Panels view (which I was completely unaware of until today).

You would think that configuring it though the content type would be enough but evidently not.

Nonetheless, hopefully my question and answer will come in useful to someone one day who encounters a similar issue to mine.


How do I display a list of nodes that reference a given node on the node content page?

In your view set up a contextual filter (under 'Advanced') on the entity reference field. Then configure the filter to provide a default value if the filter is missing. Select 'Content ID from UrL'.

When you display the view, it will list the children which point to the page you are currently displaying.


What is best method to use for multiple databases on one server?

This question is dangerously off-topic, but as far as Drupal is concerned there are two primary things to consider.

True multisite (multiple independent sites running our of the same DOCROOT) versus multiple sites on the same server don't really come into play.  In fact, you could also apply this to multiple sites using the same database server instance.

Running multiple sites out of the same database catalog is used when

You only have one catalog to use and need to share it (eg, shared hosting).
You want to share some tables between instances.

However, as those state, this isn't a good idea.  Apart from the stability issues with sharing tables, you also have the security issue of an exploit in one site potentially getting at the data from another site.

Ideally, each site should have its own catalog in your database server, and each of these should have a unique user associated with it that has full access (minus GRANT) with connections limited to where the site is running from (either localhost or the IP address of the webserver).  This is the username/password that you should use in your settings.php

Database replication doesn't really factor into the decision here.  It is use for performance and/or redundancy reasons.  Drupal has some support for master/slave arrangements, but it is not really transparent.


To get site working properly:  It seems like .htaccess issue. You do need the .htaccess file. It should be in the document root folder and secured so that any host account can read it. Out of the box Drupal has this file.

To recover Drupal User=1 password: If you are lucky, your ISP may have drush installed globally on this server. SSH to the server and try "drush uli" command. If not, you can try installing drush on your local machine - the pain will be well worth it if you plan to continue working on Drupal. You can use "drush uli" command on your local machine, login with the on-time login link given and change the admin password. They upload the database back to your ISP.


view_form_submit is not working in D7, you have to use the hook_form_alter and then you have to change the #submit:

$form['actions']['submit']['#submit'][] = 'custom_form_submit';


I think that it would be better to use

{{ content.field_size.value }}

Then twig will automatically get the value from the field.

If you just want to render the field then {{ content.field_size}} should be fine.

Hope it helps.


D7 : Plupload version could not be determined

Ok.

The problem was that i never uploaded the changelog.txt along with the js folder.


How to include attributes of the MySQL table to hook_schema() schema in drupal 7?

You can't use an ON UPDATE unfortunately - Drupal's schema API doesn't give you that sort of dbms-specific control.

You can use unsigned for unsigned and default for a default value though:

$schema['some_table'] = array(
  'fields' => array(
    'some_field' => array(
      'type' => 'int',
      'not null' => TRUE,
      'unsigned' => TRUE,
      'default' => 0,
    ),
  ),
);

See the Schema API docs for the full list of data types and usage.


Changing the link title in a view for generic file

I'm guessing that you are using a field to save the data about the files.

When the file is displayed in views, it's displayed through a formatter which acts like a theme function. The different ways an image can be shown, is in reality just different formatters that link to different theme functions (or the same, but with different arguments).

You have two options.
* You can override the theme function, which would change how ALL files are shown, when displayed using 'generic files'.
* Yo
u can create your own formatter, and theme function which could be a copy of the one Generic files uses, but with a few alterations.

The hooks you need to use, depend on which version of Drupal you use, but you can search the modules and copy how it's done for Generic files.

For a long explaination you can check out this blog post I wrote a while back.

The short version is:

use Hook_field_formatter_info:

/**
 * Implementation of CCK's hook_field_formatter_info().
 */
function module_formatter_info() {
  return array(
    'default' => array(
      'label' => t('My generic files'),
      'field types' => array('filefield'),
      'multiple values' => CONTENT_HANDLE_CORE,
      'description' => t('My description.'),
    ),
  );
}

Next use hook_theme, creating a theme function with a hook like name:

function filefield_theme() {
  return array(
    'module_formatter_default' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

Lastly create the theme function

/**
 * Theme function for the 'default' filefield formatter.
 */
function theme_module_formatter_default($element) {
  $file = $element['#item'];
  $file['data']['description'] = t('Download');
  $field = content_fields($element['#field_name']);
  $output = theme('filefield_item', $file, $field);
  return $output;
}

The above code should work and do what you want, but haven't actually tested this.


Database error when upgrading from Drupal 6.37 to Drupal 7.41

Heading ##I see this post is a few days old, hope you are still watching.

What is happening is that the update is trying to 're-shape' the type field in the system table, to look like this in D7:

type           | character varying(12)  | not null default ''::character varying
However in D6 the field looked like this:

type           | character varying(255) | not null default ''::character varyin
g

Now you have old content in that field that is longer than 12 and would be truncated and therefore the ALTER TABLE command fails. Now, this is what I would call a messed up update system.

I think there are several options to fix this.

First make a backup of your system table.

Then open a database connection to your drupal database and check what the longest entry will be. I am assuming you are using Postgres:

select (length(type)), type from system group by type;
 length |  type
--------+--------
      5 | theme
      6 | module

That is my output, now you can check which entry is longer than 12 characters, and see if it contained any useful data.

Now, the easiest way is probably to simply do the field truncations yourself:

ALTER TABLE system ALTER COLUMN type TYPE VARCHAR(12) USING SUBSTR(type, 1, 12)

Then attempt the migration again, you still have your backup should this go wrong.

Second option depends on if you need these defined types, possibly they can simply be deleted:

select type from system where length(type) > 12;
Turn this into a delete statement if you will.

Third option is possible if no code will rely on the field size being 12.

The code for the db update is in modules/system/system.install line 2112:

function system_update_7018() {
  db_drop_index('system', 'modules');
  db_drop_index('system', 'type_name');
  db_change_field('system', 'type', 'type', array('type' => 'varchar', 'length' => 12, 'not null' => TRUE, 'default' => ''));
  db_add_index('system', 'type_name', array('type', 'name'));
}

change length => 12 to the maximum desired length, and run the dbupdate again.

I can't say which consequences each of the approaches will have and each can possibly cause follow-up errors and break other stuff, so you should try them all.

Hint: use drush for the updates, there will be a lot of repetitive tasks, roll-back-update-roll-back-update.


I'm not sure if it would integrate with that widget automatically, but I really like Chosen. Doesn't work on mobile though.


Sounds like you need to do the following:

Set the securepages_enable to 0 in settings.php
Open a MySQL Client, like HeidiSQL or SQL Pro
Truncate the cache_ tables
Reload local site in browser

This should rebuild the variables and then your runtime value will be respected.

Also, check the .htaccess file to see that you are not being redirected to HTTPS.


Extending EntityFieldQuery. Which variables should I define?

class nodematcher extends EntityFieldQuery {
  public function __construct() {
    $this->query = New entityFieldQuery;

This doesn't make any sense. You are either subclassing EntityFieldQuery or you are using a delegate pattern. Doing both makes little sense. What you wanted here is perhaps parent::__construct and wherever you used $this->query just use $this.


Is it possible to trigger a webform submit via url?

Inject some javascript into the body using PHP can make auto submit to work by a param in URL:

 http://example.com/event_form?autosubmit=yes&option=y

For example, the webform node ID is 101:

<?php if ($_REQUEST['autosubmit']) { ?>

    <script>
    (function ($) {
        $(document).ready(function(){
            $('form#webform-client-form-101').submit();
        });
    })(jQuery);
    </script>

<? } ?>


hook_auth() has been gone since Drupal 5.

But it sounds like you're looking to implement something with user_authenticate().

General outline of how to accomplish this (note that this will send passwords as plaintext - use SSL if that's a problem):

Create an API page using hook_menu() for your app to hit.
In that pages callback function, accept the username and password as POST requests (or however you want to build your app) and run them through user_authenticate().
Return the results of user_authenticate() (either FALSE: fail or numeric: pass) as a json string (or whatever you want) and act accordingly within your external app.


There might be hundreds of ways to add this markup in Drupal. The two simplest that came to my mind are:

1) Add a suffix to the form tag in form build or form alter:

$form['#suffix'] = '
Suffix to form
';

2) or add the markup in a form.html.twig below the form tag:

{#
/**
 * @file
 * Default theme implementation for a 'form' element.
 *
 * Available variables
 * - attributes: A list of HTML attributes for the wrapper element.
 * - children: The child elements of the form.
 *
 * @see template_preprocess_form()
 *
 * @ingroup themeable
 */
#}
<form{{ attributes }}>
  {{ children }}
</form>

  A div container after the form

For the second solution you might also need to add a theme name suggestion.


How to remove "Submitted by .... on Fri, 06/19/2015 - 22:04" from published content in Drupal 7?

You can remove it by doing below steps.

Go to content type edit page i.e. /admin/structure/types/manage/page
Now under Display Settings, uncheck the option Display author and date information.


Yes, definitely higher up. When you are already inside of a 404 subrequest it is too late.
You could put the code in on404() of an HttpExceptionSubscriber, check the path and then replace the 404 with 410:
$event->setException(new HttpException(410));

See https://drupal.stackexchange.com/a/231263/47547


You can achieve that in couple of ways. You can create custom module or simply by using on the modules mentioned below.

Advanced Form Block

  With this module you can do the following:

  1) Create any number of blocks with a particular node edit form.

  2) create any number of blocks with a particular node add form of a
  content type.

  3) Create as many blocks as you like of each kind.

  4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.

  5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.

OR

Form Block

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

OR

You can also achieve that by creating custom module. Follow this link


Extending existing menu/route in module_menu_alter

I would try netfactory_rooms_menu() (i.e. hook_menu() instead of hook_menu_alter()). You are effectively creating a new menu callback, not extending an existing one.

Also, CLEAR THE CACHE before trying the new path.


Drupal Ubercart Merchant ID and Key are incorrect?

To fix this issue I made sure that the proper soap packages were installed.
Then I went on to create new credit card encryption keys for each domain. Right now I am waiting on SSL certs so that Drupal can generate new credit card encryption keys for each domain. I hope it works!


Get all nodes where date field matches month and year

You can use a range like condition:

$query = new EntityFieldQuery();
$query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'horas')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_day', 'value', $myFieldDate . '-01', '>=')
  ->fieldCondition('field_day', 'value', $myFieldDate . '-31', '<=');


Assuming you use Drupal 7, it is trivial to add fields to any entity using the build-in Fields module.  (If you see references to "CCK", note that this is not for Drupal 7, but to an older version of this feature.)  With fields, you can enhance Drupal 7 with new data types and entity types from the front end admin interface.

The term "field" refers to a given piece of content within an entity. A field is characterised by having a field name, field type and widget. A widget in this context can be a HTML form element or jQuery widget that is to be used for data entry.

To have latitude and longitude fields in your entity, you should install the Geofield module.  This will give you access to geofields as native datatypes, and also a widget for entering map coordinates if you need that.

To add fields to an entity, start by navigating to Structure → Content types, and click on manage fields for the content type you want to add new fields to.  This can be one of the build-in content types, or a custom content type you've defined.

Clicking on  manage fields brings up a form that shows what fields are already present in the entity. Here you can delete or add new fields to the entity. Add your geofields and click Save.

However, if you want to insert values into those fields programatically (instead of interactively using a widget), you need to create a small custom module that uses the Drupal database API to insert the values into the fields in the database.

Here are links to some fields tutorials that tells you more about how to use fields:

http://heim.ifi.uio.no/gisle/staging2/drupalprimer/drupal/drupal_field.html
https://drupal.org/documentation/modules/field
https://drupal.org/node/707832


I think you should try Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc.

This is a great tutorial to understand how Display Suite works.

Hope this answer may help you.


Can Entity Translate work on the node body?

Ah turns out you have to enable translation for the field once you've enabled translation for the content type.

Open up your content type, edit the field you want to make translatable then head down to the bottom of the page.

You should see something like:

Field translation
Users may translate all occurrences of this field:

Body in Basic page
Body in Article
Body in Webform
Body in Test Content
Body in Upgrade & Search Token Product Display
Body in Blog post/Article
Body in Development Blog

Click on "Enable translation" and you're good to go.


How to translate the user profile page in commerce kickstart

The solution described in issue #1937982 has been used to solve an issue similar to yours. That issue includes a .PO file to handle at least these strings:

Primary billing address
Primary shipping address

If that would work in your case also, you can probably use the same solution by adding 2 similar lines for these 2 other strings (you may have to verify if it is case sensitive or not):

HELLO
RECENT ORDERS


Content in website does not show under the right website name

Looks like you have removed the default front page settings. Please head over to /admin/config/system/site-information and add node/3 as default front page. Let me know how you go.


What does the 'export' key mean in a schema definition?

These properties are used for implementing ctools export/import APIs.

See How to make configuration objects exportable with CTools.


Leaflet: how to display a unique marker per map

I would use a contextual filter (Advanced settings column) based on the content NID (node identifier). You will get a settings window where you choose "Provide default value" and Type : Content ID from URL (the nid is always available from URL even if you use an alias). Then, the Leaflet map will be filtered using this NID and you will get only one marker (display all results and remove your sort date) created with coordinates entered for this specific content (page). Finally, you will need only one block with this contextual filter, since it will be automatically modified according to page URL.

Hope this helps.


You can use the function db_and() an db_or() to compile condition sets that you can the add to an existing query like this:

$query = db_select('Exhibitors', 'e');
$db_and = db_and();
$db_and->condition('ProductCategory', array(1,2,3), 'IN');
$db_and->condition('status', 'active');
$query->condition($db_and);

Example taken form here: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_and/7

Other than that, there is the DatabaseCondition Class that might be interesting for you too.


I've tried to do this a few times and never really got very far (for the reasons you've already mentioned).

The way I found to do it instead was to install the Field Collection module (and Field Collection Table for a better UX), and use that to group the fields I need into a single field, which is represented as a single widget.

Then I just hook into the particular form that's showing the field and add the AJAX that way. As coincidence would have it I've just done exactly this a few hours ago. I know this is out of context but here's a (slightly anonymised) dump of the code I used; hopefully it'll give you a place to start if you choose to go down this route:

function MYMODULE_form_directory_listing_node_form_alter(&$form, &$form_state, $form_id) {
  $selected_country_tid = $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#default_value'][0];

  $form['field_address'][LANGUAGE_NONE][0]['field_country'][LANGUAGE_NONE]['#ajax'] = array(
    'wrapper' => 'directory-form-county-wrapper',
    'callback' => 'MYMODULE_form_directory_listing_country_ajax'
  );

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#prefix'] = '
';
  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#suffix'] = '
';

  $selected_country_term = taxonomy_term_load($selected_country_tid);

  $options = array();
  foreach (_MYMODULE_get_country_counties($selected_country_term) as $county) {
    $options[$county->tid] = $county->name;
  }

  $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE]['#options'] = $options;
}

function MYMODULE_form_directory_listing_country_ajax(&$form, &$form_state) {
  return $form['field_address'][LANGUAGE_NONE][0]['field_county'][LANGUAGE_NONE];
}

field_address in the above example is the Field Collection field.


The point is moot, because the the hook_menu strings should not be translated at all. Your code should in fact be:
$items['account/edit/%'] = array(
  'title'            => 'Edit account information',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('partners_add', 2),
  'access arguments' => array('edit account in partners'),
  'type'             => MENU_NORMAL_ITEM,
  'file'             => 'inc/partners.form.inc',
);

I quote from: http://drupal.org/node/323101:

The Drupal 6 and 7 menu system stores menu item titles and descriptions in English. This allows the system to cache the data, but display to users using various languages on demand. For this to work, you should not use t() on the title or description of menu items in your hook_menu() implementation.
Again, we use plain English so that the menu system can store the English text and translate as required, benefiting performance. If, instead, we use t(), the menu system would store the menu item titles and descriptions in the language of the first visitor when the menu cache was rebuilt, which would not work as a base for translations on a multilingual site.


Available updates report does not list all available module updates

In Drupal 7, two methods are used to fetch update information. One uses a setting update_max_fetch_time which is set to 5 seconds by default. On each cron run - whether from the server's cron or triggered by a visitor (poormanscron) - or page refresh of admin/reports/updates, this value is used. Not every module's status can be fetched within those 5 seconds, which is what you're seeing.

If you use the 'Check manually' link from the 'Available updates' page (admin/reports/updates/check), a batch operation is used instead, which should process all modules. There are however also reports that this doesn't always work correctly (Failed to get available update data for [number] projects message, you would then see the status of some modules in a grey box). You may also have to clear Drupal's cache first for this to work correctly.

The best thing to do is probably to set up a cron job to run each hour (for example). This will progressively keep the status of all modules updated.

Another workaround would be to override the update_max_fetch_time value and set it to e.g. 30 seconds (you can set $conf['update_max_fetch_time'] = 30; in settings.php, or with Drush do drush vset update_max_fetch_time 30). But if a cron run is then triggered by poormanscron, this could lead to a long page loading time.

This is from issue 952394 (still open).


1) By default, dblog module is enabled. It is real performance bottleneck for big sites. But you can use syslog module (from core) or contrib analogs to write logs in /var/log/drupal.log and etc.
Rsyslog config can be something like this:

    local0.warning /var/log/drupal_site_err.log
    local0.info;local0.!warning /var/log/drupal_site.log

You should analize your logs and fix errors, warnings and even PHP notices. I think 281 messages per page — this is a lot.

2) On your dev site you can allow anonymous users to see devel information with permission “Access developer information”. Don't forget to disallow Devel on production.


Views: What setting is available in Views to hide or skip the first entry in a multi-value field? (example skip first image)

I vaguely remembered doing this in a Views tutorial and remembered it was a control located within the center region of the Views interface.

Turns out it's under "Pager": Use pager: Display a specified number of items >> "You may also adjust the settings for the currently selected pager"

Click setttings and you'll be able to add an offset.


I recommend using the Votingapi Widgets module based on the Voting API in D8, it works and does the same as Fivestar.
Some more details about this module (from its project page):

A flexible field based Voting System based on Voting API.
You need Drupal Version >= 8.2.3. (Multiple form instances on a page).

Be aware: only an alfa3 release for D8 as of right now.


Custom tpl for view mode for all contenty type

Certainly, just add the following code to your theme's template.php file (replacing MYTHEME with the name of your theme):

function MYTHEME_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['view_mode'];
}

And remember to clear the caches


How to change the 'Quantity' label in commerce-order-item-add-to-cart-form

To change label try with:

$form['edit-quantity']['widget']['value']['#title']  = t('Number of days');

Or:

$form['edit-quantity']['widget'][0]['value']['#title']  = t('Number of days');

Use Devel to check $form['edit-quantity']['widget'] with dsm($form['edit-quantity']['widget']) or dpm($form['edit-quantity']['widget']).


Changing a filter in a view without modifying the filter clone?

When you're changing a filter, before you apply there's a dropdown box. It's probably set to "All displays (except overridden)" by default. Before you hit Save, change that All Displays to "This display only"


How to solve the "No file was uploaded." when trying to use custom form field?

For saving file u can use

    $form['test_picture']['file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Test Picture'),
        '#description' => t('Allowed extensions: gif png jpg jpeg'),
        '#upload_location' => variable_get('picture_upload_location'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('pdf'),
            'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
        ),
    );


It is really a personal decision on which one you should download. It is recommended to always download the one's in "Green". However views3 offers a significant improvement in the user interface and if you are just starting out in views, this might be a better choice.

A good article on choosing modules http://drupalwatchdog.com/1/1/module-selection-in-the-wild


How to solve the warning of CAPTCHA session resuse attack

This is a bug in CAPTCHA module you are using. Module should be compatible with core, and file upload is one of the core functionalities of Drupal. Please report this bug to module's issue queue.

But you are not helpless. As a workaround, you can use Multi-Step Registration module. Keep CAPTCHA on first step only, and put profile photo in a second step. It will keep conflicting fields on separate forms, preventing them from interfering with each other.


How to prevent Drupal from scrolling to the bottom of ajax-appended content in a form

You could override the Drupal.ajax.prototype.success handler (/misc/ajax.js) in your theme  to control behavior, maybe commenting out Drupal.unfreezeHeight(); and Drupal.freezeHeight(); could do the job?
Just copy the whole function and manipulate it your own way.

/**
 * Handler for the form redirection completion.
 */
Drupal.ajax.prototype.success = function (response, status) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');

  Drupal.freezeHeight();

  for (var i in response) {
    if (response.hasOwnProperty(i) && response[i]['command'] && this.commands[response[i]['command']]) {
      this.commands[response[i]['command']](this, response[i], status);
    }
  }

  // Reattach behaviors, if they were detached in beforeSerialize(). The
  // attachBehaviors() called on the new content from processing the response
  // commands is not sufficient, because behaviors from the entire form need
  // to be reattached.
  if (this.form) {
    var settings = this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }

  Drupal.unfreezeHeight();

  // Remove any response-specific settings so they don't get used on the next
  // call by mistake.
  this.settings = null;
};

Another option would be to render the ajax form with ajax_commands where you could add custom js handlers to your callback.


Drupal 7 OG Group Unsubscribe after given time period for member

This is definitely a job for rules. It is also quite a complexed subject as you are going to need to utilise components so that you can schedule this to happen every day. I would do it like this:

Set up a views_bulk_operations view that looks up all users that have been members of groups for 90 days.
Create a rule component that loads the list of users, loops through the list, sends a notification and unsubscribes the user from the group.
Schedule the rule to do this every day.


There is a module that exposes blocks to the view header/footer and no results. It's called the Views Block Area.

  This module exposes all available blocks as a views area. This way you
  can add any block inside a footer or header from your view.

  Blocks that are generated by views, can't be selected. These blocks
  can be inserted by views areas.

This is also only for Drupal 7


How to find bad PHP node that makes search_cron fail?

i was facing this issue after upgrading a big application from 6 to 7.This is what I did. From the database run this query

SELECT n.nid FROM node n LEFT JOIN search_dataset d ON d.type = 'node' AND d.sid =
n.nid WHERE
d.sid IS NULL OR d.reindex <> 0 ORDER BY d.reindex ASC, n.nid asc

This will give you the last node that is giving you issues and has refused to be re-indexed.
From there you can do what you want with that node. For my case I realized it was a whole content type that was not displaying well. I had to resave one of the fields to allow this content type to display.


Changing the From Address with the Printer, email, and PDF versions module

It's in Administration » Configuration » User interface » Printer, email and PDF versions, as the Use Reply-To Header option.


Same menu display only a couple of levels down when used normally but when used within the "Site map" module it would display all the levels?

You can install the Menu Block module to help with that.

You can define a define a block for a specific menu, and in the block configuration you can choose the maximum depth (see the active select list in the image below). Then you can add that block to your header/whatever region in place of the menu that's there now.

This won't affect the underlying menu itself though, just the display of it for that particular block. So in the sitemap, all levels of links will show.

Obviously you may need to make a few CSS tweaks to your menu as the wrapping classes will probably have changed, but I think this is by far the quickest method to get what you're looking for.


How do I validate form elements in a modal without closing?

This is a excellent article which you can read for "fixing" your issue:
http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Keep in mind this lines:

First, we wrap our form with a div

public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  // It is important this id
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  // The status messages that will contain any form errors.
  $form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
  ];

  // more code

  $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit modal form'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      // Function to call when the users click on submit button.
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // more code
}

Second, we show the errors:

/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    // Remember the previous id ? Here it is
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}


I'ts in your content type. You might have mistaken the label with the value, or not used the label at all. Open the content type, edit each field and change the allowed values as described above the textarea.

If I'm not mistaken it is

Label|value


If I understand correctly your current problem is getting the current values of the exposed filters.

Wherever you are putting your code, as long as you have access to the view object you can get these values using view::get_exposed_input() like this:

$filters = $view->get_exposed_input();
// You can then access the value of a specific filter like this.
$value = $filters['FILTER_NAME'];

You can then use those values to implement whatever logic you require.


placing a menu block inside a views template

I used the code which was rendering the main-menu from page.tpl.php file in the theme that I am using in my current project Nexus.

<div id="main-menu">
<?php
 if (module_exists('i18n_menu')) {
   $main_menu_tree = i18n_menu_translated_tree(variable_get('menu_main_links_source', 'main-menu'));
 }
 else {
   $main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
}
 print drupal_render($main_menu_tree);
 ?>
</div>

So i used the following extraction:

<?php
$main_menu_tree = menu_tree(variable_get('menu_main_links_source', 'main-menu'));
print drupal_render($main_menu_tree);
?>

in a views template file for row design. The main menu appeared with content.

Note: The menu which will be rendered might not be themed.


This module looks like something that might fit your need: Simple preview


Field value not updating when posting data via JSON

You should be adding your date in the value property and not including a time.

"field_date_of_cage_card_creation": {
    "und": [
        {
            "value":"17 Dec 2018",
            // or maybe
            "value":"2018-12-17",
            "timezone": "Asia/Kolkata",
            "timezone_db": "Asia/Kolkata",
            "date_type": "datetime"
        }
    ]
},


Before you clean the vocabulary you need to change the taxonomy reference field, to do this you can use this code:

$nids = \Drupal::entityQuery('node')->condition('type','YOUR_CONTENT_TYPE')->execute();
$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

foreach($nodes as $node) {
  // Change your term here
  $node->field_YOUR_TAXONOMY_REFERENCE_FIELD->value = '';
 $node->save();
}

To clean the vocabulary use this modification of a drush command that you can see in https://github.com/adrian-cid/drush_commands/blob/master/drush_taxonomy.drush.inc

You need to pass an array of vocabularies names to clean.

I use the dpm() function (you need to install Devel) to show the messages, but you can change it if you want.

function taxonomy_vocabulary_clean(array $names) {
  if (!empty($names)) {
    // Check for duplicate ids.
    $test_names = array_unique($names);
    if (count($test_names) != count($names)) {
      dpm('You have duplicate vocabulary names.');
      return;
    }
    //Searching the vocabularies in the site
    $vocabulary_in_db = array_keys(Drupal\taxonomy\Entity\Vocabulary::loadMultiple());
    $vocabulary_non_existent = array_diff($names, $vocabulary_in_db);
    $vocabulary_existent = array_diff($names, $vocabulary_non_existent);

    if (count($vocabulary_existent) == 0) {
      dpm("The desired vocabulary to clean doesn't exists.");
      return;
    }
    if (count($vocabulary_non_existent)) {
      dpm('Non-existent vocabulary:');
      dpm(implode(' ', $vocabulary_non_existent));
    }

    foreach ($vocabulary_existent as $name) {
      $tids = \Drupal::entityQuery('taxonomy_term')
        ->condition('vid', $name)
        ->execute();

      $controller = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
      $entities = $controller->loadMultiple($tids);
      $controller->delete($entities);
    }
    dpm('Vocabulary cleaned:');
    dpm(implode(' ', $vocabulary_existent));
  }
  else {
    dpm('You must enter at least one vocabulary name.');
  }
}

Using the function:

taxonomy_vocabulary_clean(['tags', 'my_vocabulary_machine_name']);

The Drupal 7 code:

function taxonomy_vocabulary_clean(array $names) {
  if (!empty($names)) {
    // Check for duplicate ids.
    $test_names = array_unique($names);
    if (count($test_names) != count($names)) {
      dpm('You have duplicate vocabulary names.'));
      return;
    }
    //Searching the vocabularies in the site
    $vocabulary_in_db = array_column(taxonomy_get_vocabularies(), 'machine_name');
    $vocabulary_non_existent = array_diff($names, $vocabulary_in_db);
    $vocabulary_existent = array_diff($names, $vocabulary_non_existent);

    if(count($vocabulary_existent) == 0) {
      dpm("The desired vocabulary to clean doesn't exists.");
      return;
    }
    if(count($vocabulary_non_existent)) {
      dpm('Non-existent vocabulary:');
      dpm(implode(' ', $vocabulary_non_existent));
    }

    foreach ($vocabulary_existent as $name) {
      $vid = taxonomy_vocabulary_machine_name_load($name)->vid;
      foreach(taxonomy_get_tree($vid) as $term) {
        taxonomy_term_delete($term->tid);
      }
    }
    dpm('Vocabulary cleaned:');
    dpm(implode(' ', $vocabulary_existent));
  }
  else {
    dpm('You must enter at least one vocabulary name.');
  }
}


In Drupal 7, do database queries need to be enclosed by double quotes?

Some SQL database engines are not supporting double quotes inside the query, that's why it didn't work out for you. Read more here: db_query#comment-11959.


Default values not working in multiple select options

check it out - http://drupal.org/node/73077


how do you add a cookie policy to the site so it appears when a user arrives?

The Cookie Control module works fine to address this question.
Here is a quote from its project page:

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.


Just use views to create a block with your "menu" links and then make it show up in the sidebar for all "usertype/" and "usertype//*" pages.

That view will also need a contextual filter "userid from url" similar to your other view. You can "rewrite the url" to create the links.


If you want to filter gallery images by user id try "provide default value" and than use arg(1) which is user id in your URL, More on this here : http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7


Newly (programmatically created) blocked user gets access denied when resetting

I'm assuming that you are wanting users to click on a link in the registration email to validate the address (this is configurable in your user settings)

You should set status=1 in the user as this is the default behavior and if it is 0 the login link will not work.

If you look at user_register_submit() there is code in it to send out emails.

I think you want

$account =  user_save( NULL, $users, NULL );
if($account) {
  _user_mail_notify('register_admin_created', $account);
}
else {
// Error code
}

at the end of your second method.


How can I display custom user information on a page that is not a profile page?

Probably you should create a panel with two views. One for a general user information and other for stuff like uploaded pictures.

Hope these tutorials will allow you to get started

http://nodeone.se/sv/node/20

http://mustardseedmedia.com/podcast/episode32


The difference is that the Book module defines a content type ("Book page") that can be used to create books. The Book module allows also to create a hierarchical structure, and it shows:

the list of the child pages associated with the current book you are visualizing
a menu that allows to pass from a page to the next one, the previous one, and the top one
a link that allows you to create a new child page
a link that allows you to see a printable version of the current book page

The Taxonomy module is used to categorize the content of a site, but when you click on the link of a taxonomy term used by a node, the page you see shows all the nodes using that taxonomy term, without allowing you to pass from a node to the successive, or the one hierarchically on the top.

Said in sort, the Taxonomy module handles an attribute (in Drupal terminology is a field, handled with the field API) that can be associated with nodes, but also to users, while the Book module defines a content type that can be used to create books, and allows to handle that content type in a hierarchical way.


How to disable auto submit on value change in date_popup form?

Add 'event' => 'submit' in #ajax' => array()


Is there a Drupal 6 equivalent to template_preprocess_taxonomy_term()?

Managed to eventually figure this out myself. I'm using the following in template.php to identify a taxonomy term page in D6:-

<?php
function THEME_preprocess_page(&$vars) {
  if (arg(0)=='taxonomy' && arg(1)=='term') {
    // do something
  }
}
?>


You are looking for Insert module, using this module you can retain the sizes with the help of image cache.

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain text areas.
Insert images using ImageCache presets
Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
Per-field insert configuration


Your problem might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


How would you implement an automatic way of the images loading in a pop-up (lightbox/colorbox) window by a click?

You can. As always, there are several ways.

You can implement a Drupal behavior (jQuery script) that finds all images within the content and adds according classes / click callbacks.

Another way would be writing a little custom module implementing a content filter that does the same on your server.

I'm not at a PC right now. But I think you have two viable ideas now to search for. Let me know, if you need further help.


how to show a view with one to many relations

Yes, Display Suite would work for this. With the right modules and configuration, you may not even need to create a View.


find page.tpl.php file in theme's root folder (sites/all/themes/corporateclean/page.tpl.php).

You'll see that this file defines how and where variables and regions get printed. You can make changes right there.

What you're looking for is $logo and $site_name variables.


How do I change the limit of user accounts gets blocked or suspended?

This is a configuration setting. You can run the drush command:
drush cset user.flood user_limit 10


Unprocessable Entity: The following relationship fields were provided as attributes

As the error indicates, the entity reference has to be set in relationships, not attributes.
The documentation gives this example:
{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "Article by admin",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    },
    "relationships": {
      "uid": {
        "data": {
          "type": "user--user",
          "id": "{{UUID of user 1}}"
        }
      }
    }
  }
}

In this example, the author of the node is set using the relationship of uid.  However, it wasn't immediately clear to me how to set the entity reference field.
It turns out to be quite easy:
const data = {
  data: {
    type: 'node--page',
    attributes: {
      field_text: {
        value: `${values.textFieldValue}`,
        format: 'basic_html',
      },
    },
    relationships: {
      field_ref_term: {
        data: {
          type: 'taxonomy-term--my-vocabulary',
          id: '9fa0cdc7-384c-4aa4-8ce9-d6c97fc2f44b',
        },
      },
    },
  },
};

The key for the relationship is the machine name of the entity reference field.


Unable to see page context in cache context

Try a route based context extending RouteCacheContext:

Example:

<?php

namespace Drupal\Core\Cache\Context;

/**
 * Defines the RouteCacheContext service, for "per route name" caching.
 *
 * Cache context ID: 'route.name'.
 */
class RouteNameCacheContext extends RouteCacheContext {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return t('Route name');
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return $this->routeMatch->getRouteName();
  }

}

You can use this core example and get instead of the route name a route parameter.

You can improve cache efficiency and prefix the context name with route.. Cache contexts are ordered hierarchically, so that the caching system can remove specific cache contexts already covered by more general ones when merging cache metadata.

This leads to further considerations. If the block is only visible on a specific route and the route has only one parameter, then the core route context would have the same results as the custom context. So a specific route context only makes sense if you have too many cached block variations because the block is used in different routes or because of other route parameters and the context aware block plugin doesn't have already an appropriate cache context.


Configuration of views with entity reference fields

The images are referenced to the main content type via an Entity
  Reference field.

Who has the entity reference field? The Main content type (aventuras)?  OR the Images content type?

Based on your question, I will guess the Main content type.

If the Main content type has the entity reference field, then under Advanced you need to add a relationship of Referecing and NOT Referenced Entity (notice the bold endings).

Also, no need to add a relationship in the image field.


I don't know exactly how your CAPTCHA module works, but one possible problem is that the checkout form uses button level validate / submit handlers instead of the form level handlers your CAPTCHA module might be working through. In Drupal forms, if the button used to submit the form has those handlers, the form level handlers will be ignored.


I found The good solution for validate nested form elements
according to drupal 7 form_set_error api need to use

form_set_error('myporifletypename][myfieldname', 'my error message');

As example

 form_set_error('user_info][field_nationalcode', 'Your National code not valid');


Try this:

$base_protocol = empty($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ? 'http' : 'https';
$base_url = $base_protocol . '://www.mysite.com';

Though you may need the Secure Pages module for it to work, or to have redirection set up in your .htaccess file or virtualhost.


Is it possible to translate the suffix of an integer field?

I didn't find a solution to actually translate the suffix. Instead I added a rewrite of the field in the view where it was used, and rewrites show up in the translate settings in the view.

So the solution is, don't use a suffix. Instead add a rewrite option to the field where you use it, and translate that rewrite option instead.


Calculate sum in View of ISO-style timestamps

Imho your two best bets would be to either create a custom formatter, or to use hook_field_attach_view_alter() to modify the display (this answer might help if you go down that road). I'd be happy to expand on either of those methods.

Is there any reason you're using a text field? I would've thought a dedicated duration field would've been the way to go. I've never used any myself, but Google suggests: HMS Field, Time Period. Have you had a look at them? They might already have a formatter that supports what you want (a longshot, perhaps!).


Drupal View rewriting output of the field

Without seeing your view, it is difficult to solve. But if you edit the taxonomy field in your view, make sure that in the MULTIPLE FIELD SETTINGS section the checkbox "Display all values in the same row" is checked. That should display the taxonomy terms as term 1, term 2, term n.


Author image not rendering in node twig file

To get the image uri value, try the following:

{{ node.Owner.user_picture.0.entity.uri.value }}


How to skip step 1 on multi-step/wizard webform?

You can autosubmit step1 using JavaScript and it will direct user to step2.
You can use Drupal behaviour so that no one can see step1.


How to send email depending upon hidden component value (which will get from url)?

Webform rules
If you'd use the Webform Rules module, you have the power of the Rules module available to produce such eMails. Some details about Webform Rules (from its project page):

This module adds rules integration on webforms.
Did you ever want to react on webform submission using rules but couldn't find the proper event?
Webform Rules makes it possible to catch webform submissions by rules and do whatever you'd like to do with it (meaning: do whatever rules let you do with it).

Rules URL argument
And to make the value of URL arguments available as a new variable to Rules, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

... provides two rules conditions based on URL arguments:

check if a URL argument is present.
compare the value of an URL argument.

It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.
For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Cant get desired results for multiple sort criteria in a view

Can i suggest removing the grouping and getting the single table to display as you would like it and then once you have done that apply the grouping. It sounds as if youre sorting by points not by car class - can you change the sort to car class then add the group.

Or group by event and then sort by car class and points.


Rules, User registration, loop through other users with condition, set field value to 0

Assuming your Rules event is User Updated and you don't have hundreds / thousands of users referencing each of the nodes,

Use the Action: Fetch Entity by Property [User>Entity Reference Field] and give it the Entity Reference of the Updated User. This will give you a list called Entity Fetched.

Create a Loop using Entity Fetched
Add an action to the Loop (on the right) and Set a Data Value: [List Item>Field>Not Current Owner]
Under the loop, Set a Data Value: [Updated User>Field>Current Owner]

That will save each user that references the node.

If you don't want that because of performance etc.,

You would create a Rules component and send each List Item in Step 2 above.
Then in that rule component, have a condition that checks the user's Current Owner field is set to True, and have an action to set it to false.
Do step 3 as above in the main Rule to set the current user as owner.


In settings.php set:

  $conf['password_count_log2'] = 1;

You will speed up how drupal handles user passwords: The problems reported here: https://www.drupal.org/node/2200181 ... seem to match yours, first 2000 in X seconds second 2000 in X.Y seconds etc...

Also, in php.ini set:

  max_execution_time to 0 (for unlimited) or a high number like 3000 rather than the default 30.

NB. Be sure to return the execution time to its default setting after the migration.


Unable to change date format on node created field

One way to do this is using a preprocess hook in your .theme file. There you can do pretty much anything with that variable.

Here an example:

function [theme_name]_preprocess_node(&$variables) {
  if ($variables['display_submitted']) {

    // Getting the node creation timestamp from the node object.
    $date = $variables['node']->getCreatedTime();

    // Here you can use drupal's format_date() function, or some custom php date formatting.
    $variables['date'] = format_date($date, 'medium');
  }
}

In an earlier beta, before being able to alter the 'date' variable, I had to  first pass the string through the create() method of the SafeString class like this:

$variables['date'] = \Drupal\Core\Render\SafeString::create('your dangerous new date string')

This might not be necessary anymore, concidering all the recent fuss around the safe string functions.
Edit: I still need to do that in beta15.


If you are using l(), you would do something like this to create news?pid=3.

l('Link Text', 'news', array('query' => array('pid' => '3')));

If you have other query parameters, you can add them in like this:

l('Link Text', 'news', array('query' => array('pid' => '3', 'foo' => 'bar')));

and that would create news?pid=3&foo=bar.

More information on l() here and url() here.