Filter a field (with regex) in a view I have a view with a field Title that needs to be filtered before being sent:

Users fill a tracking number and press Enter
This number is actually related to a node id
If a user enter "123 123" or "#123123" it will not work because of the space and/or the # symbol

My first guess as a non-expert in Drupal (and coming from other CMS and PHP Framework) would be to add a filter to this input with a regex on it to get rid of all characters that are not 1-9. However, I tried to accomplish such a thing in creating a Filter Critera but it does not seem to be the solution.

Do you have any recommendation to do such a thing?

Thanks

"Filters" have certain meaning in Views. They are this little things that give "go" or "no-go" to result rows. What you seems to want is to rewrite user's input, not filter.

hook_form_alter I see in your tags is actually a good call. You can use it to append AJAX to onblur and make it rewrite field. Or you can use validation function

function yourmodule_form_validate($form, &$form_state) {
  $form_state['input']['yourfield'] = _mymodule_sanitize( $form_state['input']['yourfield'] );
}

to rewrite it after user's submit, but before it is used by views. This function takes &$form_state by reference. It means you are allowed not only to read it, but also write to it, and your changes will be visible for all submit functions attached to your form, and will be used in next rendering of your form in case of validation errors or multis-tep forms.


Add content to same page drupal 8 I got a drupal 8 home page wich works fine but all my content on that page is in the same textbox like this image here:

How can I make it so I can seperate this content and still show it under each other on the home page? This makes it way easier to edit and add new content to the page instead of editing this huge textbox of html code I got now.

I just want it so you can just press the "add content" button and it adds a new html section to the page where you can create a image slider or something and this stacks up under the content that allready  has been added.

If i press the add content now it creates a new node/# page wich I dont want. I just want the content on the home page if i press the add content button there.

Just create "promoted to the front page" nodes and keep node as your front page. The "add content" button you wanted is the node/add page. This has always worked with Drupal stretching back many years.


Autopost from Drupal to Pinterest? Is there a way to autopost images that are inside nodes from Drupal to Pinterest?

You could set something like this up, by using Rules+Mime Mail+IFTTT.

Set up a recipe in IFTTT that

Gets triggered when it receives an email by a specific address
Posts on Pinterest as a reaction, using the attachment in the email
https://ifttt.com/channels/email/triggers/50-send-ifttt-an-email-tagged

Configure Rules to send an email on an appropriate event, e.g. node updated/created

You need to use the Mime Mail to get the option to add attachments to your outgoing email
Check out this video for further information: Learn Drupal - Send email with attachments via Rules
You may need to configure your Drupal instance to use SMTP authentication on yor outgoing server to make it work with IFTTT. The PHPMailer module will probably help you with this.

Hope this helps, good luck!


How to show different entity in Views with different displays? I create a views with 2 displays.

One display show content type.

One display show taxonomy list that related above content type.

When I try to create a display with content type, then I can not create a display with taxonomy.

Content type and taxonomy are different entity, So How to show different entity in Views with displays?

You have to add relationships Content: Taxonomy terms on node then you will get options to add taxonomy in filter criteria and fields


create a copy of a field-collection for entity clone I have a use case where I need to create a copy of an entity (commerce product) that is home to various field collections.

the entity is created by a simple load/save combo:

// load entity
$old_entity = commerce_product_load_by_sku($sku);

// copy
$new_entity = $old_entity;

// alter copy so it can be saved as a new entity
$new_entity->status = 0;
$new_entity->title = $old_entity->title . '(COPY)';
$new_entity->is_new = TRUE;
// [...] and a few more unsets (created, revision, copying translations...)

// ->>> missing field_collection clone / exchange of id references in the entity here <<<-

// save entity
commerce_product_save($new_entity);

As the field_collection id stored in the entity remains unchanged, both entities now share the field collection which leads to unwanted effects.

Can someone point me to a reference on how to create copies of field_collections and get their id's returned, so I can exchange them in the parent entity before saving it? ... or maybe there is an even better way to deal with this?

This has been solved by chalee on d.o on the following issue: Integrate node_clone with field_collection module.

This is his function that works just fine for my use case:

<?php
function clone_fc_items($entity_type, &$entity, $fc_field, $language = LANGUAGE_NONE){
  $entity_wrapper = entity_metadata_wrapper($entity_type, $entity);
  $old_fc_items = $entity_wrapper->{$fc_field}->value();
  if (!is_array($old_fc_items)) {
    $old_fc_items = array($old_fc_items);
  }

  $field_info_instances = field_info_instances();
  $field_names = element_children($field_info_instances['field_collection_item'][$fc_field]);

  unset($entity->{$fc_field}[$language]);

  foreach ($old_fc_items as $old_fc_item) {
    $old_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $old_fc_item);
    $new_fc_item = entity_create('field_collection_item', array('field_name' => $fc_field));
    $new_fc_item->setHostEntity($entity_type, $entity);
    $new_fc_item_wrapper = entity_metadata_wrapper('field_collection_item', $new_fc_item);

    foreach ($field_names as $field_name) {
        //if (is_array($old_fc_item->{$field_name})){
            if (!empty($old_fc_item->{$field_name})){
                $new_fc_item->{$field_name} = $old_fc_item->{$field_name};
            }
        //}
    }
    $new_fc_item_wrapper->save();

    //Now check if any of the fields in the newly cloned fc item is a field collection and recursively call this function to properly clone it.
    foreach ($field_names as $field_name) {
        if (!empty($new_fc_item->{$field_name})){
            $field_info = field_info_field($field_name);
            if ($field_info['type'] == 'field_collection'){
                clone_fc_items('field_collection_item',$new_fc_item, $field_name,$language);
            }
        }
    }

  }
}
?>

Again, kudos goes to @chalee - thanks :)


Alter dynamically line item price on cart (drupal commerce) I want to alter a product price (for example saved at 0.70€ in store). I pulled the hair several hours to find how to change the unit price (and the impact on the total price by changing the quantity) when putting the cart and / or from the time we are on the cart .

In fact, I need a base price, and according to certain client I modified by an external data (webservice). This modified price should not be saved but just used to that moment until the checkout process is complete.

In everything I tried, including the hook_commerce_cart_line_item_refresh() the price is never changed.

An idea to save me?

Have you read any of the product pricing rules documentation or watched the tutorials on DrupalCommerce.org? It's all in there: http://www.drupalcommerce.org/user-guide/product-pricing-rules-screencasts

In other words, you shouldn't be hooking into anything, you should be using Drupal Commerce's core product pricing rules system. This is the only supported way to make consistent line item unit price alterations that are reflected in the final order total.


Owl Carousel does not respect Image Styles as set in node display in custom node file I am trying to get owl carousel to respect the image style declared in the manage display setting for the content type. The code I used to output in the node is:

            <?php foreach($image as $value):?>

                    <img src="<?php print file_create_url($value['uri']);?>" class="img-responsive"  alt="">

            <?php endforeach;?>

This renders the slides all different sizes and makes it have a background and causes it to look bad. Does anyone know how to in a custom node file make it respect the image style that I have created that cause it to scale and crop the images. Thanks.

Just to summarize my comments:
 1. after getting the images' URLs, you can run them by image_style_url() function to get the URLs to the styled images.
 2. you need to update the foreach() function to include an index such as foreach($image as $key=>$value), and use the $key index to loop through the image array.


How do I add Emoji smileys? I want to add Emoji smiles in Drupal 7 comments without using a sandbox project like https://www.drupal.org/sandbox/mparker17/2078481.

Does anyone have any idea how to add Emoji smiles in comments?

According to Drupal 7.50 released, Emojis were added as a new feature in 7.50

  Support for full UTF-8 (emojis, Asian symbols, mathematical symbols)
  is now possible on MySQL

  If content creators on your site have been clamoring to use emojis,
  it's now possible on Drupal sites running MySQL (it was previously
  possible on PostgreSQL and SQLite). Turning this capability on
  requires the database to meet certain requirements, plus editing the
  site's settings.php file and potentially other steps, as described in
  the change record.


Include a module template into an other module template I'm working on a Drupal 8 project and in my module X twig template I need to include the template of an other module Y. All what I found in documentation is how to call a template inside other template in theme see here

I've tried in my twig-of-module-X.html.twig file:

{% include 'modules/Y/templates/twig-of-module-Y.html.twig' %}

but doesn't work!
Any suggestion please?

Include the template file with its namespace:

{% include '@modulename/template_file.html.twig' %}

{# @modulename refers to 'path_to_module/templates' #}

Drupal provides a @namespace for Twig based on the machine name of every module and every theme. The @namespace points to the templates sub-directory of that module or theme.


'image_style' entity with ID 'media_library' already exists Recently updated Drupal to 8.7.1 and I am seeing the following error when running database update:

www-data@php.container:/var/www/html/web $ drush updb -y
The following updates are pending:

media_library module :
  8701 -   Create the 'media_library' image style.
  8702 -   Updates the media library view widget display (contextual) filters.

comment module :
  Add comment settings.

media_library module :
  Create and configure Media Library form and view displays for media types.
  Add a table display to the media library view and link gridtable displays.

media module :
  Keep media items viewable at media{id}.

menu_link_content module :
  Update custom menu links to be revisionable.

system module :
  Initialize 'expand_all_items' values to system_menu_block.
  Clear the menu cache.   @see https:www.drupal.orgprojectdrupalissues3044364

taxonomy module :
  Update taxonomy terms to be revisionable.
  Remove the 'hierarchy' property from vocabularies.

views module :
  Update exposed filter blocks label display to be disabled.
  Rebuild cache to allow placeholder texts to be translatable.

Do you wish to run all pending updates? (y/n): y
'image_style' entity with ID 'media_library' already exists.                                          [error]
Performing media_library_update_8701                                                                     [ok]
Failed: 'image_style' entity with ID 'media_library' already exists.                                  [error]
Cache rebuild complete.                                                                                [ok]
Finished performing updates.                                                                             [ok]

I was able to fix this by doing the following:

Removing the media_libary (I'm using git but if not you can move it somewhere):

rm image.style.media_library.yml
rm views.view.media_library.yml

Run configuration import:

drush cim -y

Now run database update:

drush updb -y

Now add the removed config items back in:

git checkout ./

Run configuration import again:

drush cim -y

Now you should be all set.


update drush 6.0 to 6.5 I have drush 6.0 and recently installed drush7 as well with composer. Now i would like to update drush 6.0 to latest release in drush version 6. Is there any work around to achieve?

Thanks,
Swaroop.

As the instructions say:

  To install Drush 6.x (stable):

composer global require drush/drush:6.*

Assuming you installed drush that way (using composer):

  To update to a newer version (what you get depends on your
  specification in ~/.composer/composer.json):

composer global update


Making an ecommerce photography competition website This has been bugging me for days, I just can't wrap my head around this situation/process and how to make it work in Drupal.

I'm making a photography competition website where a user who signs up and buys a role has the choice to upload 3(costs £4), 10(costs £6) or 20(costs £10) images but each image needs to be a part of a competition category, so say someone uploads 3 images, one is for black and white category (taxonomy term), one is for wide angle and one is for sport, each image needs to be tagged with the correct category, of which im using taxonomy terms. But how do i go about this?

Firstly limiting the user to said amount of photos? I was thinking they buy a role (there are 3 roles), role one allows to upload 3 images using the content type 3 images, role two allowed to upload 10 images on a node and the final content type is '20 images' and they can upload up to 20 images using that content type, each user though must be able to categorise each individual image using the taxonomy vocab already created called Photo Categories. How the hell do i tag each individual image so that they are categorised and ready for viewing/judging later on??

Should I do this on the user profile instead? So that when they buy their role, they can then upload the amount of photos that they are allowed to? This will still mean I have the problem of assigning each image to a taxonomy term.

Also, is purchasing a role the best way to go about this? Now that you know what I am after what are your thoughts? I know Drupal can do this 'out of the box', i'm just struggling to see what workflow the end user will go through to achieve all of this.

I would look at Node Limit. So the user buys roles and that gives them access to create more content.

Then create a content type for Entry with all the appropriate tag fields.

I like the purchasing the role structure. I wouldn't do this directly on the user


User password reset - redirect one time login to another page By default, if user submit his email in form at /user/password page, he will recieve an email with one-time login link. After opening this link he is redirected to page with form with one single "login" button - id of this form is user_pass_reset. After click on this button user is redirected to his profile in administrative part of a site: /user/X/edit where he can change his password.

But I have my own custom profile page, where users can change their password and I'd like to redirect user here instead of default profile in administration interface. I already found that user module is checking if old password is needed with this line:

$pass_reset = isset($_SESSION['pass_reset_' . $account->uid]) && isset($_GET['pass-reset-token']) && ($_GET['pass-reset-token'] == $_SESSION['pass_reset_' . $account->uid]);

But I can't find out how to redirect user to my own form on user_pass_reset submit. If I alter this form and change '#action' paramter I get a message that says this one-time login link is invalid. If I add my own submit function $form['#submit'][] = 'activit_password_redirect'; and in this function I call drupal_goto('my/own/form/page') user is still redirected to default profile page.

Is it possible to change url of this form submit?

Use hook_form_alter, then add a  $form['#redirect'] parameter with value as your custom user profile page.

OR
 append a destination query to the default form action url.

<default_action_url>?destination=<your_custom_user_profile_url>

I recommend the first option. It's the Drupal way.


Is it possible to unset private_tempstore values? I have a block that creates a private_tempstore value (which I understand works exactly like PHP sessions).

How do I unset that value.

This is the code I am using for the block.

class SsoSessionBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build(){
        $value = 'dav';
        $session = \Drupal::service('user.private_tempstore')->get('achva_sso');
        $session->set('name', $value);

        return [
            '#type' => 'markup',
            '#markup' => $this->t('The output of super SsoSessionBlock block.'),
        ];
    }
}

I saw this method, but I am not sure how I am supposed to use it.

I tried the following code, but I get an error.

namespace Drupal\achva_sso\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\user;

class SsoController extends ControllerBase{
    public function ssoLogout(){

        $session = \Drupal::service('user.private_tempstore')->get('achva_sso');
        PrivateTempStore::delete('name');

        if(isset($session)){
            $status = $session .' is logged in';
        }else{
            $status = 'is logged out';
        }
        return[
            '#type' => 'markup',
            '#markup' => '<p>' . $status . '</p>' ,
        ];

    }
}

How do I unset a value I previously set?

delete() is the method to delete a value in the store.
$session = \Drupal::service('user.private_tempstore')->get('achva_sso');
$session->delete('name');

'name' is the value passed as first argument in any call to set().
You don't use PrivateTempStore::delete() since it's not a static method and it would throw errors or warnings, if called as static method.
As side note, user.private_tempstore is a deprecated service. Instead, the tempstore.private service should be used. (See User module's user.private_tempstore and user.shared_tempstore services moved to core for more details.) In the latest Drupal 8.5.x version, the service is marked as deprecated directly in the user.services.yml file.
class: Drupal\user\PrivateTempStoreFactory
arguments:
  - '@keyvalue.expirable'
  - '@lock'
  - '@current_user'
  - '@request_stack'
  - '%tempstore.expire%'
deprecated: 'The "%service_id%" service is deprecated. You should use the ''tempstore.private'' service instead. See https://www.drupal.org/node/2935639.'
tags:
  - { name: backend_overridable }

It should also be better to use dependency injection: A class extending BlockBase, or ControllerBase, can implement the create() method to load new dependencies.


fields with Image styles only showing placeholder I've got some images that's set to be shown in specific image styles. They appear fine on each node but in teasers and views I only get a placeholder.

The console in Chrome's inspector says:

  Failed to load resource: the server responded with a status of 500 (Internal Server Error)

The Files folder has permissions set to 775. Should be good, right?

Any ideas?

Here is an overview of how file permissions should be set on a Drupal installation: https://www.drupal.org/node/244924

If you scroll down there is a shell script that you can install on your server and it will fix all file/folder permission errors.

Your issue is definitely a folder permission error, Drupal has to be able to write to the /files folder. It makes new directories for each style, each image, each size so one folder may exist but the others may not be able to be made.


How to apply single theme to all webform in drupal 7 I want to create a theme or page layout which will be applied to all the existing and newly created webforms. I want to divide page in 2 parts. In left part want to show webform description and in right part all the webform components.

Easiest way would be using a module like Display Suite to change the page layout of your webforms on it's 'Manage Display' settings. Using a two column layout, you can arrange the content on the left side and webform on the right (webform being all fields you create on the webform part of the node).

If you don't want to use a module just for that, another option would be rewriting the webform node template yourself. For that, copy your theme's node.tpl.php and rename it as node--webform.tpl.php. Note that you would have to print out the correct variables on the markup yourself.


(Drupal 6.28) Blocks list suddenly doesn't show correctly I realized today that blocks list (admin/build/block page) doesn't correctly show  all the blocks implemented in the site.
Most of the blocks are set as disabled and others are set in the wrong region, while fortunately the site displays every block still perfectly.
I have a custom theme (Zen subtheme).
The only "strange" thing I did recently was the installation of a new module which involved the assignment of a new block to a region.
Is there any way to restore the correct blocks list?
Maybe if I don't make any change to blocks system (and save the new configuration), my site will always display correctly, but I would prefer to have the correct blocks list restored.
Yes, I could draw a manual scheme of all blocks in the site (pages, views, etc.) and use it in case of disasters, but if I could restore it with a module it would surely be better
Thanks

That to me looks like an issue with theme update. Did you changed your theme recently. It yes, then try clearing your cache.


Get form ID on hook_entity_presave() I want to process some details before saving the node in Drupal 8. How will I get the form ID of the submitted form?

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->getEntityType()->id() // this only prints "node"
}

Is there any other workaround?

hook_entity_presave() doesn't get the form ID, and this makes sense: An entity could be programmatically saved from a module or a Drush plugin without showing to the user a form to edit/create the entity.

Since you just want to know if the entity is being edited or created:

You don't need to know the form ID
You can use hook_entity_presave() or hook_ENTITY_TYPE_presave() with code similar to the following one

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->isNew()) {
    // The entity is being created.
  }
}

As side note, $entity->getEntityType()->id() returns 'node' as expected: You are asking to the entity object its entity type, and for nodes that is clearly 'node'.


My custom page.tpl.php file is not picked up I have a site running in a subdir of my main site, like www.mysite.com/drupal.

I want to use a separate page.tpl.php file for my about page www.mysite.com/drupal/about.

I have tried naming the file page--about.tpl.php and page--drupal--about.tpl.php but neither is working. It just loads the regular page.tpl.php file.

This seems really straightforward and one of those should be correct. Is this buggy because Drupal is in a subdir or am I doing something wrong?

(And yes, I've cleared the cache.)

have you seen through your theme suggestions for the about page?

If not, then please refer to it and create a tpl file according to the suggestions and you will see that particular template running for "about" page.

As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments).

  To enable it, add this line to your settings.php:

$conf['theme_debug'] = TRUE;

  OR,
  You can enable it with drush using:

drush vset theme_debug 1

  And disable using

drush vset theme_debug 0

Note: You'll then see output like this when you inspect or view source:

<!-- THEME DEBUG -->
<!-- CALL: theme('page') -->
<!-- FILE NAME SUGGESTIONS:
   * page--front.tpl.php
   * page--node.tpl.php
   x page.tpl.php
-->
<!-- BEGIN OUTPUT from 'modules/system/page.tpl.php' -->
…
<!-- END OUTPUT from 'modules/system/page.tpl.php' -->


How to login into Drupal 8 using Ajax (REST API) I want to login in my Site Drupal 8.2.3 from another application using Ajax,
but is returning error all the time.

$.ajax({
    url : "http://localhost/Drupal-tuto-test/user/login",
    type : 'POST',
    data: {
        'username' : 'admin',
        'password' : 'admin'
    },
    dataType : 'json',
    error : function(data) {
        console.log('Error ',data);
    },
    success : function(data) {
        console.log('Success ',data);
    }
});

Your POST data isn't correct, you should be using "user" and "pass". For a a more complete response, see my answer here.


Migrating orders doesn't migrate total values Has anyone tried migrating commerce orders? I had problems tracing the tables that was used by commerce order.

Initially, I've already mapped commerce_order_total and commerce_order_total:currency_code (in the ui: http://prntscr.com/9a6bid). My query from the source database also outputs correctly. My problem is after migrating, commerce total values were not migrated (http://prntscr.com/9a6cko).

Am I in the right track? Please help.

I'm also confused why commerce_line_item is needed in commerce order and order_id is needed in commerce line item. I'm really confused.

Are there any existing useful links regarding this?

Thanks for any help!

The bi-directional link is a relic of the Drupal 7 entity API at the time we wrote Drupal Commerce 1.x. It was basically a DX concession of dubious benefit, but we'll be fixing that in 2.x. ; )

As for how order totals are calculated, order save automatically calculates the total by summing up all of the price components in the "total" price fields on line items. If you haven't properly set the associations in your line items or if you haven't set the price component arrays for the line items you've created, your order total will not calculate properly.


Theme hook suggestions for the breadcrumb block I'm using the Omega theme with the Delta module.
How can I theme the breadcrumb block using block--breadcrumb.tpl.php?
I want to change the output of the block to something similar to the following.

You should copy theme_breadcrumb to your theme's template.php file:

function YOURTHEME_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];
  if (!empty($breadcrumb)) {
      $crumbs = '
';
      foreach($breadcrumb as $value) {
           $crumbs .= '
'.$value.'
';
      }
      $crumbs .= '
';
    }
      return $crumbs;
  }

By this function you can set up a ui li structure.


Cannot use drupal_set_messages in a custom controller module In a custom controller, when I try to use drupal_set_message() in a custom Module Controller it works only if I put :

drupal_set_message('Test error', 'error');

return array(
   '#type' => 'markup',
   '#markup' => "Welcome",
);

=> the message is shown via {{ page.highlighted }}

If I put :

drupal_set_message('Test error', 'error');

return array(
   '#type' => 'page',
   '#markup' => "Welcome",
);

It doesn't work... I need to put a type page to be able to inject custom variables. Does anybody can help me to understand how it works ? I try to read the docs and a Drupal 8 book but I really don't understand how that works.

Thanks !

You might want to try

return array(
  '#theme' => 'ctr',
  '#myvar' => 'myvalue',
);

And then define a hook_theme.

/**
 * Implements hook_theme().
 */
function ctr_theme($existing, $type, $theme, $path) {
  $variables = array(
    'ctr' => array(
      'template' => 'cntr',
      'variables' => array(
        'myvar' => 'defaultvalue',
      ),
    ),
  );
  return $variables;
}


Why do I get an error about the modules/custom directory not existing? I have installed Drupal 8 on Ubuntu. All works well, but I cannot create a new module using Drupal Console.

When I run drupal generate:module, I get the following error message.

  [InvalidArgumentException]
  Module path "/var/www/html/maryem/modules/custom" is invalid. You need to provide a valid path.

Why? How can I avoid that error message?

There is no such thing as modules/contrib or modules/custom with the vanilla download of Drupal.

It is a convention you can use for organization. Create the folders yourself. Drupal will still find the modules in either one. The same principle applies to the themes folder. Some modules that say "download the JS plugin to /libraries" - you would have to create this folder too.

Drush, Drupal Console, and Composer all understand this, as well. If you are using Composer, you just need to inform it in your root composer.json, example:

    "installer-paths": {
        "docroot/core": [
            "type:drupal-core"
        ],
        "docroot/modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "docroot/modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "docroot/profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "docroot/profiles/custom/{$name}": [
            "type:drupal-custom-profile"
        ],
        "docroot/themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "docroot/themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ],
        "docroot/libraries": [
            "type:drupal-library"
        ],
        "drush/contrib/{$name}": [
            "type:drupal-drush"
        ]
    }

When requiring modules, profiles, or themes, Composer will then place them in the appropriate directory.


How To Pass Taxonomy Term (Name) to Filtered View (ID) - Drupal 7 I have a custom view (page) created using Views in Drupal 7.

It contains a taxonomy field and an (exposed) taxonomy filter. When viewing the custom page/view, it works exactly as needed and a user can select a taxonomy filter to limit results accordingly. For example, the default view is /books and the user, via the exposed filter can select /books?book_type[]=21 to show only the books that have taxonomy ID 21.

The problem I am experiencing is that I need a second custom view (essentially a series of thumbnails, each depicting a different 'book_type') to link directly to the /books?book_type[]=21 URL path. Within this second view, I have added the appropriate taxonomy field and via the Rewrite Results option of the field, I have selected Output This Field as a Link and inserted books?book_type[]=[field_book_taxonomy], where [field_book_taxonomy] is the referenced taxonomy field.

When I view this thumbnail page, the link works, but the URL contains the taxonomy name rather than ID. So whilst I need /books?book_type[]=21, the page receives /books?book_type[]=ficton.

I have tried various Contextual Filters, including Term Name converted to ID, but the URL always passes name and the page therefore returns "An illegal choice has been detected".

Ideally I would like to retain the path /books?book_type[]=ficton on the initial view and have this interpreted successfully by the actual filtered view.

Please can someone offer a pointer as to where I am going wrong with this?

Thank you.

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

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


How to add a user-friendly option to link to nodes from body text or text-field? I'm looking for an option or module that provides the possibility to link to other internal nodes avoiding the usage of full html in a text field. Users should be able to highlight a term and assign a link to it. It would be nice to have a kind of select-list containing the available nodes to link to.

I have done this before, but only for external links and with a minified editor. But i have no idea how to put a list of nodes there. Is there an alternative to achieve this?

Sounds like you're looking for the LinkIt module.

  Linkit provides an easy interface for internal and external linking.
  Linkit links to nodes, users, managed files, terms and have basic
  support for all entities by default, using an autocomplete field. In
  7.x-2.4 there is also support for fields (text, textarea, and link).

If you have pretty paths I'd also suggest combining it with Pathologic, that way your links will have their path aliases applied rather than their direct links (i.e. node/123 will become about-us)


Images loading fine on day 1, broken on day 2 Strange problem.

Images on my production site are 100% working at one point (right after getting a refresh from staging), and within a day or two, some images on some pages become broken links.

(Production is updated from staging through mysql database dump/restore).

As I continue to watch this over the course of subsequent days, more pages in production experience this symptom, but the images are always there in staging - never broken.

Here's some data...
When viewing the content of a page in the staging environment, an inserted image looks like this (Admin UI - view Source).

...installed one of the Outlook toolbars.

[[{\"type\":\"media\",\"view_mode\":\"media_large\",\"fid\":\"123\",\"attributes\":
{\"alt\":\"\",\"class\":\"media-image image-style-large image-style-large image-style-large\",
\"height\":\"298\",\"typeof\":\"foaf:Image\",\"width\":\"264\"}}]]

Who can ...

When the Staging content is pushed to Production, viewing the same page in the Admin UI on the production server, the content starts out exactly the same and the image renders fine.

Within a day or two, the Production page changes (presumably by something Drupal Cron is doing) to something like this:

...installed one of the Outlook toolbars.

Who can ...

The "img src" version that creeps in is a bad URL -

http://default/sites/default/....

I've grep'ed my daily mysqldumps for this bad URL string, and each day there are a different number that creep in.

    for file in /data/mysqldumps/*sql
    do
      echo -n $file
      echo -n ": "
      grep -o "http://default" $file | wc -l
    done

/data/mysqldumps/20121205-160101.sql: 0 (Zero occurrences on Dec 5 because I pushed
                                         on that date, & all images were known good)
/data/mysqldumps/20121206-160101.sql: 106
/data/mysqldumps/20121207-160102.sql: 130
/data/mysqldumps/20121208-000101.sql: 138
/data/mysqldumps/20121209-000101.sql: 157
/data/mysqldumps/20121210-000101.sql: 158

No local Admin changes have occurred on production, and nothing but cron is running there.

What can be causing this? It's only happening in production (which is totally awesome).

Any suggestions on troubleshooting?

Thanks,
Mark

There is a related issue for this here. http://drupal.org/node/1352182.

What's happening is that drupal is storing the URL that is created when the page is first viewed after the cache is cleared. Normally that would be your site url, but sometimes it's not.

In the issue linked you see that some people fixed this using the Pathologic module.


Not able to change the settings.php I am working on drupal commons, and using pantheon servers for hosting. The major problem I am facing is the server database config issues. I am not able to change the settings.php file. Also Pantheon every now and then changes their db server password. How can I control this ? is there any server variable for the db instance, port, user id, password ?

Drupal removes "write" permission from settings.php, so to edit it, you need to give this permission back.

SSH

chmod u+w sites/default/settings.php

FTP, SFTP and alike

Use your cilent, and just tick appropriate checkbox. Like this:


Gray overlay and no dialog when clicking Image button in CKEditor Attempting to get CKEditor and Media to work together on a Drupal7 site. Things are mostly working great, but when I click the regular Image button (or double-click an image, or use the context menu to access image properties), I get only a gray overlay and no dialog window.

I'm using CKEditor 7.x-1.18 with the 4.10.0 FULL library locally installed (in libraries), as well as CKFinder 3.4.4 (also in libraries), all with Media 7.x-2.19 and the Media CKEditor 7.x-2.5 bridge module.

When I click the Image button, I get this error in console:

TypeError: Drupal.settings.picture is undefined[Learn More] plugin.js:152:15
init/<
http://example.com/sites/all/modules/picture/ckeditor/plugins/plugin.js:152:15
n
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:10:222
CKEDITOR.event.prototype</<.fire</<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:12:42
CKEDITOR.dialog
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:594:500
openDialog
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:642:134
openDialog/<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:642:492
e
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:175
y
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:332
v
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:258:412
A/e.$.onload/<
http://example.com/sites/all/libraries/ckeditor/ckeditor.js:259:327

I'm not Drupal-technical enough to understand this error entirely. But my intuition is that I don't have something configured correctly. (Installation instructions I have found are so ancient, I'm not even sure the module supports this version of CKEditor.)

After discovering that the Image button works fine in the default "Advanced" text format, which I did not modify, and which doesn't have the Media button added, I started investigating differences.

Turns out that if I disable the Picture module in Editor Appearance > Plugins, things work.

I just don't know what I'm giving up by disabling this. I would like images to be responsive. :-(


Unset widget tab from media browser programmatically Need to unset a widget tab from media browser based on the condition of media type supported by the field.

Media types: Image and Video.

For example, There is a field which references image media type only. When the media browser appears on the form, it displays create embed tab as well to embed the videos.

As the field doesn’t reference the video media type, need to unset the tab programmatically to help the content author.

I have tried the form alter, but I don't get any information about the media type referenced by the field in the hook.

It should be possible with some code like this:

function MY_MODULE_form_entity_browser_MY_FORM_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#pre_render'][] = 'MY_MODULE_pre_render';
}

function MY_MODULE_pre_render($element) {
  kint($element); //Find the tab you want to remove.
  if (...) {
    unset($element['...']);
  }
  return $element;
}

Another commonly used solution is to create 2 or 3 media browsers depending on your needs.
So you will have an image media browser, a video media browser and an image + video media browser.

Then you just select which one to use in the field settings.


How to count number of field collection items for a row in a view? I just want to count the number of field collections items in a row. I am working on a view. In the view I am able to show the field collection items value, but I do not want the value I just want to count number of items per row.

I am trying view aggregate but its showing sql errors.

While it may be possible with just using Views. I find it easier to do this type of 2-step logic in Drupal with additional information.

For example use Computed Field module to store an integer value in the field on node save for a custom computed field called number_of_fc_values or whatever you want to call it. You then just count the number of field collection items on save using PHP.

For example your PHP could look like the following for the computed value PHP field, this example API usage is taken from https://drupal.stackexchange.com/a/84282/3279

$node_with_fc = node_load($node->nid);
$items = field_get_items('node', $node_with_fc, 'NAME_OF_FC_FIELD');
return count($items);

Now in your View you simply add your number_of_fc_values field to the field values for the row display.


How to let administrators AND anonymous users create new accounts? I need to let anonymous users create his/her own accounts. But also I wish to create accounts when logged in as administrator. Is it possible such configuration? In admin/config/people/accounts is not possible, it just let you choose between exclusive options...

You can always create users as an administrator by going to admin/people/create.

So, in admin/config/people/accounts, in the Who can register accounts? you can choose Visitors and you will be good to go.


Entity Print PDF Layout for Views page My requirement is to convert a views page into a PDF. I have created the views page with table formatting and a PDF plugin attached to the header that allows one to download the views page as PDF. I created an entity-print.html twig template and an HTML structure copied from the answer in this post How to customize entity print pdf and created a twig variable 'footer' in THEME_preprocess_page function in the theme's .theme file but the calls {{ footer }} to that variable in the template returns nothing.
In other to at least test CSS formatting, I placed these in the respective files:
ENTITY-PRINT.HTML.TWIG

    <meta charset="utf-8">
    <title>{{ title }}</title>
    {{ entity_print_css }}

{# The footer is repeated on all pages and must be printed first. #}

    {{  footer  }}

{%  if cover_page  %}

    {{ cover_page }}

{%  endif  %}
{# The header is repeated after the cover page for all pages. #}

    {{  header  }}

    {{ content }}

THEMENAME.THEME
function THEMENAME_preprocess_page(&$variables) {
  $variables['footer'] = "HERE IS YOUR FOOTER";
  $variables['header'] = "HERE IS YOUR HEADER";
}

IN .INFO.YML
entity_print:
 views:
   views_page_machine_name: 'theme_name/result-pdf'

IN .LIBRARIES.YML
result-pdf:
  css:
    theme:
      styles/result-pdf.css: {}

IN CSS FILE (i.e. result-pdf.css)
* {
    color: red;
}

div {
    background: blue;
}

and then created result-pdf.css but the styles did not change anything in the generated pdf.
One of the answers in another post Entity print get variable in twig template pointed to creating an entity specific template for layout of the PDF  with HTML as required. For example, for the article content type you have node--article--pdf.html.twig. What is the template suggestion for a views as described in my case?
The question is how do I achieve:

create a HTML layout format that is fed all the fields from the views page
rightly set the footer/header variable for output in the entity-print.html template mentioned above
turn bullet into A pdf (so that the download link on the views page generates the formatted html as pdf).

Perhaps bullet 1-3 is irrelevant, a step by step direction on how to have a views page formatted as required and converted to PDF using the entity print module will be appreciated.

The solution came down to replacing "views" with "view" - without the s and "views_page_machine_name" with "all", such that this:
entity_print:
 views:
   views_page_machine_name : 'theme_name/result-pdf'

became:
entity_print:
 view:
   all: 'theme_name/result-pdf'


What am I doing wrong with accessing this array element? $form['cookie']['saved'] = array(
    '#type' => 'textfield',
    '#title' => 'How long?',
    '#required' => TRUE,
  );

But if I do:

  if ($form_state['values']['cookie']['saved'] == 'Dog the Bounty Hunter') {
    form_set_error('dog_error', t("That doesn't make any sense."));
  }

I get an error that the 'cookie' index doesn't exist.

Install the development module and do dpm($form, 'the form'); and dpm($form_state, 'my form state'); in your form alter function. I believe you'll see that $form_state is "flattened" to only the innermost values of your form array.

So, the saved array key exists, not [cookie][saved].

In general try to make use of this convention, or assumption by drupal. Usually your FAPI form has fieldset(s) as outer keys (not passed into $form_state at all, they only affect the appearence of the form) and input values as inner keys. So rename your 2nd key from saved to cookie_saved.

If you really (for some reason) want the ['cookie']['saved'] to be in $form_state just as-is -- perserving the hierarchy of information. You would want to set the #tree property of cookie in your FAPI array.

See these 2 resources of information:

Legacy drupal page talking about FAPI usage
current FAPI quickstart guide.

Both are relevant for background information how FAPI usage and how its evolved to meet our needs as developers. Search for #tree and #parents within the linked documentation pages.


Show calculated value at the bottom of every node for a specific content type I am beginner in Drupal. I am using different content types and views for my project. Here for specific content type I have created number of fields. Two of the fields are integer field type.

I want to calculate those two fields and show the calculated values at the bottom of every single node for a specific content type.

How can I achieve it? using views or by any other way.

Computed Field module will do for you.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!

if you need this through views, you can check this link there are answers which might help you.

also this module will help you,

Views Custom Field

  Now that the Views module has incorporated the rownumber and markup
  fields, only the PHP field is left for this module. I started a new
  project called Views PHP. It also includes support for PHP filters and
  sorts.


How do I limit webform submissions based on the email address? Is there a way to limit the submissions based on the email address when using the Webform module in Drupal? Right now, there is a setting to limit using the ip address & cookies but I only want to limit using the email address. Anyone has any ideas?

Edit the email field in the webform and check both the "mandatory" and "unique" options. That way, it will not except more than 1 submission with the same email address.


Preprocess SCSS with Zen Theme on MS Server I'm getting familiar with the official documentation of Zen Theme on Drupal 7. I'm wondering about the SASS- and SCSS-Files. The CSS-Interpreter can't understand these files ofcourse. I read about gulp.js which is the preproccessor for SCSS-Files. I also read about the server nodejs - what I used years before - that gulp.js needs for action. I read it here: getting started SASS and Compass

Can someone explain me, how dose MS Server with no Drush works to handle SCSS with gulp.js-File - what is not been found in the Zen Theme-Folder by me - to preprocess clean CSS-Files?

I don't have experience with MS server but I expect the entire process to be the same as described.

This applies to themes in general, not only Zen:

Using Sass preprocess to compile CSS is independent from Drupal, or Drupal themes. This is just an outside tool that you can use to make your CSS life easier, if you are familir enough with CSS and Sass. The end output that themes use will always be CSS, because that is what browsers understand.

Some themes have opted to integrate Sass preprocessing into their workflows. You don't have to use Sass, you can always just override the base CSS that was generated through Sass with your own CSS. But some themes have Sass so tightly integrated that it would a pitty not to take advantage of it. It's entirely your call.

Most of Sass preprocessing situations define which folder on your system contain Sass files, and which folder stores the compiled CSS, they are usually different folders (it's a cleaner practice not to keep the compiled CSS in the same folder as its source Sass). This is what you will find in most themes that use Sass, you will have a dedicated folder for Sass, and another one for compiled CSS, so you can continue using that structure. This structure is then recorded in the gulp.js file, so the preprocessor software knows which files to use as sources, and where to save the compiled code.

If you're not using Sass, but only pure CSS, you should keep your CSS in the third place! Don't keep it in the folder with the compiled CSS, because if a preprocessor is ever triggered, the contents of that folder might be deleted! Keep your dry CSS in a dedicated folder that doesn't have anything to do with Sass. You will add the CSS files to your Drupal theme configuration, so they are applied after all the theme code. This is how you can bypass dealing with Sass if a theme is using it.

Nodejs isn't the only way to get Sass working on your computer, there are other technologies that have it, but either way you'll have to install some engine that makes the Sass processor available.

Once you install nodejs, and the preprocessor packages as noted in the Zen tutorial, you will be able to start compiling CSS out of Sass files "anywhere" on your computer, given the correctly configured gulp.js.

You will probably just want to work on your Zen subtheme, which already comes with a great gulp.js, so if you have the preprocessor installed correctly you can start compiling the Zen subtheme Sass into CSS.

This can be done manually, you edit the Sass files to edit/add new Sass/CSS code, then (through terminal) use nodejs and Sass commands to execute Sass to CSS compiling. So you manually execute the compile command each time you want to compile your Sass changes and test them in browser.

More commonly it is done automatically by using a command to start watching Sass folder (a process is opened on your computer in your terminal). This way when you save changes to a Sass file the processing starts automatically, old CSS files get overwritten with the new CSS that contains the changes. There is also the Browsersync option that refreshes CSS automatically in the page where you're developing (local environment server) but it's more complicated with caching...

So this is what the development steps are with Sass, once you have the preprocessor installed:

Open terminal, go to your subtheme folder
Start watching (there's a command for that, the process is started and is kept active)
Edit the Sass files to make your changes (in what ever editor you usually use)
Save Sass file(s), this is when the preprocessor will compile the CSS, you will see the output in terminal, if you have any errors you need to fix them etc. The output will tell you when the CSS is compiled so you can check your changes in browser (it can be miliseconds or seconds depending on circumstances)
Repeat
When you're done with development you stop watching the subtheme folder after your latest compile (you stop the process you started in step 2)

What is also usually involved in development is commiting changes to Git once you have a meaningful piece to commit (not after every Sass file save). For this I keep another terminal (shell) open, one for keeping an eye on CSS compiling with the watch command, the other for "regular" commands and git.


Filter View by Entity Reference Value From Current Node I've been trying to figure this out for a while now, I believe that this should be easy but I still can't solve it. I'm a beginner at this. -_-

I have 3 Content types

Venue
Food
Package

I have a List of Venue that will be used as reference for the Food. So, The Food content type has an entity reference field -> field_venue

The Food will only be available to the venue it referenced.

The Package Content type has the entity reference Venue and Food. It shows the venue and the food available.

I use Entity Reference View Widget for the Entity reference on Package Content Type. The Venue is working well.

My Problem is the Food.

I need an Entity Reference View Widget (VIEW) that shows the available food for the Venue.

On the form, the user will only be able to answer the Venue field. After that the form will be saved and the entity reference field for Food will display on the page, that is the place where the user will answer that field.

On the entity reference view widget Food, I have the following:

Filter Criteria:
Content Type: Food

Relationship:
Entity Reference: Referenced Entity (field_venue) marked as required

The problem is that the view shows all the food even if the chosen venue is not available for that food. I don't know where to put that condition. Either on contextual filter or Filter Criteria. I'm not sure. I just need the view to get the Answer of the Venue from that same form/node so that the Food will filter automatically.

Is there anyone that will be able to help?

Thank you very much!!!

I got this working with this set up:

Contextual Filter: field_venue
-> Provide default value
 ->PHP Code
  -> PHP contextual filter code

  $node=menu_get_object();
  return $node->field_venue_for_catering['und'][0]['target_id'];

"field_venue" is the venue field from "Food"
"field_venue_for_catering" is the venue field from "Package".


How do I create a system message for a user's first failed login attempt? When using the core login block on the homepage, it appears that the failed login system message, "Sorry, unrecognized username or password. Have you forgotten your password?" is only presented to users on their second failed login attempt. The first time they fail, only the missing/incorrect username and/or password fields are highlighted. Is there any way of changing this default behaviour, so the system message is displayed on the first attempt, as well?

The error messages are always created when a user tries to login.

If the error message doesn't show, you must have a custom module, that removes the messages some how. Maybe via redirection or something similar.


my articles publish even when I deselect publish I'm an admin user type with publisher priveges as well. When I save an article, it is always save as "published". Even when I uncheck "published" under "publishing options" it saves as published.

In other words, I make sure "published" is deselected, and when I save and edit the article, the "published" select box is ticked.

My goal here is to save the content as unpublished, but I can't even when manually deselecting "published".

Drupal version 6.30. Fresh install. No whacky modules added.

This is what I did to fix the problem:

I disabled all except the core modules.
I then tested to see if I could unpublish content, and I could.
I then re-enabled each module until I found the culprit. In this case, it was the "rules" module.


How to get page visit count from access log I need to display the list of pages(nodes & terms) from access log. I enabled drupal core statistics module.

The view result should include

Page title.
Total number of distinct pages($view->total_rows).
Total views result($view->result).
Individual visit count of pages ().

I created a view and a template. I am getting points #1,#2 & #3 in my view. But #4 is missing.

I checked access log table in DB, but didn't found the column for page view count. How can get the missing point in my view?

1. Module Visitors

You may want to consider the Visitors module. As mentioned on its project page, it provides a block containing:

Total Visitors.
Unique Visitor.
Registered Users.
Last Registered User.
Published Nodes.
Your IP.

At this time there is no integration with the Views module ... yet. All reports created today use the theme function. Such views integration is being considered though, i.e. in the format of some out-of-the-box example, similar to the view delivered with the charts module.

2. Module Forena

If you'd want to "roll your own cookies" (i.e. some report that perfectly fits your custom requirements), then you might want to consider the Views integration of the Forena module. Here is a relevant excerpt about that from its project page:

  Use Views with Forena to create additional more complicated layouts than can typically be created using views. Forena provides a views rowstyle plugin that lets you use a Forena report to format the output of a view.

For an example of such custom report, created with Forena, start from the statistics (summary info) of the Watchdog Statistics, as in this Watchdog Statistics sample. Note the red numbers to the right of the table, which are actually hyperlinks that can be used as drill-down reports. I.e. if you click on any of them (like the "2" for "Page not found"), you get a details report about (in this case) the 2 specific records related to the "Page not found"). More details about this specific case can be found in comment #2 of issue 2337327. Obvious, I didn't really do any effort to beef up the look-and-feel of that report, like background, etc.

3. Other modules

Modules related to Visitors contains some other modules available, which might be considered as a possible alternative (or maybe 'addition'?), such as the Views Watchdog module.

Disclosure: I'm maintainer of the Visitors module, and co-maintainer of Charts and Forena,
I hope this does not violate the site's policy on self-promotion.


How to show a view page but hide all the content in the view for certain roles? Working on a membership site built on Drupal and am aiming to hide the content of certain views pages on the site unless the user has a specific (membership) role.

However, setting view page access control hides the entire page — including title and its very existence (page disappears out of nav menus, etc.). My goal is to show the page is still there (almost as a teaser), allow anonymous users to click on it, but hide all of the body content (fields, etc.) if the user does not have the correct role. That body content should then be replaced by a message to subscribe to the membership.

Is that doable with views or another module ? If so, how? Any suggestions?

Note: I'm already using the Field Permissions module to hide some of the same fields on other pages using roles. As such, I can't apply that module for this use.

Edit: We're using views to generate 800+ pages automatically (tokenized paths, etc.). That adds a layer of complexity — any solution has to be able to scale easily.

For a quick and easy solution use panels.

Use panels to display your view on the page for that specific user role.
Inside the variant portion, swap the panels to a general text area for anonymous users.

very useful links:

Creating Different Versions of Same Page Variants (watch all the free videos)

Can one apply a panels layout to a view page?


Install Issues with OS and Composer 2 I am stuck on trying to do an OS install and following the install guide found here.
When attempting to use Composer2 to fetch I get the following errors.
  Problem 1
    - drupal-composer/drupal-scaffold is locked to version 2.6.1 and an update of this package was not requested.
    - drupal-composer/drupal-scaffold 2.6.1 requires composer-plugin-api ^1.0.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
  Problem 2
    - oomphinc/composer-installers-extender is locked to version v1.1.2 and an update of this package was not requested.    - oomphinc/composer-installers-extender v1.1.2 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
  Problem 3
    - drupal-composer/drupal-scaffold 2.6.1 requires composer-plugin-api ^1.0.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
    - goalgorilla/open_social 9.4.0 requires drupal-composer/drupal-scaffold ^2.5.0 -> satisfiable by drupal-composer/drupal-scaffold[2.6.1].
    - goalgorilla/open_social is locked to version 9.4.0 and an update of this package was not requested.

You are using Composer 2, which some of your plugins seem to be incompatible with. Make sure you update your plugins or report a plugin-issue to ask them to support Composer 2.

In reading though several bug reports and various different posts I see this isn't a uncommon problem to have due to the last update of composer from V1 to V2.
It was recommended in a bug report that the submitter downgrade Composer to V1 so I did that and got a different set of results as follows.
    PS C:\> composer self-update 1.4.1
Upgrading to version 1.4.1 (stable channel).

Unable to write "C:\ProgramData\ComposerSetup\bin\composer.phar". Access is denied.
Complete this operation with Administrator privileges [Y,n]? y
Operation succeeded.
Use composer self-update --rollback to return to version 2.0.7
PS C:\> composer create-project goalgorilla/social_template:dev-master DIR --no-interaction
Warning from https://packagist.org: You are using an outdated version of Composer. Composer 2.0 is now available and you should upgrade. See https://getcomposer.org/2
Installing goalgorilla/social_template (dev-master dd01e6827fb19f29b3245fa893ac1f5911c72200)
  - Installing goalgorilla/social_template (dev-master master): Cloning master from cache
Created project in DIR
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file

  [ErrorException]
  "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"

The only thing I can find on that was on stack which basically said, yeah no way that's going to work.
Its my understanding that the next release will address the Composer2 changes required but is anyone aware of detailed documentation that would help me presently in navigating the scaffold issues? I am seeing all sorts of posts about patches and work arounds where what is being described is way way over my head.
I am way out of my league here in working this out but stubborn enough to learn with the right glints of information.

I can see in your output that you are trying to update to a specific version of Composer and it also prompting an "Access Denied" shortly after:
PS C:\> composer self-update 1.4.1
Upgrading to version 1.4.1 (stable channel).

Unable to write "C:\ProgramData\ComposerSetup\bin\composer.phar". Access is denied.

So it looks like that command already failed. You may have to manually install Composer on your machine if you run in such permission errors and move the composer.phar executable to the appropriate directory.
PHP 7.3
Please also see this GitHub issue for the ErrorException that you are facing: PHP 7.3 breaks composer with continue/targeting error (solution: downgrade to 7.2) #7783

[ErrorException]
"continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

In that issue it states that you will need at least Composer version v1.6.0 or up to be compatible with PHP 7.3.
Composer v1
Is there any reason why you need an old v1.4.1 version? If not then for now I suggest you rollback to the latest stable version of Composer v1 as per @Kevin's comment, which you can do by running:
composer self-update --1

Which should currently give you Composer v1.10.17, or again if that fails download the latest v1 manually.


Bulk upload via Form API, or, Please Warn Me It appears that Drupal 7 lacks a good, user-friendly bulk node creation/file uploading module, and I'm wondering why.

Specifically, I'm wondering what unforeseen issues I'd run into if I tried to create my own. What hook would I use? What do I need to know about saving files and creating nodes out of them before embarking on this task? What terrifying monsters must exist in this terrain that it's never been tread?

My specific plan so far is to use the Form API and hook_form_alter to create a webform with a field that can do multi-uploads of images and then, upon submission, generate nodes with Title = image name and an image field that will get populated with the location of the image file.

Has anyone out there attempted anything similar with Drupal 7, and if so, what were your results / what warnings would you give?

I don't think there is any particular difficulties in bulk creation of a nodes from a set of uploaded files. What would be difficult and probably explain why there is not such feature implemented in Drupal 7 is that it would be difficult to make it generic and re-usable. Mapping files to node is not a straightforward process. Variability is probably to high to allow a meaningful re-usable implementation.

If you plan to do write custom code, don't start with Webform. Webform is great for forms that are content to be edited by end users of the site/CMS. They are not designed to be a developer tool to create complex forms with custom backend behaviors. Using Webform will force you to deal with two form APIs in code. While one of them is designed to serve UI users, not developer.

You, or your user, would probably love to have a single widget to upload multiples files (as opposed to multiple file form element). But I suggest you first get a working solution that rely on the Form API and the available file widget. Drupal's API are build to work with standard and old-style browser to server interactions. Introducing new interactions model early into the mix will likely make thing unnecessary difficult by forcing you to learn and understand Drupal's API and inner working only to find workaround for its limitations. Once you get a working solution, search solutions to build a better UI/UX using progressive browser side enhancement. OR at least, refactoring a working solution build on sane and understood bases.

Since processing multiple files and creating multiple nodes is likely a long running operation, you should use the Batch operations API.


How to run alter query to modify mysql database using hook_schema? I want to change data-type of a field in for a particular table in database. I  want to use hook_schema_alter() to do so.
The ALTER query is:

ALTER TABLE `abcd` CHANGE `session_number` `session_number` INT( 255 ) NOT NULL COMMENT 'Session number to get number.'

Is it possible to implement such query using hook ? If yes please guide me.
Tonnes of thanx in advance.

Changes to the schema are typically handled with hook_update_N and you will normally locate this file in the module.install file.

For example with the update from Drupal 6.x-7.x the some of the base permissions were rename:

/**
 * Rename blog and forum permissions to be consistent with other content types.
 */
function system_update_7000() {
  $result = db_query("SELECT rid, perm FROM {permission} ORDER BY rid");
  foreach ($result as $role) {
    $renamed_permission = $role->perm;
    $renamed_permission = preg_replace('/(?<=^|,\ )create\ blog\ entries(?=,|$)/', 'create blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ blog\ entries(?=,|$)/', 'edit own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ blog\ entry(?=,|$)/', 'edit any blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ blog\ entries(?=,|$)/', 'delete own blog content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ blog\ entry(?=,|$)/', 'delete any blog content', $renamed_permission);

    $renamed_permission = preg_replace('/(?<=^|,\ )create\ forum\ topics(?=,|$)/', 'create forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ any\ forum\ topic(?=,|$)/', 'delete any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )delete\ own\ forum\ topics(?=,|$)/', 'delete own forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ any\ forum\ topic(?=,|$)/', 'edit any forum content', $renamed_permission);
    $renamed_permission = preg_replace('/(?<=^|,\ )edit\ own\ forum\ topics(?=,|$)/', 'edit own forum content', $renamed_permission);

    if ($renamed_permission != $role->perm) {
      db_update('permission')
        ->fields(array('perm' => $renamed_permission))
        ->condition('rid', $role->rid)
        ->execute();
    }
  }
}


How to set #default_value for radio button on Ajax Callback? I've a form having a radios and 'select list with Ajax callback event'. When user changed selection from the select box, I tried to set the default_value for radio button. but it doesn't work.

In the function check() I'm able to get the changed $id value every time I change the select list, but the default_value not working. it's always checked to the value 1 ('Yes').

I've tried like following but not working.

/**
 * Form.
 */
function myform($form, &$form_state) {
    $current_items = array(1=> 'Yes',2 => 'No');
    $form['current_items'] = array(
      '#title' => t('Change value'),
      '#type' => 'select',
      '#options' => $current_items,
      '#ajax' => array(
        'callback' => 'ajax_change_callback',
        'wrapper' => 'change-div',
      ),
    );
    $form['change_fieldset'] = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#type' => 'fieldset',
    );

    if (!empty($form_state['values']['current_items'])) {
      $form['change_fieldset']['checkin_form'] = check($form_state['values']['current_items']);
    }
    else {
      $form['change_fieldset']['checkin_form'] = check(1);
    }

  return $form;
}

/**
 * Form callback.
 */
function ajax_change_callback($form, $form_state) {
  return $form['change_fieldset'];
}

/**
 * Callback Form.
 */
function check($id) {
    $items = array(1 => 'Yes', 2 => 'No');
    $form['checkin'] = array(
      '#title' => $id,
      '#type' => 'radios',
      '#options' => $items,
      '#default_value' => $id,
    );
    return $form;
}

Please check if this works

$commands[] = ajax_command_invoke('#my-radio-button-id', 'val', array(array('checked' => TRUE)));

Ref: http://handsomedogstudio.com/setting-radio-button-values-drupal-ajax-call


Simplenews logs out when sending test newsletter I am trying to send a test newsletter through simplenews and it logs me out from my website everytime I hit the send button. I am logged in as admin. I have successfully sent test newsletters before and I dont think it is a permissions issue since I have necessary permissions.
The only thing I changed was install simplenews related modules like simplenews-statistics,etc. I also copied the .tpl.php files from simplenews's module folder to my theme folder.

What could be the problem?

I found out that the problem occurs when I use custom .tpl.php templates. I deleted the statistics module and .tpl.php files from my theme's folder. So, I am using the default .tpl.php files provided by Simplenews and it works.

Now, I need to figure out why I can't use custom template files.


Drupal 8 cron not running from external source (as anonymous) Running cron with crontab is not working on our Drupal 8 website if the user is anonymous. If I'm logged in as admin, I can run cron with the button or the url with key. If I'm not logged in, cron doesn't run with url with key.

Running from crontab is of course anonymous and so cron is not running.

Any ideas?

Version: Drupal 8 beta 4

Line in crontab:

*/5 * * * * wget -O - -q -t 1 http://www.entityone.be/nl/cron/theactualcronkeyhere

I know the question is old, but I faced a similar problem and would like to help people coming from google.

I assume you have a function in one of your specific cron hooks which needs extra permissions to run which won't work because Drupal runs cron as an anonymous user.

What helps is to identify which hook_cron needs elevated rights and switch to e.g. the admin account before the affected code runs:

use Drupal\Core\Session\UserSession;

// call the account switcher service
$accountSwitcher = \Drupal::service('account_switcher');
// switch to the admin user
$accountSwitcher->switchTo(new UserSession(['uid' => 1]));

// run your code here

// switch back to old session
$accountSwitcher->switchBack();


Error message after using Internalization I installed Internalization module and made my website Turkish as default.
Now I receive this error message

This warning issued from file and directory permission.
This issues maybe useful for you.
link1
link2


Preview info on mouse over on an image How can I get the effect like on StackExchange where user information is displayed when you hover over their avatar?

I have a site that only has images on the front page, and would like the user to be able to get some information about the image before they click through.

I am using Drupal 7.

Also you can use qTip

  qTips are stylish tooltips that can be configured and styled (more to
  come in later releases) to fit nearly any website's design.


How do I add Custom fields to the Order Information Checkout page in Commerce 2? I would like to add a set of additional fields to the order summary so after a user adds a product they would need to fill out some conditional fields of information alongside their billing information.

Drupal Commerce 2 documentation is pretty lacking at the moment and I am expecting to change the YAML files to add new fields. However, there seem to be various places to add new fields but nothing is showing up as additional fields on the order summary page.

What are the steps to add new fields?

I found the answer to this, it's not very obvious at the moment due to the lack of documentation but it's blinding simple when you know how.

Install the new profile module.
https://www.drupal.org/project/profile

Edit the page:

configuration > people > user profile

Here you can add commerce2 user pane or new fields.

For me I needed to make a new Content type form that the user could create and fill out as part of the checkout process, so I used the inline entity form.

Really you could use any field collections or paragraph's to add to the user fields as I notice there is a new patch to support field group and paragrahs.

I hope that helps someone else looking for this answer.


How to get vote results from node reference through views? I have two content types:
1. Restaurant page
2. Write a review page
The write a review page has node reference url widget field and also the fivestar rating field. The image attached below will explain more:

I have created a view page, where I want to get vote average results for each restaurant (also if possible than on each individual restaurants page too). I basically want average result of ratings given to each restaurant page by the node reference content type which is write a review page.
Below are two images explaining my view:

And the preview:

Now I am really not sure what I am doing wrong here, I changed aggregation settings for all randomly to average to count to all the possible scenarios but nothing seems to work. The votingapi_vote table is also empty, I know that fivestar doesnt necessarily use those tables to store, but then how could I display the stars or even the average of all the ratings that restaurant has got?

------------ update 1 -------------------------

Here is the relationship content type which I am getting:

Can you add a relationship of referenced node? or referenced write a review?

If not use the entity reference module instead. Add an entity reference field, with auto complete widget. Bundle type: Node.

Then in view add a relationship of referenced write a review.


Can not update drupal/core with composer Can not update drupal/core to 8.6.11

composer prohibits drupal/core:8.6.11

shows

webflo/drupal-core-require-dev  8.6.10  requires  drupal/core (8.6.10)

How can I solve it ??

The trick is, that drupal/core and webflo/drupal-core-require-dev always have to point to the very same version.

If you use composer update composer will look for this and pull the needed actual versions alone.

There are some articles recommending not to do so, but instead to update in minor parts and specify a concrete packet for better testing and reverting possibilities if something goes wrong. This means typing:

composer update drupal/core --with-dependencies

This may be true, but I often run in such errors with dependencies then I have to solve myself. You have now to specify both packets in the same command, then it will work too:

composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

My private conclusion:

If I have time to go the suggested way and solve such dependencies, than I will specify the single packet to update.
If it makes problems and I have an actual backup of my codebase and my database (as you should alwas have before updating anything!) and have not so much time, I simple type composer update and mostly all will work out of the box at the first try.


When page is not node entity site breaks How can correct this, my problem is that I'm using node label to set class. And everything works perfectly until I visit contact form or user login form which are not node entities, then site completely breaks, only on that two pages. How can I make some condition if it's not node or its contact form?

  if ($vars['node']->getType('location')) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $title = $node->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

getType() takes no arguments.

What you want to do is:

  if (isset($vars['node']) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

That will check that the node object exists in the variables array, and getType returns location.

You could go a step further and ensure the type on the off chance that $vars['node'] could get set to anything not an instance of NodeInterface, which getType would not be available for and throw another error.

  if (isset($vars['node']) && ($vars['node'] instanceof NodeInterface) && $vars['node']->getType() == 'location') {
    $title = $vars['node']->label();
    $vars['location'] = str_replace(' ', '-', strtolower($title));
  }

Be sure to include NodeInterface with a use statement at the top of the file.

See more about getType().


Access denied after installation I just finished the installation, everything went fine but when I go to view my site I can not login. I cant get to /user

have a look:
www.huf.co.nz

all worked fine on my local before I tried to make live

I have cleared all cookies and cache

Checking your URL, I see that going to http://www.huf.co.nz/user gives a 404 (page not found) from your web server, but http://www.huf.co.nz/?q=/user render's Drupal's login page.  This means that for some reason, "clean URLs" -- i.e., URLs that don't have the "?" in them -- aren't set up right.

It isn't clear what web server you're using from the 404 page.  If you're using Apache, then just look at the README file in the base of the Drupal install, or go to https://www.drupal.org/documentation/install/beginners, since looking at your HTML you appear to be using Drupal 7.42.  Apache is the easiest web server to set up, since Drupal ships with a .htaccess file that sets things up for clean URLs.

Drupal 7 also ships with a web.config file for using IIS, if you are serving Drupal from that web server.

If you're using something like nginx, you need to add a bit of configuration in order to get the web server to properly turn your URLs into the format that Drupal needs to see; nginx won't read a .htaccess file.  If you are using nginx, Google "perusio drupal", or go to https://github.com/perusio/drupal-with-nginx.

If you're using anything other than those 3, you'll need to find someone who knows how to translate an Apache type configuration into that web server's configuration.


Receiving form values on mail I am trying to receive the values of the form on my email, but I just receive empty mails. What is wrong in my code?

 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   $langcode = 'fr';
   $to = 'my_mail@gmail.com';

   $mailManager = \Drupal::service('plugin.manager.mail');
   $module = 'FrenchForm';
   $key = 'New contact';
   $params = array(
    'body' => 'test',
    'subject' => 'Website Information Request',
    );
   $send = true;
   $message['subject'] = t('New mail');
   $message['body'][] = t('test');

   $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
}

To send an email, Drupal 8 is not different from Drupal 7: You also need to implement hook_mail() as described in MailManager::mail().

See also the code used from MailManager::doMail(), which is the method that effectively composes and sends the email.
First, it initializes the $message variable.

  // Bundle up the variables into a structured array for altering.
  $message = array(
    'id' => $module . '_' . $key,
    'module' => $module,
    'key' => $key,
    'to' => $to,
    'from' => $site_mail,
    'reply-to' => $reply,
    'langcode' => $langcode,
    'params' => $params,
    'send' => TRUE,
    'subject' => '',
    'body' => array(),
  );

It passes that variable to the implementation of hook_mail() done from the module that is sending the email.

  // Build the email (get subject and body, allow additional headers) by
  // invoking hook_mail() on this module. We cannot use
  // moduleHandler()->invoke() as we need to have $message by reference in
  // hook_mail().
  if (function_exists($function = $module . '_mail')) {
    $function($key, $message, $params);
  }

Then, it sends the email.

  // Optionally send email.
  if ($send) {
    // The original caller requested sending. Sending was canceled by one or
    // more hook_mail_alter() implementations. We set 'result' to NULL,
    // because FALSE indicates an error in sending.
    if (empty($message['send'])) {
      $message['result'] = NULL;
    }
    // Sending was originally requested and was not canceled.
    else {
      // Ensure that subject is plain text. By default translated and
      // formatted strings are prepared for the HTML context and email
      // subjects are plain strings.
      if ($message['subject']) {
        $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
      }
      $message['result'] = $system->mail($message);
      // Log errors.
      if (!$message['result']) {
        $this->loggerFactory->get('mail')
          ->error('Error sending email (from %from to %to with reply-to %reply).', array(
            '%from' => $message['from'],
            '%to' => $message['to'],
            '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
          ));
        drupal_set_message($this->t('Unable to send email. Contact the site administrator if the problem persists.'), 'error');
      }
    }

As you see, the email is sent using $message, not $parameters. If you don't implement hook_mail(), $message['body'] will be an empty array, and $message['subject'] will be an empty string.
That is why you get empty emails.


Boolean field: hide (in display) if unchecked I have a content type with a boolean field (checkbox). Basically, what I'm trying to achieve is this:

If this field is checked, only show the label (when viewing the page)
If this field is unchecked, don't show the field at all (no label and no value)

Is there a simple way of doing this? (Without resorting to Views or custom code)

I've noticed that if I use "Check boxes/radio buttons" as widget type for this field, it comes close to what I want, since it offers three values to choose from (yes, no, and N/A), and if N/A is selected, the field isn't rendered on the display page.

However:

I don't want 3 values to choose, but 2. (3 might be confusing for users, and having to explain "Don't use the 'no' value" really isn't a good solution.)
I don't want the value to be displayed when "Yes" is selected (only the label).

OK, so it is possible and actually rather simple. Here's how I did it in the end:

Edit the field's settings:
"value if checked" -> use the text you want to see displayed when checked
"value if unchecked" -> leave empty

And then under Content type > Manage Display, hide the label for this field.

This way, only the value of this field will be shown.
Since the value when unchecked is empty, nothing will be shown when the field is not checked.


Migration yaml - A colon cannot be used in an unquoted mapping value I think I might be losing myself here. I am getting an invalid YAML error on a very simple migration file that really should be working fine. Would someone mind taking a look and letting me know if they can see something obvious that I am missing? Error code is:
A colon cannot be used in an unquoted mapping value at line 14 (near "  method: row").

YAML file is:
id: data
label: 'Data'
source:
  plugin: data
  key: migrate
process:
  name: data
    -
      plugin: existing_term
      vocabulary: data_source
      source: data
    -
      plugin: skip_on_empty
      method: row
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: data_source

Migration runs without error if I remove process plugins underneath name. Same error occurs if I get rid of the second process plugin (so with no piping). Basically, if I add anything that is indented more than 1 level, this error throws. I am sure that indention is '2 spaces', and this structure has worked in the past. This is on a vanilla drupal 9 install done with composer.

I don't know about the details of the YAML content, but just looking at the YAML it seems to me that name: data should be just name: otherwise it is not valid YAML.


How can we make the summary field auto expand on load? We have an admin page with a summary and body. The summary is auto collapsed but we want it to be automatically expanded on the page load like below in the image.

You could do it with the Summary Options module.

This module provides site builders with additional options for the
'summary' field when using "Text Area with a Summary" widget.
Often, a summary or teaser field is used when displaying content in
views. Drupal already has built in support for a summary field,
however there is not much control of whether or not it is display, or
required.


How to theme the maintenance mode page? What would be the best practice for theming the maintenance mode page in Drupal 7?

You can edit or create a "maintenance-page.tpl.php" file in your theme directory and edit that to theme your maintenance page.

You can view the source on the Drupal API page


Adding a new dependency to a module As a module maintainer, I want to add a dependency to one of my existing modules, so that my entity can use a field type plugin declared by the dependency.

What steps do I need to take to make sure that:

entup doesn't WSOD because my new field depends on a non-existent module.
Drupal end-users get prompted to download and install the new dependency.

I did find another similar issue -- What is the protocol for adding a new module dependency to a module that has only had a dev release? -- which deals with Drupal 7. This will help address question #2, but doesn't speak to the added complexity of entup.

I also found an issue dealing with deployments via drush -- Enable new modules dependencies on deploy -- but this doesn't address my questions either.

Any other tips or advice?

@Ivan Jaros is correct.

a) use dependency in your module info file, b) implement hook_requirements, c) activate the field only if the other module exists(ie. soft dependency).

  @Kevin, after you've enabled the module

Use a) and c) above.

  Drupal end-users get prompted to download and install the new dependency.

In c) you need to set a message to the user explaining why the field is unavailable and where to get the dependency.  Use function drupal_set_message.

Links:

D8: module exits, https://www.drupal.org/node/1894902 , see \Drupal::moduleHandler()->moduleExists($module)

D8: set message,  https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_set_message/8.4.x


Fatal error: Declaration of ... must be compatible with /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    return [];
  }

in BlockBase.php

vs

/**
     * @inheritdoc
     */
    public function blockForm(array $form, FormStateInterface $form_state ) {
       $form = parent::blockForm($form, $form_state);

       $form['city'] = [
        '#type' => 'textfield',
        '#title' => $this->t('City'),
        '#default_value' => $this->configuration['city'],
       ];

       return $form;
    }

in CustomWeatherBlock.php

Adding array in first argument as typehint of $form gives above error.
I just need to understand why is it giving an error.Is it because BlockBase is an abstract class and CustomWeatherBlock class extends BlockBase hence it needs to copy exactly the methods name and its arguments (including typehint) ?

Error

  ( ! ) Fatal error: Declaration of
  Drupal\custom_changes\Plugin\Block\CustomWeatherBlock::blockForm(array
  $form, Drupal\custom_changes\Plugin\Block\FormStateInterface
  $form_state) must be compatible with
  Drupal\Core\Block\BlockBase::blockForm($form,
  Drupal\Core\Form\FormStateInterface $form_state) in
  /Applications/MAMP/htdocs/d8jsonapi/web/modules/custom/custom_changes/src/Plugin/Block/CustomWeatherBlock.php
  on line 16

BlockBase implements BlockPluginInterface, which defines blockForm() as follows:

public function blockForm($form, FormStateInterface $form_state);

Interfaces are like contracts. Any class that implements an interface (or one of it's descendants) must define all the functions in the interface, and they must be defined exactly as in the interface. This is so that developers can replace classes, but ensure the code will still work, since the function definition will always expect the same values, as defined by the interface.

When you add a typehint to force $form to be an array, you break the contract of the interface. The interface says that any value should be allowed for the $form argument, but you are saying it must be an array. If you used your code, and a function passed a non-array value, it would cause an error. The interface is there to prevent such errors from happening. This is why you cannot change the function definition.


Views Display Mode Toggle I'm looking for a way to add the ability for users to toggle one of two view modes. Essentially, looking for a 'list/grid' switch. I've tried using https://www.drupal.org/project/views_modes but it's failing to switch the URL at all.

If anyone has knowledge of a patch/fork of this project, or a way to achieve this, I'd be grateful!

Display Suite Extras module (part of Display Suite) has an option to do that.


How to upload image or video from mobile device to content Creating node via mobile browser goes ok, but when adding image or video i can only record and upload which also works fine, but i can not access gallery and choose an image to upload.

Options available after clicking Choose file are:
- Camera
- Camcorder
- Voice Recorder
- Documents

That's a mobile OS issue. But in general, documents will open a list and show file managers at the bottom.


How to use an aliased content title for a Views contextual filter? I've set up a page view with a path of 'services/communication/%' the '%' being a contextual filter of 'Content: Title'.

The problem with this is that the url ends up looking something like 'services/communication/Best Practices'. In the contextual filter I have set the case to 'lower case' and checked the box to 'Transform spaces to dashes in URL', however, neither of these things are doing anything.

In most cases the link to some content works fine but if there is a dash in the content title (e.g. 'online-led reporting') the content won't display.

How can I use an aliased content title with the contextual filter?

How I attacked the spaces/punctuation issue ( http://drupal.org/node/786612 ) in Drupal 6 was by creating a url_safe_title text field and putting it in any content type that needed to be looked at, searched for, etc by it, and then having nodeapi() "fill it in for me" like this:

function MODULE_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (isset($node->field_url_safe_title) && $op == 'presave') {
      module_load_include('inc', 'pathauto');
      $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }
}

You can get fancy and hide the field with permissions, css etc so your users don't see it when creating content. I use http://drupal.org/project/nodeformcols to hide it and hide it from $content on display, too.

So, what this does is change simple titles like Hello World into hello-world but also online-led reporting into online-led-reporting with the added/needed benefit of being able to get back to "online-led reporting" from it.  It also helped out with stuff like Kukla, Fran and Ollie that turned into kulka-fran-ollie :)

So now in Views I use this field instead of the node title when I needed to grab things.  Just have to be aware of uniqueness, but that's another story in of itself :)


How to create independent sections, which consits of menu and more pages automatically I have little problem with creating independent sections on the web.

I have content type named project. It is basically landing page, which has own menu and this menu can link multiple simple pages. These projects have simillar structure, on every on them is page like timeline, news & events... Now when I want to create new project, I need to create new project, than create multiple simple pages, create menu, add menu to this project and so on. It is really complicated. Is there any way how can this be automatized?

Example: I will create new project, and menu and simple pages will be created automatically.

Try with field collection module and divide groups of fields in sections as explained in field collection module documentation. You will get what you want!


How to create a Views based chart with time intervals and using Highcharts? Is there any change to do time interval to Highcharts -module ?

Such as in this example: http://www.highcharts.com/stock/demo/compare

Or do I need to use different module for that?

The example in your question looks like a variation of this chart:

The above is a screenprint of a chart created with the Charts module, for which Highcharts is one of the supported charting engines (apart from Google Charts). So consider this module as a possible alternative to create such chart(s).

Head over to the Community documentation Create charts using Views for details about how to use the Charts module in combination with Views.

Disclosure: I'm a co-maintainer of Charts.


Form API Submit Button for Multiple Forms I created a module with 3 forms on it. Is there a way to only have one submit button at the very bottom of the page that will store all three values?

Not really. Drupal form may try to redirect you after successful submit. If 3 forms try, which redirect should work? And that's only one example.

Create fourth form function. In it, call all 3 existing ones, clean up mess with submit functions, validators and redirects, and it should work. Or simply merge your forms into one, why you needed three?


Why Search APi detect wrong SOLR host? Configuration view:

As you can see Search API uses site base url as SOLR host which is obviously wrong...

Ok, localhost replaced by $_SERVER['name'] value is only for presentation purposes. More info here: https://www.drupal.org/node/2512986

I had other issue with SOLR, so that's why it didn't work


Email misses fields from form This is regarding a Drupal 8 site, specifically Drupal 8.7.1 and the "Contact" module (with Contact Emails, Contact Storage enabled).

The issue that I'm running into is some of the fields are not included in the email that's sent out when the form is submitted. No Swiftmailer or other HTML email packages involved here, my ultimate goal is just to include all fields that were filled out.

I narrowed the situation down to this - when logged in, the resultant email sent out after form submission always contains all of the correct fields. If not, or in other words an anonymous user fills out the form, some fields are missing from the email entirely.

The aforementioned missing fields are actually paragraphs, or entity revisions, that I made use of to get access to the add / remove paragraph functionality on the front end. They work great, with a bit of preprocessing, but absolutely refuse to be included in email messages when the submitter is an anonymous user.

Sanity check - The fields are all there and filled out as part of the Contact Storage module, so that's not the issue. Anonymous users obviously do not have any kind of access to administer paragraph types, but this is not needed when the paragraphs are fields in a contact form(?).

I've checked around the various stack exchanges and other sites, but I can only find vaguely relevant issues, such as Theme contact emails. Using paragraphs in Contact does not appear to be a popular thing to do.
They are embedded as subforms, but I can't find anyone else who has asked this question.

The site is hosted on Acquia Cloud, PHP 7.2, if that helps. Short of digging through the module's entire codebase or setting up HTML mail with something like Swiftmailer, I'm stumped.

Any help is much appreciated, please let me know if you need any more detail on something - I know this is a lot to read without code or screenshots.

After working with JDev518 on this we discovered this was a permissions issue with paragraphs. Although this should have worked as is, we ended up installing Paragraph Type Permissions" and assigning specific permissions to create/edit/view the paragraph fields in question for anonymous. This "forced" the permission check to work and started including the submitted values in the email. However the contact module is determining the view permissions on those paragraph fields when it's building the email seems to be the cause of this issue.