Entering inner fields after attaching a field collection entity programmatically CONTEXT

Adding a node with its field-collection field and inner fields programmatically. Saving the node. Then trying to reach the inner fields - bam! - they are not in the array!

MORE INFO

if I am adding the node manually (not by code) and then trying to get to the inner fields - they ARE there.

[Edit] - The same problem of undefined inner field happens if saving using VBO (Views Bulk Operations module). So, can it be that the structure is bad? However, I have built the collection field using the manual interface only, not by code.

CREATING A NODE WITH FIELD COLLECTION

$node = // Creating a node
$fc_item = entity_create('field_collection_item', array('field_name' => $field_machine_name));
$fc_item->{$field_machine_name}[$node->language][$index][$value_column_name] = $field_value;
$fc_item->setHostEntity('node', $node, $node->language);
$fc_item->save(TRUE);
$node = node_submit($node);
node_save($node);

TRYING TO GET INSIDE FIELD COLLECTION JUST MADE

$value = $node->field_coll_print_authors['und'][0];
print_r($value);

I get:

Array
(
    [value] => 278 // This is the field collection item id
    [revision_id] => 1533
)

However, what I would have expect, and what I actually DO HAVE when adding a node of the same type by hand is:

Array
(
    [field_print_author_last_name] => Array
    (
        [und] => Array
        (
            [0] => Array
            (
                [value] => amir // This is the value I need
            )
        )
    )

HELP

Well, is there any function I have not called in order to attach the field collection item properly to the node? Or something else is missing?

Thanks for your help!

Field collections are not stored in full with the Loaded node access via node_load(); only their entity ID.

The data does sometimes look like that, for example in a node form (because it actually has to create fields for them) and in a rendered node via node_view()(depending how you have set it in the view mode settings).

But you can load them easy enough and get the values that way.

Here is an example :

Dynamically creating a node with multiple field collections :

  global $user;
  $type = 'floor_staff_checklist';
  $event_id        = 12345;

  $chk_node        = new stdClass();
  $chk_node->type  = $type;
  $chk_node->title = '';
  node_object_prepare($chk_node);
  $chk_node->uid                           = $user->uid;
  $chk_node->nid                           = 0;
  $chk_node->status                        = 1;
  $chk_node->promote                       = 0;
  $chk_node->field_event[LANGUAGE_NONE][0] = array(
    'target_id'   => $event_id,
    'target_type' => 'node',
  );

  if ($type == 'floor_staff_checklist') {
    $time = strtotime("01-01-2000 19:30:00");
    for ($i = 0; $i < 22; $i++) {
      $strtime = date("H:i", $time);
      $time += 1800;
      $flrchhk_fc = entity_create('field_collection_item', array('field_name' => 'field_floor_check'));
      $flrchhk_fc->setHostEntity('node', $chk_node);
      $flrchhk_fc->field_check_time[LANGUAGE_NONE][0]['value'] = $strtime;
      $flrchhk_fc->save();
    }
  }

  $chk_node = node_submit($chk_node);
  node_save($chk_node);
  drupal_goto("node/$chk_node->nid");
}

In this situation, I am creating a node, and creating 24 field collections within it, one for every hour, then saving the node.

And if you want to view the data :

$entity = entity_load_single($chk_node->nid);
if (isset($entity->field_floor_check[LANGUAGE_NONE]) && !empty($entity->field_floor_check[LANGUAGE_NONE])) {
  $fcs = array_column($entity->field_floor_check[LANGUAGE_NONE], 'value');
  $items = entity_load('field_collection_item', $fcs);
  foreach ($items as $item) {
    dpm($item);
  }
}

This will load the node, access its references to the field collections, load them, and loop through them printing the contents through Krumo (Devel module).


Migrate Drupal7 to local, user login link redirect to live, how to redirect it to local? I have changed cookies name and base URL for my local environment, I have also emptied all cache tables, but still it redirects to the live site.

Like http://server1/mysitename/user to https://www.mysitename/user

My guess is your using the secure login module.

Either:

drush vset securelogin_base_url "http://server1/mysitename/user"

or

drush dis securelogin


show product reference field with both add to cart and render product display format i want to show product reference field with both add to cart and render product display format how i will do that?

Any help is appreciable.

I mean when i view a product it will show both add to cart form with all type of product variation.

Thank you all in advance.

oh very easy i do it with template just create new template node--product--type--full.tpl.php  .

and use this

<?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);

      $options = $node->field_product[$node->language];
      foreach($options as $index => $option){
      $cmp_btn = drupal_get_form('properties_compare_add_form_' . commerce_product_comparison_create_key('commerce_product', $option['entity']), 'commerce_product', $option['entity'], $node->nid);
      $content['field_product'][$index]['commerce_product'][0]['cmp_btn']=$cmp_btn;
      $content['field_product'][$index]['commerce_product'][0]['cmp_btn']['#attributes'] = array('class' => array('compare-form' . $option['product_id']));

      }
      print render($content);
    ?>

i remove the add to cart button in view an set the display to render product


Set all boolean certain fields to 0 if 1 with rules I'm trying to reset all field_flag fields of all terms of a taxonomy value, where field_flag is TRUE (or 1).

Does anyone know how to do that?

Maybe some more back-story: I have a rule that gets fired on creation and editing of a taxonomy term when it has the field_flag in it.
Now out of this I want to "reset" all field_flags since only one term can have that field checked.

Thanks!

To clarify, you have created a new flag using the Flag module and attached it to a taxonomy bundle (either terms or vocabularies) and want to reset these flags.

You can do this directly in your database with a couple commands. First, you need the Flag ID of your flag which is in the 'flags' table:

mysql> desc flags;
+--------------+----------------------+------+-----+---------+----------------+
| Field        | Type                 | Null | Key | Default | Extra          |
+--------------+----------------------+------+-----+---------+----------------+
| fid          | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| content_type | varchar(32)          | NO   |     |         |                |
| name         | varchar(128)         | YES  | UNI |         |                |
| title        | varchar(255)         | YES  |     |         |                |
| global       | tinyint(4)           | YES  |     | 0       |                |
| options      | text                 | YES  |     | NULL    |                |
+--------------+----------------------+------+-----+---------+----------------+

You can find this by selecting the fid, and name from flags:

mysql> select fid, name from flags;
+-----+---------------+
| fid | name          |
+-----+---------------+
|   1 | bookmarks     |
|   3 | taxonomy_flag |
+-----+---------------+

In my development server, the taxonomy_flag id is 3. Now take a look at the flag_content table where all the flag content data is stored:

mysql> desc flag_content;
+--------------+----------------------+------+-----+---------+----------------+
| Field        | Type                 | Null | Key | Default | Extra          |
+--------------+----------------------+------+-----+---------+----------------+
| fcid         | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| fid          | smallint(5) unsigned | NO   | MUL | 0       |                |
| content_type | varchar(128)         | NO   | MUL |         |                |
| content_id   | int(10) unsigned     | NO   | MUL | 0       |                |
| uid          | int(10) unsigned     | NO   |     | 0       |                |
| sid          | int(10) unsigned     | NO   |     | 0       |                |
| timestamp    | int(10) unsigned     | NO   |     | 0       |                |
+--------------+----------------------+------+-----+---------+----------------+

What you want to do to reset all the values for your target flag is delete all entries from the flag_content table, so in my example above that would be

delete from flag_content where fid=3;


Drupal multi-site in an add-on domain? How can I configure Drupal 8 with multi-site under an add-on domain using cPanel?  I'm getting a 404 when I browse to my subdomain after following these steps:

Clean install of Drupal to my add-on domain: /public_html/addondomain.com/drupal.  I can successfully browse to addondomain.com/drupal
In cPanel, create a sub-domain at sub.addondomain.com with a document root at /public_html/sub.addondomain.com
Create the directory /public_html/addondomain.com/drupal/sites/sub.addondomain.com
Create a sites.php within public_html/addondomain.com/drupal/sites that contains the following code:
<?php $sites = array('sub.addondomain.com' => 'sub.addondomain.com',);>.  File permissions are 644.
Copy /public_html/addondomain.com/drupal/sites/default/default.services.yml to /public_html/addondomain.com/drupal/sites/sub.addondomain.com/services.yml
Copy /public_html/addondomain.com/drupal/sites/default/default.settings.php to /public_html/addondomain.com/drupal/sites/sub.addondomain.com/settings.php
Remove the directory /public_html/sub.addondomain.com
Create a symbolic link in /public_html/: ln -s addondomain.com sub.addondomain.com

When I do all of the above, I get a 404 error when I browse to both sub.addondomain.com and sub.addondomain.com/drupal.  Why am I not redirected to the Drupal installation page where I can enter in my database info, etc.?  Is the error with my symlinks?  My server (cPanel) configuration?  My .htaccess under either my /public_html, public_html/addondomain.com, or /public_html/addondomain.com/drupal?

My solution was to point the document root of sub.addondomain.com to /public_html/addondomain.com/drupal.  I did this within cPanel, which - if I understand cPanel correctly - is going to directly edit the Apache VirtualHosts directives within Apache's config files for my site (something I wouldn't have access to directly with shared hosting).


Displaying the data export/feed icon only when there are search results I've got a data export attached to my view. Although it works what I want it to do... it displays under the search form even when there are no search results... How do I get around this?

You can override the template for the views.

There is a variable called $empty this field contains the text to be displayed if the node is empty. You can use this to check if view is empty or not.

If you have placed the attachment before the node then you would edit the below section.

<?php if ($attachment_before): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

You can change this to

<?php if ($attachment_before && !$empty): ?>

      <?php print $attachment_before; ?>

  <?php endif; ?>

This would make sure that the attachment is printed only if the view has a result.


Custom form not being validated on submission So, I'm trying to implement a Salesforce generated Web-to-Case form on my Drupal site. I have implemented the form correctly so that it updates the Salesforce application cases, but for some reason the form doesn't get validated before submission. I have placed the form in a block with a custom module for portability and versatility. Here is the code for the form. Neither the required fields, nor my attempt to validate the form are enforced before submission. I'm pasting my code below stripped of extraneous fields to for demonstration.

function web_to_case_form($form, &$form_state){
  $form = array(
'#action' => 'https://webto.salesforce.com/servlet/servlet.WebToCase?encoding=UTF-8',
);
  $form['lastname'] = array(
  '#id' => '00N6A000009vWYv',
  '#name' => '00N6A000009vWYv',
  '#required' => TRUE,
  '#title' => t('Last Name'),
  '#type' => 'textfield',
  '#maxlength' => 30,
  '#size' => 20,
  );

   $form['maidenname'] = array(
  '#id' => '00N6A000009vWYM',
  '#name' => '00N6A000009vWYM',
  '#title' => t('Maiden Name'),
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 30,
  '#size' => 20,
  );

  $form['email'] = array(
  '#id' => 'email',
  '#title' => t('Email'),
  '#name' => 'email',
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 80,
  '#size' => 20,
  );

   $form['phone'] = array(
  '#id' => 'phone',
  '#title' => t('Phone'),
  '#name' => 'phone',
  '#required' => TRUE,
  '#type' => 'textfield',
  '#maxlength' => 80,
  '#size' => 20,
  '#element_validate' => array('element_validate_number '),
   );

  $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
   );
return $form;
}

function web_to_case_form_validate($form, &$form_state) {
  $email = $form_state['values']['email'];
  // Verify that the email address is valid.
  if (!valid_email_address($email)) {
    form_set_error('email', t('You must provide a valid email address.'));
  }
}

Is this because the form is being submitted to an external URL? If that's the case, how to I validate a form before submission? Otherwise, not sure what's going on here. I've even tried to add a validate element to one of the form elements, but that doesn't seem to work either.

Is this because the form is being submitted to an external URL?

Yes, the submit handler for a form in your website won't be executed unless that form is submitted back to your website.

  If that's the case, how to I validate a form before submission?

If you mean server-side (non-JS) validation, and you want the user to continue on to the remote URL as if they'd submitted the form as normal, you can't. There's simply no way to do that.

If you don't need the user to be forwarded on to the remote URL after submission, and the remote website allows it, you could just send a POST request from the submit handler with the data you've received from the Drupal form submission.

If you're even luckier, they'll have an API you can use instead.


Ajax breaks jQuery Toggle I use a small script that hides/shows a pane when a certain element is clicked.

(function($) {
Drupal.behaviors.luminary = {
    attach: function (context, settings) {
         $(".toggle-visible").click(function () {
         var targetselector = $($(this).attr('data-target-selector'));
         targetselector.slideToggle("fast");
      });
    }
}
})(jQuery);

It works well, but when an ajax event occurs, the pane will slide visible, and immediately slide invisible again. It goes down, and comes right back up. It only happens after an ajax event. Any ideas?

Change

$(".toggle-visible").click(function () {

for

$('.toggle-visible').unbind('click').bind('click', function() {


openatrium installation error? I installed openatrium locally on Wampserver2.4, after installing all the 186 modules, I goes to site home page, but it show following error

how to cope this error

You might need to do a change in my.ini file which is configuration file for your mysql server.

Change

open the my.ini file.
you might not have this (max_allowed_packet) line already there.
So you need to add this line at some point in this file.

max_allowed_packet=24M
Save the file
Restart mysql server.

Reference:
https://drupal.org/node/163145


Creating a block in own module I am using Drupal 6.27, created my own module, used hook_perm() in my module. Now the question is - did i do that in the right way?

/**
 * Implementation of hook_block().
 */

function adminka_block($op = 'list', $delta = 0, $edit = array()) {
  switch($op) {
    case 'list':
      return array(
        'adminka_simple_block' => array('info' => 'adminka simple block', 'cache' => BLOCK_NO_CACHE),
      );
    case 'view':
      switch($delta) {
        case 0:
          if (user_access('view adminka')) {
            $block['subject'] = t('My admin panel');
            $block['content'] = 'Добавить ' . variable_get('content_type_name', false) . '
';
            $block['content'] .= 'Выход';
            break;
          }
      }
      return $block;
  }
}

Because i didn't found another way to restrict that block visiblity only to users with user_acess('view adminka').

I think you do it  in  the right way, but instead of using this

$block['content'] = 'Добавить ' . variable_get('content_type_name', false) . '
';
$block['content'] .= 'Выход';

you should use l function

  This function correctly handles aliased paths, and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.

like this:

$block['content'] .= l(t('Выход'), '/logout');


I got a notice every time I upload an image Suddenly, I got this error every time I want to upload an image. It does not matter if it is an file field, or an IMCE import to CKeditor. I got the message, and the image does not upload. Do you have any idea?

  Notice:getimagesize() [function.getimagesize]: Read error! in image_gd_get_info() (line 349 of /www/mysite.com/modules/system/image.gd.inc

My "tmp" and "sites/files" directories have the permission 777, php5-gd is already installed.
I have also problems uploading attachments files, after upload them the size of the file is 0 bytes.

In this conversation, they suggest two solutions: one is changing the path of the "tmp" directory, but it doesn't work for me; the other is related to favicon set.
I remember that I uploaded a favicon in theme settings as I always do, and I think after that I began to have the issue. I am not really sure if it is related because this bug happened in older versions of Drupal.

Some images of my problems.

The issue is already fix. The hosting provider had changed some permissions of my shared account.


Can I use a style.php? I was wondering if I can change the style sheet of a theme from style.css to style.php and Drupal will use it? I tried it and it didn't work.
I did, of course, change the file name in template.php as well. Is there anything else I need to consider?

Yes you can but you shouldn't.

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

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

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

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

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


Location module predictive textfield If you are familiar with the location module you would know that when creating a location the state/province textfield predicts options as you type. These options come from a file in the Location module.

I need to re-create that for the city field. Can you please point me in the right direction of how to accomplish this? I want to avoid user typos.

Do I need to create a module of my own or do I hack Location.module ???

Thanks

What this is is an autocomplete field. My guess is if you want to recreate it for another field within the same module then you will indeed need to hack Location module. You'll want to look at the autocomplete callback for the state/province field as well as the autocomplete properties set on the field itself.

However, this may be difficult to do with cities, which is probably why it hasn't been done in Location. If you want to an autocomplete field for cities that actually adheres to the cities wiin a state/province, or even if it doesn't adhere, it will require a full list of cities within each state/province. That's a pretty hefty task if you ask me, but it certainly isn't impossible. I would check around the Location issue queue to see if this has been discussed before. Maybe you can gain information on why it was never done and what the drawbacks may be to developing this.


Drupal 8 + Twig background-color -field select How I do with twig this:

I got list -field where I got differents color:

black|Black

grey|Grey

black = background-color: #000;

grey = background-color: #eee;

When I select Black it will appear somewhere on the node or field.

Example

One way to do this is provide a field template for that field that just prints the value and no markup:

field--your-field-name.html.twig:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Then in the main template, wherever you want to output that field value, you would have:

Example

The result should be just the field value, with no whitespace, so "black" or "grey".


Schedule an email to be sent to new users a week after registration I am creating a site in Drupal 8 and would like to be able to schedule an email to be sent to new users.  The email should be sent automatically one week after they have registered.

In Drupal 7, I would have used Rules Scheduler to do this, but this doesn't appear to have been ported to Drupal 8 yet.  Could you suggest another way that I could do this?

My way to do this is to schedule a cron job at X time. You can check here how to do this https://www.drupal.org/node/23714 or use Ultimate Cron (https://www.drupal.org/project/ultimate_cron).

If you choose to use the Drupal core, implement hook_cron() where you will check the users that are registered by one week ago( table users_field_data, column "created"). Getting all the users then it only remains to send the email. Here is an example of sending email using mail Manager:

$mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'module-name';
  $key = 'key1'; // Replace with Your key
  $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $message; // Create this variable $message with the concret meesage.
  $params['title'] = 'Title example'; // Replace with a title.
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

  $result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
  if ($result['result'] != true) {
    $message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
    drupal_set_message($message, 'error');
    \Drupal::logger('mail-log')->error($message);
    return;
  }

  $message = t('An email notification has been sent to @email ', array('@email' => $to));
  drupal_set_message($message);
  \Drupal::logger('mail-log')->notice($message);

All these need to be integrated into hook_cron() function.


Sidebar Menu like on Myspace (for each profile) I have several content types. Bio, images, videos etc. for each user.
Now i want to have sidebar menu like on Myspace profiles where the menu reacts only to user you are watching.

Is there a module for this or i should use views and how ?

You might start with the Author Pane module:

  Author Pane is a block of information about a given user, like those
  typically found on a forum post, but can be used in other places as
  well. From core, it collects the user picture, name, join date, online
  status, contact link, and profile information. In addition, any module
  or theme can feed it more information via the preprocess system. All
  of this information is then gathered and displayed using a template
  file.


Views, User type page view ignoring Omega content grid I have created a view of users with a page display.  When I navigate to that page it isn't rendering Omega's usual id or grid classes.  Instead it is just using Views classes.

For example here is the HTML output for a normal content type views page:

And here is the HTML output for a user type page view:

Has anyone come across this?

--

Just to add that if you add a block to the content region then the omega template seems to work normally.

Ok so I think I have found a workaround / solution when using view pages.  I think that the Context module may of had a hand in this, as another site I run, which doesn't have context installed works fine when rendering views pages.

So while poking around Context and its available blocks I noticed that there was a Main page content block.  I added that to the content region and now if I use a view as a page the content region HTML is rendered.


How to Auto-save a custom entity to database in response to a new user account using Rules? I have defined new custom entity through hook_entity_info:

function mymodule_entity_info(){
  return array(
    'mymodule_account' => array(
      'label' => 'MyModule Account',
      'entity class' => 'MymoduleAccount',
      'controller class' => 'EntityAPIController',
      'views controller class' => 'EntityDefaultViewsController',
      'base table' => 'mymodule_accounts',
      'entity keys' => array(
        'id' => 'aid',
      ),
      'fieldable' => TRUE,
      'load hook' => 'mymodule_account_load',
      'view modes' => array(
        'full' => array('label' => 'Full', 'custom settings' => FALSE),
        'teaser' => array('label' => 'Teaser', 'custom settings' => FALSE),
      ),
    ),

  );
}

I have extended the Entity class, overriding the constructor:

class MymoduleAccount extends Entity{

  public function __construct(array $values = array(), $entityType =
  'mymodule_account'){

    global $user;
    if(empty($values)){
      $values['created'] = REQUEST_TIME;
      $values['title'] = '';
      $values['balance'] = 0.00;
      $values['uid'] = $user->uid;
    }

    $this->entityType = $entityType;
    $this->setUp();
    // Set initial values.
    foreach ($values as $key => $value) {
      $this->$key = $value;
    }
  }
}

I have defined a reaction-rule as follows:

On events segment: I selected

After saving a new user account

On actions segment: I defined two elements:

Create a new entity
Parameter: Entity type: Mymodule Account
Provides variables: Created entity (entity_created)

And:

Save entity
Parameter: Entity: [entity-created], Force saving immediately: true

I have tested these codes by creating new user account, but no mymodule_account has been created in it's database table. What am I missing?

Your issue (about "no account has been created in DB table") might possibly be because of the event (= "after saving new user account") you are using, which might simply not be the right event.

Moreover, have a look at issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module  works ...).

A possible compromise to avoid these kind of issues, is to transform what's you're trying to do into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component (eg X secs or mins "after saving that new user account" ... if your cron job runs frequent enough, if not it'll be next time cron runs). This compromise will ensure that at the time the Rules Component is executed, the content is for sure saved ... (so that can't be the reason anymore then why it would still be empty ...).

Not sure if this is "the" reason for your issue, but I'd definitely give it a try to see if it helps (debugging is the art of taking away all possible causes for an issue ...).


Add url alias with parameter (?foo=bar) I need to create urls aliases like this:

/mypath?foo=bar&foo2=bar2 (source) -> /foo/bar (alias)

via standard drupal alias url add (admin/config/search/path), but when I insert that link in the source path textfield I receive an error about not existent source path. But the path is correct (it works).

How can I resolve it? Only via direct db query?

The reason you get that error is that the form validation handler verifies the source entered in the form is a valid menu path, using drupal_valid_path().

Setting the path alias directly in the database would cause errors, as the source of the path alias is used to set $GET['q'], in drupal_path_initialize(), which contains the following code.

$_GET['q'] = drupal_get_normal_path($_GET['q']);

In your case, $_GET['q'] would be set to mypath?foo=bar&foo2=bar2. All the functions that use $_GET['q'] expect it to the in  the format path/subpath; the presence of the query parameters would cause errors. See for example the code executed by menu_get_item().

Using a custom module, you could implement hook_url_inbound_alter(), and hook_url_outbound_alter(). The first would transform foo/bar in mypath, setting $_GET['foo'] = 'bar', and $_GET['foo2'] = 'bar2'; the second would transform mypath in foo/bar, when $_GET['foo'] == 'bar', and $_GET['foo2'] == 'bar2'.


drupal_render() vs drupal_render_children()? What is difference in functionality between drupal_render() and drupal_render_children() ?
When I used drupal_render for $form derived as follows from hook_theme

function hook_form_alter($form,&$form_state,$form_id) {
if ($form_id == 'content_type_a') {
  $form['#theme'][] = 'custom_content_type_a_node_form';
}

}

function hook_theme() {
  return array(
    'custom_content_type_a_node_form' => array(
       'render element' => 'form',
    );

}

Then inside a THEMENAME_custom_content_type_a_node_form

function THEMENAME_custom_content_type_a_node_form(&$variables) {
$output = '';
$form = $variables['form'];

$output =
Some HTML code
;

$output .= drupal_render($form);

return $output;
}

While using drupal_render in the above function the page was going into loop and function was being called by endlessly
But when I replaced that with drupal_render_children($form) it did not go into an endless loop
What is the reason for such a behavior?

drupal_render() renders an item. Rendering it contains theming it. Look into function's code, there is this line:

// Call the element's #theme function if it is set

So placing render inside theming function is bound to make a loop. drupal_render_children() exist to break this loop - it renders element's children only, so you can print element itself in theming function and still have children themed by their own proper functions.


Increasing performance of cache_form on high traffic sites I am noticing a significant performance increase in my load testing when this table is small, but due to a large traffic site this is growing very quickly.

I have read that it is not a good idea to move this into an "in memory" cache like redis or memcached but can this be moved to a noSQL database for example?

My issue is that even with frequent clearing of old records the performance is struggling and my main solution is to take the database offline and optimize the table to reduce the physical size of the table in MariaDB.

Checkout https://www.drupal.org/project/apdqc if you're on D7; this is my config for it in the settings.php file.

$conf['apdqc_cache_default_compress'] = 2;
$conf['apdqc_cache_compression_level_cache_form'] = 3;


Why are cck fields included in body when getting a node? I have a content type that has several CCK fields: date, session number, session type, sold out, and homepage eligibility. The values of the fields are in no way stored in the body of the node as far as the database is concerned; here's the contents of the body field from one node in the node_revisions table:

The word &ldquo;insight&rdquo; is one of the most misunderstood and misused words in the marketing world today, but it is also one of the most important. As consumers become more fragmented and individualized, they will increasingly look for brands that represent some aspect of who they are. Brands will have to understand their target from an insights perspective. It will no longer be sufficient to settle for target generalizations.

In this seminar participants will take his/her knowledge and application of insights to an entirely new level. This seminar will teach attendees how to:

Identify real insights and distinguish them from generalizations, significantly improving the quality of an organization&rsquo;s insights.

&ldquo;Craft&rdquo; (rather than just articulate) an insight so it is evocative, breathing life into creative briefs/documents so they inspire.

Connect a shopper insight to a corresponding consumer insight (insight connectivity): How does the life of the shopper outside of the store (the consumer&rsquo;s life) effect what they do in the store (the shopper&rsquo;s life)?

When I use the $content variable in a node template, though, the values of the CCK fields are printing as well. I did a print_r($node) to see what was happening, and this is what I get (some elements stripped out for brevity):

stdClass Object (
  [nid] => 383
  [status] => 1
  [created] => 1323794850
  [vid] => 383
  [title] => Advanced Consumer and Shopper Insights
  [body] =>

The word “insight” is one of the most misunderstood and misused words in the marketing world today, but it is also one of the most important. As consumers become more fragmented and individualized, they will increasingly look for brands that represent some aspect of who they are. Brands will have to understand their target from an insights perspective. It will no longer be sufficient to settle for target generalizations.

In this seminar participants will take his/her knowledge and application of insights to an entirely new level. This seminar will teach attendees how to:

    Identify real insights and distinguish them from generalizations, significantly improving the quality of an organization’s insights.
    “Craft” (rather than just articulate) an insight so it is evocative, breathing life into creative briefs/documents so they inspire.
    Connect a shopper insight to a corresponding consumer insight (insight connectivity): How does the life of the shopper outside of the store (the consumer’s life) effect what they do in the store (the shopper’s life)?

Date and Time:
April 16, 2012
Session Number:
S1
Session Type:
Advanced Learning Session
Sold Out:
Open
Homepage Eligibilty:
Yes)

The last chunk of the body element (starting with Date and Time) are all CCK field names and values. Why are they included as part of the body? And what can I do if I don't want them displaying?

CCK fields, by default, are rendered into $content.  The order depends on their order on the Manage Fields tab.

To not do this, edit the content type, and goto the Display Fields (or goto /admin/content/node-type/my-content-type/display).

Then set the fields/labels as Hidden or Excluded.  I am spacing on the exact difference (too long since I set this up in Drupal 6), but I normally just use Hidden.


Commerce Kickstart - items won't float side by side I'm developing a store using the new Commerce Kickstart 2.  All of a sudden my items in the store are floating one on top of the other instead of items within the same collection floating side by side. For example I have multiple headings of "Notebook Computers" above each notebook computer product and they all float one on top of the other all the way down the page instead of One header and all the products floating side by side.

I took my CSS back to the default and it didn't make a difference.  Has anyone else come across this? I'm not sure if a module I may have installed caused this or a setting within the view may have caused this.  I'm hoping someone else has come across this.
Thanks!
Candace

AAAAh!  The answer is to shut down the site, shut down localhost, and re-start everything back up again.  It must have been a memory issue!


How to add the Terms and Conditions to custom form,not using any profile 2 or webform module? How to add the Terms and Conditions to custom form?
 i have made a module and willing to add a "read me / terms and conditions " type of thing to my form .

Whole code can be seen here , just dont wanted to write it again .
Custom module error, does'nt show on the page

Please suggest.

You can just add another element to the form like so:

$form['terms'] = array(
  '#type' => 'checkbox',
  '#title' => t('Terms & Conditions'),
  '#prefix' => "
Your terms go here
",
  '#required' => TRUE,
);

That will just stick the text before the checkbox, and then use CSS to position it however you want.

You might also want to put a validate hook in there and remove the #required attribute so you can write your own text in the form_set_error.


How to send password in email body function lawyer_register_menu() {
  $items['lawyer_register'] = array(
    'title' => 'Lawyer Registration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'lawyer_register_form'
    ),
    'access callback' => TRUE
  );

  $items['lawyer_register-autocomplete-engine'] = array(
    'page callback' => 'lawyer_register_autocomplete',
    'type' => MENU_CALLBACK,
    'access callback' => TRUE
  );

  return $items;
}
function lawyer_register_form($form, &$form_submit) {
  $form         = array();
  $form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE
  );

  $form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE
  );

  $form['fname'] = array(
    '#title' => t('Full Name'),
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['phone_no'] = array(
    '#title' => t('phone_no'),
    '#type' => 'textfield',
    '#description' => t(''),
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['street_address'] = array(
    '#title' => t('Street Address'),
    '#type' => 'textfield',
    '#size' => 50,
    '#maxlength' => 100
  );

  $form['county'] = array(
    '#title' => t('County'),
    '#type' => 'textfield',
    '#size' => 20,
    '#maxlength' => 20
  );

  $form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1
  );

  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit'
  );
  return $form;
}

function lawyer_register_form_submit($form, &$form_submit) {
  $edit    = array(
    'name' => $form_submit['values']['name'],
    'pass' => user_password(),
    'mail' => $form_submit['values']['mail'],
    'init' => $form_submit['values']['mail'],
    'status' => 1,
    'access' => REQUEST_TIME,
    'fname' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['fname']
        )
      )
    ),
    'street_address' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['street_address']
        )
      )
    ),
    'phone_no' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['phone_no']
        )
      )
    ),
    'county' => array(
      LANGUAGE_NONE => array(
        array(
          'value' => $form_submit['values']['county']
        )
      )
    )
  );
  $to      = $form_submit['values']['mail'];
  $subject = 'New account created';
  $headers = "From: something@somewhere.org\nContent-type: text/html";
  $body    = 'A new user account has been created for you at Something.org.
 Your login details are as follows:
Username: ' . $form_submit['values']['name'] . '
 Password: \'???????\'

 Please login to Lawandmoney.org and change your password.
';
  if ($form_submit['values']['send_message'] == 1) {
    mail($to, $subject, $body, $headers);
  }
  user_save(drupal_anonymous_user(), $edit);
  drupal_set_message("Successfully Register. Please check your Email for login    details.");

}

here I'm creating customized login registration page working properly. Now I want to send password to user via email so what i can write in message body like for username I write Username: '.$form_submit['values']['name'].' So what can I write for password?

Store user_password() in a variable. Change your code to this

    function lawyer_register_form_submit($form, &$form_submit)
    {
     $new_password = user_password();
     $edit = array(
      'name' => $form_submit['values']['name'],
      'pass' => $new_password,
      'mail' => $form_submit['values']['mail'],
      'init' => $form_submit['values']['mail'],
      'status' => 1,
      'access' => REQUEST_TIME,
      'fname' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values']   ['fname']))),
      'street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_submit['values']['street_address']))),
      'phone_no' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['phone_no']))),
      'county' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['county']))),
      );
      $to = $form_submit['values']['mail'];
      $subject = 'New account created';
      $headers = "From: something@somewhere.org\nContent-type: text/html";
      $body = 'A new user account has been created for you at Something.org.
 Your login details are as follows:
Username: '.$form_submit['values']['name'].'
 Password: '$new_password'

 Please login to Lawandmoney.org and change your password.
';
       if($form_submit['values']['send_message'] == 1){
         mail($to,$subject,$body,$headers);
         }
       user_save(drupal_anonymous_user(), $edit);
       drupal_set_message("Successfully Register. Please check your Email for login    deatils.");

     }


Files uploaded via custom configuration form are eventually lost This is a difficult one to explain. so, I am hoping that someone else has had a similar problem. I am uploading a file via custom configuration form, my field on the form looks like:

$form['homepage_image'] = array(
  '#type' => 'managed_file',
  '#description' => t('The image used on the home, agents, and featured property pages.'),
  '#default_value' => $config->get('pm_admin.homepage_image'),
  '#upload_location' => 'public://upload/siteimages',
  '#required' => TRUE,
);

My submit handler sets the config property in the bog standard way:

$config->set('pm_admin.homepage_image', $form_state->getValue('homepage_image'));

Initially this all works fine, the image is saved and I can grab it and render it where I want in templates. However, after several hours (I have not figured out the trigger) the image disappears. The configuration form no longer has the value. The file is also removed from the file system.

Not sure what is causing this and would appreciate any help.

The trigger is the 'status' property of the file. It defaults to temporary, and Drupal clears out temporary managed files on a cron run.

To fix, add this to your form's submit method:

$fid = $form_state->getValue('homepage_image')[0];
$file = \Drupal\file\Entity\File::load($fid);
$file->setPermanent();
$file->save();


Node Add / Edit Options Vertical Tab Problem For just one of my content types -- the built-in Article content type -- the node option vertical tabs at the bottom of the add / edit form are not displaying correctly.

As shown in the attached screenshot, the first node option for whether to create a menu link for the node is displayed as a tab. All other node option fieldsets are displayed WITHIN the first vertical tab as collapsible fieldsets, not as additional tabs. This only happens for the Article content type.

I cannot figure out why this is happening. Clearly, some module is form_altering the node add / edit form, but I have no idea which one or why only for Article.

Here is a series of things I would try. Check tabs after each test.

Try with a different browser.
Flush all caches (that one often solves a lot of problems).
Put your site in maintenance mode and Run updates (update.php).
Disable the Overlay module.
Disable all modules. Flush all caches. Re-enable all modules.
Update to the latest version of core if you can (currently 7.22).

Number 5 is a bit time consuming but it has solved issues for me in the past. First, make a list of all enabled modules. I do this with screen captures. Second, start disabling modules (except maybe Admin menu). You won't be able to disable all modules at once. It may take half a dozen Save configuration to completely disable all modules. When done, Flush all caches and while you're at it, clear your browser's cache too. Finally, re-enable all required modules. Run updates. Run cron. Flush all caches.

Hope this helps.


Which image preset to use? I am using D7 and views for one of my sites. I created a new image preset under the Configuration-> Image styles with scale and crop effect. My problem is whenever I create a node with this image preset I could see few portions of my image being cut out. This happens specially when the image is vertically large or horizontally large. I need to use a preset which does not cut the image and resizes it properly irrespective of whether horizontally large or the other.

Thanks.

You want to use the "Scale" option, and only set 1 of the variables. Either width OR height. You can leave 1 of them blank. This way the image styles will respect the aspect ratio of your images. I usually only set width, and leave height blank.

Don't use "Scale and crop" as crop will cut parts off your image to make it fit the size you specified.


How to disable edit their own profile per role? In Drupal 7, How to disable the edit profile permission per role? I found the "Tab Tamer" module, but this does not apply the feature per role.

There is one module called "UserProtect" module. With this module you can hide edit account, edit password, email from based on user roles and for specific users too.

You can set permission by going /admin/people/permissions where you can see User protect and you can configure it /admin/config/people/userprotect here

Protected Roles

User Protect Module Permission

For example, I don't want to give permission to my Test One and Test Two Users for edit their profile. So, I wanted to hide it from "Test One" and "Test Two".

Hope this helps!


How can I construct a table view with columns passed as a parameter? I have a content type, referenced by multiple subsequent content types and at some point I made a spreadsheet with all that data. My new assignment is to display a view like that and then export it to Excel, but before that let the user choose which columns appear in the table. I'm also going to need to be able to display exposed filters for all the chosen columns and save the columns and the filters as a report template.

Is it possible to do all that using Views or perhaps create it from scratch as a new entity?

I've been trying to do that in Views and I've hit a few walls. I thought about creating a bunch of PHP fields for all possible columns and check if they should be displayed based on the list of columns to display. Displaying data that way worked, but I can't put filters on PHP fields so I pretty much can't use them here.

After that I tried simply displaying all the columns initially and then in the "modify output" part of the fields display an empty string if that column is not on the list of columns to display (this way I could simply hide the empty columns). Only to realize you can't put PHP code anywhere in the view field settings.

Haven't managed to get that far but I think you can't simply display a node and x referencing nodes in one table row.
How it works in my db is that there's a "Examination" content type, which has different types. Multiple examinations might reference the same node so I'd have to find a way to display that node and all referencing examination types in the same row. Assuming each type can occur once.

^ This part might deserve it's own question though.

To put it shortly: I need to populate table view columns based on a list of columns while still being able to expose full filters to each column

What you'll want to do is create a new display (using the table style) on the fly and then use that display to render the output.

If you take a look at views exports, you can get an idea of how columns are added to new displays:

From commerce_cart.views_default.inc:

$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['title'] = 'Shopping cart';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'quantity' => 'quantity',
  'commerce_display_path' => 'commerce_display_path',
  'line_item_title' => 'line_item_title',
  'commerce_total' => 'commerce_total',
);

// Ignoring relationships...

$handler->display->display_options['style_options']['info'] = array(
  'quantity' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
      'align' => '',
    'separator' => '',
  ),
  'commerce_display_path' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
  ),
  'line_item_title' => array(
    'align' => '',
    'separator' => '',
  ),
  'commerce_total' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => 'views-align-right',
    'separator' => '',
  ),
);

  /* Field: Commerce Line Item: Quantity */
  $handler->display->display_options['fields']['quantity']['id'] = 'quantity';
  $handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
  $handler->display->display_options['fields']['quantity']['field'] = 'quantity';
  $handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
  $handler->display->display_options['fields']['quantity']['label'] = '';
  $handler->display->display_options['fields']['quantity']['precision'] = '0';
  $handler->display->display_options['fields']['quantity']['suffix'] = ' × ';
  /* Field: Commerce Line item: Display path */
  $handler->display->display_options['fields']['commerce_display_path']['id'] = 'commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['table'] = 'field_data_commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['field'] = 'commerce_display_path';
  $handler->display->display_options['fields']['commerce_display_path']['relationship'] = 'commerce_line_items_line_item_id';
  $handler->display->display_options['fields']['commerce_display_path']['label'] = '';
  $handler->display->display_options['fields']['commerce_display_path']['exclude'] = TRUE;

And so on. Then, just save the view (views_save_view()) and render the output. Commerce has a function called commerce_embed_view() that shows how to make this happen. This is slightly modified, though:

// You can get the ID after you save it.
$view->set_display($display_id);

// Set the specific arguments passed in. Optional.
$view->set_arguments($arguments);

// Prepare and execute the View query.
$view->pre_execute();
$view->execute();

// Return the rendered View.
return $view->render();


How to customize the homepage title without creating new pages? I can set up my page like this and it works fine:

somepage:
  path: '/my_page'
  defaults:
    _title: 'My custom page title'
    _controller: '\Drupal\my_module\MyController::content'
  requirements:
    _permission: 'access content'

BUT I need the path to be empty, so I tried this: path: '/' - not working. What I need is to be able to customize default homepage title of drupal 8 (without having to create new pages).

Tried path: '/' path: / path: ''. No success.

Any suggestions?

By default the homepage for D8 is set to /node (similar to D7).
And unlike Drupal 7, this is a view. So, adding a title is as simple as adding the title to the view. (Views in core, yay!)

Go to /admin/structure/views/view/frontpage.
Add title to the view
Save

It is as simple as that!
If you save any other page as your homepage, then you could set the title to the route as you have already specified in the question.


Permissions to Upload images in text field The Administrator role has no problem with this, but a lesser role (Editor) that I created cannot upload an image in the basic html text box.  They ARE ABLE to upload images as files and images, however.  What is the permission setting that I am overlooking here?
I should mention, this is Drupal 8.

The basic html option does work for uploading in-line images - for the Administrator.  Permissions on the in-line folder are correct.  Allowing my Editor role to use full html and even restricted HTML does not answer.

Just a further note, Editor can insert an in-line image in source code mode.

You need to use Full HTML in order to accept upload images in a text box.
Basic HTML doesn't allow img tag.

The other option is to add img tag in basic Html format, check:

  admin/config/content/formats/manage/basic_html

or create a new text format which will be available to other roles and will allow img tag.


How to change #weight of fields added to user register page by form_alter()? I have created some fields on my user registration page named like -
First Name (machine name - field_first_name),
Last name (machine name - field_last_name) etc..

I want to change their #weight according to me to appear at the place where I like them to be from the form_alter function at my custom module..

For the default name & email I used -

$form['account']['name']['#weight'] = 7;
$form['account']['field_first_name']['#weight'] = 8;

& it worked..

But If I am using for added fields in this way like -

$form['account']['field_first_name']['#weight'] = 6;

It's not working...

Can I get any help in this ?

Account as a whole is in a group which contains the name password etc. The one we add might be out side of that. That is why it is not effecting the weight.


Show node for specific content type using views contextual filter Let me explain the issue in detail. I have created two views. The first view displays listing of content for content type named Invoice. The View has a page display. This view is working fine.

I want when a user clicks on any content item the resulting page should use the another view which I have created to show the items for a specific content item based on the node id passed.

How to pass the node id as a contextual filter for second view. I have given the path for second view as node/%, but then the view just work for all content types. I don't want that thing to happen. I just wants to have that view called for Invoice content type items.

I have also used validation criteria for contextual filter, but that doesn't work.

A simple query alter will do the job.

Say example you are using a module my_views_invoice

    function my_views_invoice_views_query_alter(&$view, &$query) {

    $nodeid = $view->args[0][1]; // get the node id from contextual filters. Ex :Array ( [0] => node [1] => 1 )

   $content_type =  node_load($nodeid) ;// get the content type from the node load : Ex $content_type->type

      if ($view->name == '<Your view name>') {
// Add a where condition in the query like below..

        foreach ($query->where[0]['conditions'] as $key => $conditions) {
          if ($conditions['field'] == 'node.type') {
            $query->where[0]['conditions'][$key]['type'] = $content_type->type;

          }
        }
    }


Get the user's current language code How can I get the user's current language code in a view as a raw value, for example en or fr-ca?
This isn't for filtering content. I need the raw value of the users' current language to pass into a URL for a third-party tool. I added a custom text field. Then placed in some Twig code. The code is just failing to the fallback else value.
Based on other forum posts, I tried this code.
{% if language.getId() == 'en' %}
  en
{% elseif language.getId() == 'es-us' %}
  es-us
{% elseif language.getId() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I get failed.
{% if language == 'en' %}
  en
{% elseif language == 'es-us' %}
  es-us
{% elseif language == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I still get failed.
{% if language.id() == 'en' %}
  en
{% elseif language.id() == 'es-us' %}
  es-us
{% elseif language.id() == 'en-us' %}
  en-us
{% else %}
  failed
{% endif %}

I still get the same output.

I would suggest adding a custom text field then add the language value as a field. this way you will have the language as a replacement pattern that you can use with any custom link field which would be  something like {{ language }}

You need to checkout the style settings of to use the custom link option.


How do I use the Commerce Coupon module? Does anyone know how to use the Commerce Coupon module?

I created a coupon discount (%) type with Product_reference field; then, I created one coupon of that type, and selected the products to wich it should apply. This seems not to work.

The key to creating the coupon rules are two events: "Validate Coupon," and "Redeem a Coupon."

In this case, you need to create a rule with the "Redeem a coupon" event; in it, you need to add the actions "Create coupon line item," and "Set granted coupon amount" (in that order). The "Set granted coupon amount" action requires a number that is the discount to be applied. You need to calculate this in the rule by finding the percentage of the order total.

This video may help.


Problems rendering radio buttons after an ajax call I'm going to be linking this D.O issue.

I found that when changing an attribute other radio buttons would not update properly. Specifically that when there was two possible options for these buttons but each were only available if another option in the form was set, changing the first attribute resulted in the second one not being rendered as checked. If you went to add that item to the cart the proper variation would be added so this  seems to be just visual.

I was able to use xdebug to find that the default value of the buttons is set correctly.
I've been digging through the rendering trace of this element but am getting quite lost.

Does anyone know why after an ajax call a radio button would be rendered incorrectly and not be marked as checked?

A common mistake with AJAX is presuming that an AJAX callback is "aware" of the form's state. In reality, the form definition that AJAX works with is the original form instance. You will have to set the form values accordingly in your AJAX callback prior to returning the re-rendered markup. The $form argument that you receive in your callback function is always a cached copy of the original form.

So, to track what is going on in your form across AJAX callbacks, need to stash data server-side (e.g. in \Drupal::state()) or use the values stored in the $form_state argument. A good explanation of Drupal's form handling can be found here (thanks Jaypan!): https://www.drupal.org/forum/support/module-development-and-code-questions/2012-02-24/update-form-state-in-ajax-callback#comment-5648474


Getting access denied when altering user view route I want to display custom content for the user profile page instead of the entity view so I am altering the entity.user.canonical route and I am setting a custom controller and title compared to the entity view and page callback that is set by the UserRouteProvider. I am leaving the requirements athey are since I don't need to change anything regarding the permissions.

Strangely though I am still getting Access denied after I flush the cache. The code that I am using in my event subscriber that is run on the RoutingEvents::ALTER event is:

  $collection = $event->getRouteCollection();
    $route = $collection->get('entity.user.canonical');
    $route->setDefaults(array(
      '_controller' => '\Drupal\mymodule\Controller\UserController::profilePage',
      '_title' => 'Profile'
    ));

If I will use setDefault('_controller'...) instead of setDefaults() method it will work since I think the _controller has more priority over _entity_view but the _title does not have priority over _title_callback. So this is not a viable solution.

Any idea what the issue with that access might be? Does the _entity_access requirement require the _entity_view to be used instead of the controller? Should the presence of the entity in the url be sufficient?

Can't be sure as you haven't posted your controller, but my guess would be that you are not type hinting the argument there as UserInterface $user, so it doesn't get upcasted. That is required for _entity_access to work


What is the best way to update/add paragraphs with REST on a node I have a node with a paragraph. This paragraph has a couple fields and there can be any number of these paragraphs on a node.

I want to update this node via REST.  This is some of the GET output:

"field_region": [
    {
        "target_id": 13,
        "target_type": "taxonomy_term",
        "target_uuid": "2ae47cc7-c1c2-477d-8f23-b124e964f83a",
        "url": "/regions/california"
    }
],
"field_tactic_disbursements": [
    {
        "target_id": 9,
        "target_revision_id": 13,
        "target_type": "paragraph",
        "target_uuid": "1c98b1aa-f443-47fe-baff-1ecd0b499d1f"
    }
],
"field_year": [
    {
        "target_id": 1,
        "target_type": "taxonomy_term",
        "target_uuid": "58f65d10-143f-4a23-9315-52220c433602",
        "url": "/years/2018"
    }
]

Based on how this is, it looks like I will have to do a separate PATCH/POST request for each paragraph.   Is there a way to do this in one request?

I'm thinking about creating  a custom Resource to handle this but not sure if there is a better way.

https://www.drupal.org/project/entity_reference_revisions/issues/2848878 is an issue that allows to embed paragraphs on a field directly into the main resource.

We developed and use it exclusively for the use case of default_content with hal_json. It will likely not work out of the box with REST and patching/updating entities. But you're welcome to use it as a first step towards that, patches based on that are welcome.


How can I make Drupal/MySql accept special characters in ANSI (without changing the file's encoding)? I'm developing a custom module where a user (actually an admin of sorts) can upload a  CSV file. Based on the contents of this file, certain rows are inserted into a table.

I'm now having problems with special characters, like é. These give the following error:

SQLSTATE[HY000]: General error: 1366 Incorrect string value: '\xE9initi...' for column 'remarks' at row 1

I've tried changing the collation of the table and of the specific field, but this didn't help. The only thing that did help is changing the encoding of the file. But this puts the burden of solving the problem in the hands of the (non-technical) admin. Something I don't want.

What's more, this used to work. Before this module, things were done with a (non-Drupal) php script. The difference is that the old php script used mysql_query to insert the records, whereas I am now using db_insert.

How can I make Drupal/MySql accept the special characters in ANSI?

Found it. I just needed to encode the values with:

$encodedval = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);


Panels settings modal not working I am trying to make changes to a saved "selection rule" on one of my Panels, but when I click the settings gear icon, the icon moves on top of the "Delete" icon for a second, then moves back alongside - but no modal pops up.

Tried:
 - disabling javascript in browser (results in a page of code after clicking gear)
 - Using a different browser

Checked status page for errors
Switching versions of jQuery (via jQ update) as well as source CDN
Clearing caches
Restarting httpd
Testing it on my dev server with a similar environment - works fine
Tried the same operation in another Drupal installation on the same server, and the same modal works fine with that one.

The site is on a Centos 6 VPS running CPanel, APC and memcached, and behind Varnish.

I see nothing related in /var/log/messages, domlogs, error logs or watchdog, nor in the console.

When a Panels modal works (e.g. clicking the gear icon for a rule in the Context section of the same Panel) the console shows "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
But on the site where it works, this message doesn't show up in the console. This is the closest thing to a clue I've been able to find, but I don't know what it means.

Any suggestions how to fix it, or even how to diagnose what the problem is?

Figured it out. I was using Adminimal for my admin theme, and I changed the skin to "Alternative" and tried again ... and it worked. So it was something in the theme that caused the conflict, though I don't know what.


Using "if statements" to add classes in Twig I'm attempting to use an if statement to determine the value of a field and print a class based on that value. I'm not getting any errors, but the addClass is not working. No classes are being added. I'm assuming it's a simple syntax error. I'm a designer first, and I'm new to Twig templating. Thank you in advance!

{% for key, item in content.field_stat_value if key|first != '#' %}

0

{{ content.field_stat_title[key] }}

{{content.field_special_character[key]}}

  {% endfor %}

1) Install and enable the Devel module.

2) Add your /sites/development.services.yml:

# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

3) Add your /sites/default/settings.local.php:

<?php
/**
 * @file
 * Local development override configuration feature.
 *
 * Place this file in the /sites/default/ directory next to settings.php.
 * This will include the development.services.yml file for twig debug use.
 *
 */
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

4) Update your /sites/default/settings.php:

(uncomment this section)

# if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
#   include $app_root . '/' . $site_path . '/settings.local.php';
# }

This will allow you to add {{ dump(content.field_name | keys) }} to your template file so you can see just what keys you need to access the correct values.

Try:

{% for key, item in content.field_stat_value %}

    {{ dump(content.field_special_character | keys) }}

{% endfor %}

Then just add what you need to follow:

{% for key, item in content.field_stat_value %}

    {{ dump(content.field_special_character.mynextkey.0.whatever | keys) }}

{% endfor %}

I add this answer as being able to print out values will help a designer best. Plus, if your class is not printing, I just think content.field_special_character[key] is not evalutaing to %.

Having debug setup will also allow you to ensure you have the correct naming conventions for your twig template.


Why do I get the "Class 'Drupal\Core\Database' not found" error? I am using the following code.

$conn = Database::getConnection();
$conn->insert('testimonial')->fields(array('name' => $form_state->getValue('name')))->execute();

I get the following error:

  Class 'Drupal\Core\Database' not found

I am using use Drupal\Core\Database;. What is wrong in my code?

Update: i find using namespaces a problem, like now i want to get row count, if insert was successfull or not. i tried with

$result->allowRowCount = TRUE;
if ($result->rowCount() == 0) { }

and for rowcount i added the name space use Drupal\Core\Database;
i get

  Cannot use Drupal\Core\Database as Database because the name is already in use in

and if i remove this . i get

  Call to undefined method Drupal\Core\Database\Driver\mysql\Connection::rowCount()

How to use namespaces exactly. like i am assuming if i do

  use Drupal\Core\Database

then all the classes in that namespace and all the children namespace should get inehrited. Is this right ?

Drupal\Core\Database is the namespace of the class, which is not what the use statement requires. It needs the full-qualified class name, which, for that class, is Drupal\Core\Database\Database.

use Drupal\Core\Database\Database;

That is what Drupal core uses, for example in the DbLog.php file.

namespace Drupal\dblog\Logger;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\DatabaseException;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;


Drupal 8: javascript not loading in theme I would like to add a little javascript to my bootstrap child-theme, but is not loading.

These are the configuration files:

child.info.yml :

 core: 8.x
type: theme
base theme: bootstrap

name: 'child'
description: 'Uses the jsDelivr CDN for all CSS and JavaScript. No source files or compiling is necessary and is recommended for simple sites or beginners.'
package: 'Bootstrap'

regions:
  navigation: 'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'
  sidebar_second: 'Secondary'
  footer: 'Footer'
  page_top: 'Page top'
  page_bottom: 'Page bottom'

libraries:
  - 'child/global-styling'

child.libraries.yml:

global-styling:
  css:
    theme:
      css/style.css: {}
      css/masonry.css: {}
      css/basic-page.css: {}

  js:
  js/main.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

main.js

$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

Change

$(document).ready(function($) {
    $(function() {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
    });
})(jQuery);

to

Drupal.behaviors.basic = {
   attach: function (context, settings) {
   (function($) {
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 300) {
                $("#navbar").addClass('smaller');
            } else {
                $("#navbar").removeClass("smaller");
            }
        });
   })(jQuery);
  }

};


Add a discount to a product with Rules I want to add a new price field called Discount to a product. So now I have two price fields, Price and Discount.

Then with the help of the rule, I am interested in showing in the node page the price(with line-trough) and the discount.

Then when adding the product to the cart, the discount price will be added, instead of the normal price. How can I achieve this with rules?

PS: I don't want to use the Commerce Sale price module since it doesn't integrate with Search api.

I have found these instructions but I am not sure how to create the rule!

Add another price field to your product type.
Add a rule that applies the discount to the price on that product if the extra price field exists. Make sure you use the Discount price component when creating the rule.
Use Extra Price Formatters to display the difference.

I finally found a solution:I cloned the rule of the Commerce Sale module:
I created a Component:
Conditions:
-Entity has field:Parameter: Entity: [line-item], Field: commerce_product
-Entity has field:Parameter: Entity: [line-item:commerce-product], Field: field_discount_price
-NOT Data value is empty:line-item:commerce-product:field-discount-price:amount

Actions:Set the unit price to a specific amount
(Specify the numeric amount to set the price to:Price:Amount
Value:Discount

Then I created a rule:
Events:Calculating the sell price of a product
Action:The previous component
(Data selector:Commerce line items)

Then I used a price formatter and its done https://www.drupal.org/project/commerce_extra_price_formatters
Thanks!


How can I export and then import taxonomy terms? So I built my own custom entity type (we'll call it notes). And on my notes I have fields that use taxonomy terms, however when it comes to exporting the data out on individual fields, it shows the data, but when I restart the site and re-import everything, the taxonomy terms don't get imported with it.
Taxonomy terms is pretty important and a core with Drupal, so I don't understand why we can't export and import them easily like with the other data.
So I end up with fields that do not have taxonomy terms or is reported as missing.
Is there a way I can do this so when I import, the taxonomy terms get imported too?

The line between config/content can be blurry since there are many use scenarios. Drupal assumes a default scenario where terms are user-edited content that's not part of the CMS configuration.
Taxonomy terms are content entities, unlike taxonomy vocabularies, which are config entities. Hence, the D8 configuration export/import will not work for taxonomy terms.
There are various modules that will let you import content (and thus taxonomy terms). Some are more general-purpose (e.g. the migration framework, the content sync module), others are specific to taxonomy (e.g. taxonomy import module). Research solutions and figure out what works best for your scenario.


How to resolve the SMTP not connect to server drupal? I have used the SMTP Module for sending mails and done all the configuration according to this link(URL: http://www.symphonythemes.com/drupal-blog/configure-drupal-smtp-gmail).

But I could not send a mail. The error is like phpmailerException: SMTP Error: Could not authenticate. in PHPMailer->SmtpConnect().

Please help me, How to sort out this issue.

If you are using gmail account for SMTP then you need to enable "Allow less secure apps: ON" under "sign-in & security" of you google account settings.


PluginNotFoundException - MailChimp Earlier today I tried to install the MailChimp plugin for Drupal 8. I couldn't get it working properly so I decided I would just go ahead and uninstall it.
However, when I navigate to /admin/modules/uninstall I get the following error:

The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "filter_mailchimp_campaign" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 57 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('filter_mailchimp_campaign')
Drupal\filter\FilterPluginCollection->initializePlugin('filter_mailchimp_campaign')
Drupal\Component\Plugin\LazyPluginCollection->get('filter_mailchimp_campaign')
Drupal\filter\FilterPluginCollection->get('filter_mailchimp_campaign')
Drupal\filter\FilterPluginCollection->sortHelper('filter_align', 'filter_mailchimp_campaign')
uasort(Array, Array)
Drupal\Core\Plugin\DefaultLazyPluginCollection->sort()
Drupal\filter\FilterPluginCollection->sort()
Drupal\filter\Entity\FilterFormat->filters()
Drupal\filter\FilterUninstallValidator->validate('filter')
Drupal\Core\Extension\ModuleInstaller->validateUninstall(Array)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->validateUninstall(Array)
Drupal\system\Form\ModulesUninstallForm->buildForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormBuilder->retrieveForm('system_modules_uninstall', Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
call_user_func_array(Object, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

Likewise, when I try and go to edit any pages content, I get the same error. This is preventing me from doing anything. I went ahead and uninstalled the plugin manually be removing all of the mailchimp files from the modules directory over FTP but I am still getting this error.
Any ideas on what I need to do to fix this? It's driving me crazy!
Thanks

I was able to fix this. I had to go into the database and manually delete the entry filter.mailchimp_campaing from the config table.


How to get Entity Reference Autocomplete results to display in a table? I am currently working on a site which will take in an unlimited amount of nodes (in this case inventory numbers) for a Sales Order which I can then save, view and export into a CSV in Drupal 7. I am wondering how I can take the results of the Sales Order and form the results into a Views Block that is attached to the Sales Order NID page.

For example here is my Entity Reference Autocomplete:

Then when I save this, I want to be able to view the results in a table when I click on the Sales Order. I would like the table to display certain information from the item (which I know is done in a view).

Here is how my Views Block is set up currently (with the preview results):

I am unsure as to why nothing shows up on either the preview or the page.

I have also tried using Inline Entity Reference but that doesn't seem to work either. I am a Drupal Ameteur, but need some help with this.

Is the Entity Reference Autocomplete list not saving properly or does it save it anywhere at all? If so, how do I access it?

EDIT: So I have the block assigned to the Sales Order Content type and it is assigned in the Content section in the Blocks menu. (I think this is right)

I also just changed the Pages section to No Restriction and nothing changed.

The first thing thats jumps out at me is that you have "Referencing Entity" rather than "Referenced Entity" in your views relationship.

Because you are showing  a view of content with the field, you are already showing the referencing entity. What you want is a relationship to the referenced entities.

Have you also got the views block to display on the correct content type?

You have the correct contextual filter set up (you can use "get content id from url" rather than raw value).

Make sure the block is shown in a region on all of the referencing entities content type.


Session variable lost after setting it in ajax call In my custom .js code included into administration panel via my custom module I have AJAX call:

... //call this on click or sth
jQuery.post("sites/all/...mycustommodule/ajax/here.php", function(result){ alert(result); }

And here.php defines some custom session variable:

<?php
sesssion_start();
$_SESSION['test_module_test'] = 'test';
echo $_SESSION['test_module_test'];
?>

When I hit here.php with POST request thanks to my .js code I get alert with session variable outputed:

  test

But then, when I try to print_r($_SESSION['test_module_test']) inside my custom module code, I always get some session variables, but without my test_module_test:

Array
(
    [views_seed_time-...] => 1482412682
    [views_seed_name-...] => 1482412682
)

I don't know if the session gets destroyed in between or there's something else going on here.

I'd assume those are 2 different sessions; use session_id()in both contexts to confirm.

To make sure you're using the same session, just implement your AJAX path inside Drupal, with hook_menu()


How to redirect exposed view filter form submission? I have a view which is displayed from a theme method using views_get_view() and view::preview (see below). This view has an exposed filter. Unfortunately the exposed filter form does not work. When I submit the form it calls the wrong URL.

The wrong URL looks like this

http://domain?date_start=12

For comparison, the link of the sortable columns (which work as expected) does look like this:

http://domain/myselfcare/communications?order=destination&sort=asc&date_start=12

How can I fix this?

function theme_win_care_communications_page( $customer, $form, $form_state) {
  global $user;
  $output = '';
  watchdog('win_care', 'communications_page user=' . $user->uid . ', cust=' . $customer->id);
  $communications_view = views_get_view('drp_communications');
  $output .= $communications_view->preview('default', array($user->uid));

  // add an explanatory text
  if ($customer->reseller_id==33) { // mbudget only
    $output .= t('Note M-Budget: tariff is a function of the call time (in lots of 10 cents).');
  }
  else {
    $output .= t('Note: setup fee of 0.50 per call, minute rate according to current tariffs');
  }

  return $output;
}

Thanks for the additional info, it adds a lot of light to the issue. I am not exactly sure what is going on but maybe an explanation of what drupal does might give you an "A-ha! That's where I entered some info wrong" moment:

In the code, drupal/views/etc uses form redirects:

$form_state['redirect']= VARIABLE OR CODE TO SET IT TO A PATH

that is obviously mangling the redirect into:

http://domain/?date_start=12

What is interesting here is it is setting that url to the date_start value instead of adding that to the url:

http://domain/myselfcare/communications?order=destination&sort=asc&date_start=12

So here, instead of adding ?date_start=12 to the end of

http://domain/myselfcare/communications?order=destination&sort=asc

it's replacing it all (additional vars get the ?= changed to an &=)

So, I'd look at how you are defining date_start in your view forms and see if anything odd pops up there.  That or in your theme code setting the redirect to that directly.


On Cron run Open and save all Profile2 based user profiles i have a RULES event on "Cron maintenance tasks are performed" and a action is attached to it "execute custom php code"

<?php
$old   = '1 day';
$old = strtotime("now - $old");
$query=db_select('profile','pf')
        ->condition('pf.created',$old, '<')
        ->fields('pf',array('uid','pid','created'));
$result=$query->execute();
foreach($result as $record){
$profile=profile2_load_by_user($record->uid);
profile2_save($profile);
}
?>

Error :

  Recoverable fatal error: Argument 1 passed to profile2_save() must be an instance of Profile, array given, called in /home/test/public_html/drupal_sedco_2/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code on line 9 and defined in profile2_save() (line 292 of /home/test/public_html/drupal_sedco_2/sites/all/modules/profile2/profile2.module).

Any clues .
Thanks

profile2_load_by_user returns either a single profile or an array of profiles keyed by profile type. profile2_save expects a single profile.

It looks like in your particular case array is returned, so you need to:

Test what you got from profile2_load_by_user
If it's a single profile, use profile2_save directly.
If it's an array, either select the array element you need, or foreach over that array, calling profile2_save on each element.


How do I define multiple blocks in one module and include different javascript for each? In Drupal 8

I understand that to create a block I create a file in this structure:

mymodule/src/Plugin/Block/MyModuleBlock.php

If I would like to create another block for this module, or even a dozen blocks in this module, where do I define them so that they render differently and contain different javascript/css?

Use the following folder structure to create multiple custom blocks in drupal 8

-mymodule
--src
---Plugin
----Block
-----block1.php
-----block2.php
-----block3.php


Domain context ignores domain aliases I'm using Drupal 7, Context and Multisites.  A Context determines which Block to render based on the domain's URL.  This works fine for the live site with the actual URL.

My dev environment uses Domain aliases to make it work.  For sampledomain.com, I have an alias for sampledomain.local.  Context seems to ignore this alias and skips rendering the block on my dev machine.

Is this a known bug with Context/Multisites?  Or is there an additional configuration option to make this work?

I was able to use Context Debug All to determine that the context is actually being loaded.  The error is related to a different issue.


Rate widget not working in views I have an image gallery which I've made using views and each image has a yes/no rate widget. When the image is clicked a popup box is shown with the image in it which I have made using colorbox. I have also added the yes/no rate widget in the pop up box. The problem is that the rate widget is not working in the gallery but it works inside the popup box. How can I make it work in both the places?

This is strange, but when I click on the rate widget in the popup box for a certain image, it starts working in the gallery as well but only for that image.

This is what my views looks like. Only the (Votes)Votes:Value appearing first is working first and then after clicking that the other one works for that particular content.

It's because you used the "Votes: Value" twice, use it once, "Exclude it from display" and render it using tokens as many time as you want and you must be good to go.


Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous? The site I am working on has a lot of Anonymous nodes because it is a migration from a system that didn't have a proper user system.  Users can claim their articles by going in and editing the node and changing the system author, but I'd like that to happen by default whenever someone (preferably someone who is not the administrator) edits a node that has the anonymous author.  I'm sure it must be imminently doable through some form alter or form preprocess hook, but I don't quite get the drupal form system yet.  Solutions and pointers to good sources of information both welcome.

UPDATE I refined this question here: How can I set a default node owner for anonymous nodes on the node edit form?

Option 1 - Adapt node author after editing it

If you have the Rules module enabled, you can simply use a rule that looks like so:

{ "rules_change_anonymous_user_to_current_user" : {
    "LABEL" : "Change anonymous user to current user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "node-unchanged:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

Rules Event: after updating existing content.
Rules Conditions:

Author of node being edited has uid=0.
User editing the node is logged in.
User editing the node does NOT have role "administrator".

Rules Actions:

Set node author to current user.
Display a (warning) message like "Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.".

Done! ... with Option 1.

Option 2 - Adapt node author after flagging it (instead of editing it)

As per your requirement like "...whenever someone (preferably someone who is not the administrator) edits a node that has the anonymous author ...") the previous option has a disadvantage I think: the node has to be edited. But what if the node content is actually fine, and does not need any edits at all? Therefor I'd recommend a possible alternative, which you either use together with the previous option, or as a replacement of it. Read on for more details ...

You could also use the Flag module to create a (non-global) flag that are allowed to be used by authenticated users. Let's say you define a flag labeled like "I am the author", with machine name "i_am_the_author". With such flag in place, you can use a variation of the rule from Option 1, which looks like so:

{ "rules_change_anonymous_user_to_flagging_user" : {
    "LABEL" : "Change anonymous user to flagging user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_i_am_the_author" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "flagged-node:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

Rules Event: after a node has been flagged, under "I am the author".
Rules Conditions:

Author of node being flagged has uid=0.
User flagging the node is logged in.
User flagging the node does NOT have role "administrator".

Rules Actions:

Set node author to current user.
Display a (warning) message like "Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.".

Done! ... with Option 2.

Option 3 - Heading for the golden cradle

If you'd implement Option 2 (using the "I am the author" flag), you could even replace the rule from Option 1 by a variation of it, which is that you simply disallowed edit attempts of nodes that (still) have an anonymous user. Here is a summary of how such rule could look like:

Rules Event : Drupal is initializing.
Rules Condition: Current path is like /node/nid/edit (using a regular expression).
Rules actions:

Perform a redirect (to any path that fits, eg some help page to explain the reason for the direct).
Set a Drupal message to indicate that edits are only allowed by a user who flagged the node first by ... you guessed it ... the "I am the author" flag.

Voilà!

Option 4 - Resolving node author disputes

No matter which solution (option) you'd use, there is always a chance that multiple users might claim to be the node author.

To also take that scenario into consideration, you could create a variation of the rule from Option 2. Some details about such rule:

Replace 1st Rules Condition by "node author of flagged node is NOT uid=0.
Replace both Rules Actions with sending an eMail to (eg) the site administrator, to indicate that some type of conflict about a node author came up (and adapt the message being shown accordingly).

Game over!?!?


Check if there are any elements with a certain class in the form array of unknown depth I'm new to Drupal and still have to figure out a lot. This might also be just a general programming question.

I wrote a module that has some js-libraries which should be attached to forms on different conditions. For one of those libraries, I want to add it in case the form array has an element with the class "remove-button", which could be at any depth.

I searched for different recursive approaches, but it doesn't work somehow. I was able to attach the library without a condition so it attaches to all forms, so the problem lies within my recursive function.

Snippet from hook_form_alter in my .module file:

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id)
{
  // remove-button
  $hasRemoveButton = containsClass($form, 'remove-button');
  if ($hasRemoveButton) {
    $form['#attached']['library'][] = 'my_module/remove-button';
  }
}

Recursive search function (last code I tried):

/**
 * Search a class in $form.
 */
function containsClass($array, $class)
{
  if (!is_array($array)) {
    return false;
  }
  if (isset($array['class']) && in_array($class, $array['class'])) {
    return true;
  }
  foreach ($array as $subarray) {
    containsClass($subarray, $class);
  }
}

Anyone an idea how this can be achieved? Maybe with a different approach than a recursion?

You can try this for your recursive function.

function containsClass($array, $class) {
  if (is_array($array)) {
    if (in_array($class, $array['class'])) {
      return true;
    }

    foreach ($array as $element) {
      if (containsClass($element, $class)) {
        return TRUE;
      }
    }
  }

  return FALSE;
}

The problem with your function was that it's not returning the result of containsClass() when it's called recursively. However, you only want to return the value if it's TRUE, which is why I added the conditional to check that. Finally, after all items have been looped through, if no TRUE value is found, FALSE should be returned.


How to get an editable cart at checkout with Drupal Commerce? I always used Commerce Kickstart as a starting point for making e-commerce stores, but this time I opted to go with pure drupal + commerce modules.

One problem I have is that the cart view I get when I enter the checkout process is non-editable: it's just the list of items. The view used by the checkout is "Shopping cart form (Commerce Order)", and the cart uses Shopping cart summary (Commerce Order). The latter has "remove" button in rows and an "update cart " link. Actually, I was able to replicate the elements of the formerin tha latter, save for the update" cart link.

I can get the one I am used to by going to view cart, but I do not get this one on chceckout. I tried to change settings at admin/commerce/config/checkout/form/pane/cart_content, but I can't  get the desired result.

Any Ideas?

The module Commerce cart form checkout pane does this very well.