Hiding body in teaser display For CCK fields you can set the display to be hidden for teaser display and shown when in full node display. How can I do the same for a node's body field as it's not listed on the display settings page?

I don't know of a module that would provide a user interface you could use to achieve what you're after. It is quite simple, however, to put together a tiny module and implement hook_nodeapi('view') to remove the body part from the node content before it is built for display.

The most basic example would be the following, removing the body part from all nodes' teasers:

function YOUR_MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view' && $a3 /* teaser */) {
    unset($node->content['body']);
  }
}

Just pop a function like this into your module and adjust the if condition as needed.


How do I create table in custom module In Drupal 7 we used to use hook_schema() in the .install file to create a table. I believe that, in Drupal 8, you can do that as well, but I was under the impression that you should create .yml files with your schema.

What's the method for creating tables in Drupal 8?

You can use hook install to create your own tables, if you really want to, although Drupal has many other more out-of-the-box solutions.  But if you do want to roll your own, there's an example module, called dbtng_example, in the examples module: https://www.drupal.org/project/examples, complete with routing for adding and removing your custom database entries.

I'd recommend installing it and trying it out, then you can use that as a basis for creating your own database table in Drupal 8.

Another approach to consider is to create a config entity or a content entity.

If you use the drupal command line tool there's even a command for generating these "drupal generate:entity:config", and "drupal generate:entity:content".

Also in the examples module, there is config_entity_example and content_entity_example.

From https://www.previousnext.com.au/blog/understanding-drupal-8s-config-entities: "The main difference between content and config entities is how they are stored and (at the moment) config entities are not fieldable".

There are some other more out of the box solutions, such as the config_pages module that allow you to easily spin up places to store data on your site:
https://www.drupal.org/project/config_pages

We recently used these for one off landing pages, by creating a controller and route.  This has a huge advantage over a custom table as you can easily add new fields and you can use data types such as images and entity references easily, you can also set field formatters, and load the data formatted using the config_pages entity view builder.


Can't use exit(0), how else can I terminate a response? Here's my code(using Drupal 8):

public function checkForRedirection(GetResponseEvent $event) {
    $is_authenticated = $this->currentUser->isAuthenticated();
    $route_name = $this->routeMatch->getRouteName();

    if (!$is_authenticated && $route_name !== "user.login") {
      header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
      header("Cache-Control: post-check=0, pre-check=0", FALSE);
      header("Pragma: no-cache");
      define("SITE", "www.google.com");
      $response = new RedirectResponse(SITE, $this->redirectCode);
      $response->send();
      $exit(0);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ["checkForRedirection", 30];
    return $events;
  }

So I'm redirecting an authenticated user away from my site. It works perfectly how I want it to, the only problem is PHP Mess Detector doesn't allow the exit(0) function, so wondering what are my alternatives to produce same functionality that exit(0) does here?

You need to terminate using the kernel. You'll have to generate $currentRequest and $response, which may already be available depending on where your code lies. After you have them, you can terminate the request using:

\Drupal::service('kernel')->terminate($currentRequest, $response);


Return a variable from field template I want to return a "global" variable from a field template file

Assume I have a content type called "basic_page".  Basic Page has a field called "my_field".  In the template for basic page (node--basic-page.tpl.php), I render "my_field" by calling:

$fieldMarkup = drupal_render($content['field_my_field']);

In field--field-my-field.tpl.php I do whatever I need to do to return the field HTML / markup - no problems here.  But I want to return a variable to node--basic-page.tpl.php as well.  Is there a way to insert this variable into the node render array, or something of the sort?

I do not want to do this in a hook_preprocess function.  If there is no other option I will, but was hoping I can avoid this.

Use template_preprocess_field in your template.php and add your variable there.

Then in your tpl.php you can easily access that variable and render that variable along with your markup.


Add specific CSS class with Semantic Views I am searching for days now and don't find the solution so I exposed my problem here.

I am under Drupal 7 and I don't find an issue for this problem.

Here is the purpose:
I created content with one specific field, a boolean, so when it's checked i want to add a class to an existing view. I explain....
Once I created content explained before, I create a view for it (with semantic views) and save!
It works perfectly but....what I want to do is that when I check the boolean (in the content) it adds me a new class to the article () see figure below:

In a content (created with a custom content type), I check this checkbox:

And so:

became:

From now the source code looks like this:

Thank you very much for your answers!

This is possible to accomplish by overriding the View's template. You would have to create a custom Views tpl file with logic for adding a custom class based on a field value. Unfortunately you can not do this by simply using Views UI.

How to achieve this:

Add your Boolean field to the View and "Exclude from Display". Keep the default formatter of the field.
Create a custom View template. Click on Theme: Information in *Advanced settings* of your View. You'll see template suggestion for overriding different parts of the View. Here you are looking to override the Style Output of your View.
Click on Style Output link and you'll see the default content of .tpl file. Copy the code and paste it in a file named *semanticviews-view-unformatted--machinenameofyourview.tpl.php*. The name of the file that you should use will be listed in step #2, right after the one that it highlighted in bold, so you'll be safer by just copying and using that. Save this file in your current theme's template folder.
Now go back to the Theme:Information dialog of your View and click "Rescan Template Files" - you'll see that your new template is now detected by the View as it will become highlighted in bold. Click OK - now you told the View to use your new template. Save the view.
Open your new template file and paste the code below in it. You can replace the content of new template with the code pasted below, or just find the section // ADDED and paste it in the right place. *Section //ADDED will define the logic for adding custom class when Boolean field is checked.*
Replace the field_field_boolean w/ field_field_yourfieldname. Note: double field_  is necessary here. Also, replace the name of the class to your desired class name.

.....

<?php
/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <<?php print $group_element; ?><?php print drupal_attributes($group_attributes); ?>>
    <?php print $title; ?>
  </<?php print $group_element; ?>>
<?php endif; ?>
<?php if (!empty($list_element)): ?>
  <<?php print $list_element; ?><?php print drupal_attributes($list_attributes); ?>>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!empty($row_element)): ?>

  <?php // ADDED CODE ?>
  <?php
        $custom_class = '';
        if (isset($view->result[$id]->field_field_boolean[0]['raw']['value']) && $view->result[$id]->field_field_boolean[0]['raw']['value'] == TRUE) {
            $custom_class = 'my-custom-class';
        }
        $row_attributes[$id]['class'] = $row_attributes[$id]['class'].' '.$custom_class;
    ?>
  <?php // END OF ADDED CODE ?>

  <<?php print $row_element; ?><?php print drupal_attributes($row_attributes[$id]); ?>>
  <?php endif; ?>
    <?php print $row; ?>
  <?php if (!empty($row_element)): ?>
  </<?php print $row_element; ?>>
  <?php endif; ?>
<?php endforeach; ?>
<?php if (!empty($list_element)): ?>
  </<?php print $list_element; ?>>
<?php endif; ?>

.....


Forum access based on role I cant figure out to hide forum sections based on role. I only want clan leaders to see the clan leaders section, squad members to see their own squad section etc. I already have the roles set up, but I can't figure out how to restrict access to container/forum based on those roles.

Someone mentioned the taxonomy access control module. But that seems really overyly complicated for what I want to accomplish.

Not sure what version of Drupal you are using, but have you looked at the Forum Access module?  For D6 there is a stable release and the D7 version is in Beta. The module is also very straight-forward

From the module's page:

  This module changes your forum administration page to allow you to set
  forums private. You can control what user roles can view, edit,
  delete, and post to each forum. You can also give each forum a list of
  users who have administrative access on that forum (AKA moderators).

  This module requires the ACL module in order to function. The D7
  version also requires the Chain Menu Access API module.

  Forum Access is compatible with the core Forum module, Advanced Forum,
  and Content Access, Domain Access as well as all other well-behaved
  node access modules.


Checkbox for Views Filter I have a view and used Better Exposed Filter module to show this Checkbox to filter the content in the view. The picture may explain the situation properly

In above filter by criteria, those values are Taxonomy Terms, which will increase later.

However my problem is, I want to have a Checkbox only for Development Taxonomy. So, instead of Filter by and list of Taxonomies, it would only be Filter by Development with a checkbox near to it. When the checkbox is checked it'd show the view which is Listed Under only Development

I tried something like CSS or jQuery show only this taxonomy class and hide other taxonomy terms, but that's last resort.

Any Drupal way I can accomplish this without writing codes?

In your filter settings there is an option "Limit to the selected items".
Check that and select "Development" from the select field of options and it should do what you are trying to achieve.

Then change the label of your filter as required.

See the attached image:

The view itself looks like (note I changed the filter to be cat, not car as in the previous image, because I already had content tagged with cat):


How do I set a condition to only show a block to members of a group? I use the Drupal Group module. Is there a way to check if a logged-in user is an groupmember or not when the user visits the grouppage? I have some blocks that should be hidden if an user is not a member.

Programmatically you can use Group::getMember() to determine if an account is a member of a group.
if ($group->getMember(\Drupal::currentUser())) {
  // the current user is a member of the group.
}

Note that Group::getMember() returns a GroupMembership entity.
You could then create a condition plugin, using the above methodology to determine if the current user is a member of the group. I've created a tutorial on how to use the Conditions API to create conditions plugins, using this example of a condition where a member is a member of the group: https://www.jaypan.com/tutorial/custom-block-visibility-plugins-and-condition-plugin-api


Trigger a rule when a module update is available It would be terrific to have Rules integration for when the Update Manager module finds an update. Is there a way to do this?

Potential ways I'd use this would be to have an update page, customized emails, adding logs in Heartbeat, and so on.

I know that you specifically asked about Rules, but you might also consider using Drush for this.  For example, if you want an email to be sent to you every time an error appears on your status page, you could just drop this one line into your crontab:

0   */1   *   *   *   /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /bin/drush --root=/path/to/drupalroot --uri=mysite.com status-report --severity=2

(n.b. your path may vary.)  If there is output from the status-report command, cron will send it out in an email; if there is no output, nothing happens.

Hope you don't find this answer to be too off-topic.  Rules is great for responding to user actions, but for scripting site maintenance tasks, Drush is often more convenient.


Set the value of a hidden form component I have a Webform in drupal 7. I want to add a hidden field porgramatically to it, and I would like to set the value of this field per form.
I want to achieve all these in a custom submit function, as I want to use the sid (serial ID) of the Submission, to generate a unique ID for each Submission.
At the moment everything is working, except to set the value.
I googled it a lot, tried out hundreds of codes but non of them worked in my case.

Here is my code:

<?php
$form['#submit'][] = 'webform_custom_submit';

function webform_custom_submit($form, &$form_state) {
  if ( !array_key_exists('my_uniq_id', $form['#node']->webform['cids'] ) ){
    $components = array(
      0 => array(
        'name' => 'My Unique ID',
        'form_key' => 'my_unique_id',
        'type' => 'hidden',
        'weight' => 1,
        'pid' => 0
      )
    );
    webform_ensure_record($form['#node']);
    foreach ($components as $component) {
      $component['nid'] = $form['#node']->nid;
      $form['#node']->webform['components'][] = $component;
      webform_component_insert($component);
    }
  }
  $my_uniqe_key = generate_some_unique_key_function();
  //Here I wan't to set the value of the component 'my unique ID', but nothing worked yet
  $form_state['my_unique_id']['#value'] = $my_uniqe_key;
}

Thanks for the help, I'm sure I could find the answer somewhere, but I tried it 3hours long...

Here  is the $form and $form_state written out with dpm from my webform_custom_submit function.

And here are some codes, I tried already:

<?php
$form['values']['my_unique_id'] = $my_uniqe_key;
$form['values']['my_unique_id']['#value'] = $my_uniqe_key;
$form['values']['my_unique_id']['value'] = $my_uniqe_key;
$form['submitted']['my_unique_id']['#value'] = $my_uniqe_key;
$form['my_unique_id']['und']['0']['value']['#value'] = $my_uniqe_key;
$form_state['values']['my_unique_id'] = $my_uniqe_key;
$form_state['values']['my_unique_id']['#value'] = $my_uniqe_key;
$form_state['values']['my_unique_id']['value'] = $my_uniqe_key;
$form_state['my_unique_id']['und']['0']['value']['#value'] = $my_uniqe_key;
$form_state['values']['my_unique_id'][LANGUAGE_NONE][0]['value'] = $my_uniqe_key;
drupal_array_set_nested_value($form, array('submitted', 'my_unique_id', '#value'), $my_uniqe_key;);
form_set_value( array('submitted','my_unique_id'), array(0 => array('value' => $my_uniqe_key;)), $form_state) ;

$cid = $form['#node']->webform['cids']['my_unique_id'];
$form_state['values']['submitted'][$cid] = "static text";

You should use the presave hook provided by webform instead of adding additional submit handlers to the form.

/**
 * Modify a Webform submission, prior to saving it in the database.
 *
 * @param $node
 *   The Webform node on which this submission was made.
 * @param $submission
 *   The Webform submission that is about to be saved to the database.
 */
function hook_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  $component_id = 4;
  $submission->data[$component_id][0] = 'foo';
}

This is a lot cleaner than adding custom submit handlers to the form (your custom handler is called after the webform submission handler, which can be a big part of the problem).

You have access to the node object in the presave hook so additional checks can be added beforre altering the component.


Correct way to add custom column to user table? I'm looking to add a column called 'updated' directly to the users table.

The Field API and Joins are not an option for me in this case due to external constraints.

How can I safely modify the user_schema to add the 'updated' column in a custom module and safely clean it up when the module is removed?

Here is the layout of the 'updated' column based on the Schema API:

  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );

Currently my attempts using hook_install are not working as I believe they should.

It seems that I was missing hook_schema_alter(). This fixed my issues with drupal_write_record() and views.  Thank you @Clive for your comment here.

Overview of what you need to do:

In hook_install() you need to call db_add_field() to add a field.
In hook_schema_alter() you modify the schema so that other modules can
interact with your changes.
In hook_uninstall() you need to call db_drop_field() to clean up/remove your added field.

Actual Code:

Here is how I accomplished this.  The code below belongs in your module.install file.

function hook_install() {
  $field = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
  $index = array(
      'indexes' => array(
          'updated' => array('updated')
      ),
  );
  db_add_field('users', 'updated', $field, $index);
}
function hook_schema_alter(&$schema) {
  $schema['users']['fields']['updated'] = array(
      'type' => 'int',
      'not null' => TRUE,
      'default' => 0,
      'description' => 'Timestamp for last time user was updated.',
  );
}

function hook_uninstall() {
  db_drop_field('users', 'updated');
}


MachineName field element: How do I use the source and exists properties? In my custom form, I am trying to create webform entities. Since webforms need unique machine names, I'm using the MachineName (machine_name) form element. The D8 MachineName element documentation suggests that we can get the field to auto-populate based on the text input of another field, AND there can be an AJAX callback to call a function that can check to see if the machine name is unique.

Neither is working for me. These are the form elements I am using.

//----------------- general settings ------------------
$form['settings'] = array(
  'label' => ['#type' => 'textfield','#title' => 'Form Title'],
  'id'=> array(
    '#type' => 'machine_name',
    'label' => 'hh',
    '#source' => ['label'],
    '#maxlength' => 64,
    '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    '#machine_name' => array(
      'exists' => array(
        $this,
        'webform_id_exists',
      ),
    ),
  ),
);

Can anyone advise? I have a callback function named, but no idea what it should look like.

We can look at Drupal\node\NodeTypeForm.php for an example.

We see the name and type fields defined like:

$form['name'] = array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  // ...
);
$form['type'] = array(
  '#type' => 'machine_name',
  // ...
  '#machine_name' => array(
    'exists' => [
      'Drupal\node\Entity\NodeType',
      'load',
    ],
    'source' => array(
      'name',
    ),
  ),
  // ...
);

This shows us how to define the special machine_name type properties in the array. We can see that both exists and source are defined inside #machine_name. Additionally, we see that the exists callback is just calling the NodeType::load() (which is actually inherited straight from Drupal\Core\Entity\Entity::load()).

For our exists callback, given this example, we'll want to use the equivalent method for whatever kind of entity we're creating a machine name for. Given your example, we're creating webforms, so we'd use the Drupal\webform\Entity\Webform::load() method for the exists callback.

We also see, from the machine_name element documentation, that the source property needs to be the #array_parents of the source field. Since your fields are nested inside settings, you'll need to include it in the source property.

Given the above, your updated code should be:

$form['settings'] = [
  'label' => [
    '#type' => 'textfield',
    '#title' => 'Form Title'
  ],
  'id'=> [
    '#type' => 'machine_name',
    'label' => 'hh',
    '#maxlength' => 64,
    '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    '#machine_name' => [
      'exists' => [
        'Drupal\webform\Entity\Webform',
        'load',
      ],
      'source' => [
        'settings',
        'label',
      ],
    ],
  ],
];


How do I completely disable user profiles and the dedicated login page in Drupal 7? I am building a site in which user accounts matter only to provide the authenticated / not authenticated information. I created a custom login block that is always displayed (in the header of the website). I want to reach the following two points:

Since user profiles are not needed, I want to disable them for usability reasons. The users should, after login, be redirected to the landing page of my website.
Also, I want to disable the dedicated login page that appears, i.e., upon entering the wrong password.

Is there any easy way to do these things?

Yes, you can change built in menu / page callbacks with hook_menu_alter

For example, alter user_menu

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Go to front page when visiting /user and /user/login
  $items['user']['page callback'] = 'drupal_goto';
}


how to overreide page.tpl.php with my custom menu I have override page.tpl.php with my new custom menu created in my custom module. my menu look like below

$items['node/edit/restaurant/%/barcodes'] = array(
    'title'=>'Barcodes',
    'menu_name' => 'barcodes',
    'description'=>'Barcodes',
    'page callback'      => 'drupal_get_form',
    'page arguments' => array('leo_MSTag_barcode', 5),
    'access callback'=>TRUE,
    'type' => MENU_CALLBACK,
  );

I already try with page--barcodes.tpl.php, page--node--edit--restaurant--barcodes.tpl.php but not work for me. any new template suggestion for override mu menu page?

I guess you could do something like this:

function MYMODULE_preprocess_page(&$vars) {
  $patterns = 'node/edit/restaurant/*/barcodes';
  if (drupal_match_path($_GET['q'], $patterns)) {
    $vars['theme_hook_suggestions'][] = 'page__node__edit__restaurant__barcodes';
  }
}

That would let you use page--node--edit--restaurant--barcodes.tpl.php after a cache clear.

As an aside, your page arguments are wrong in the router item, should be:

'page arguments' => array('leo_MSTag_barcode', 3), // <-- Index of arg is 3, not 5


taxonomy menu select list with redirect when a menu item is selected I'd like to have a taxonomy drop-down list like the one in www.1mobile.com.

When I select an term, it should go to the respective page, showing products concerning with selected term.
I tried Custom Search module. But as far as I concern, it is not meet my requirement.

What is the best way to fulfill this requirement?

Try Autocomplete Deluxe, it has a taxonomy widget available for use, and I used it just the other day and I believe that it does what you need it to do.


Seamless Responsive Photo Grid with Omega I'm trying to create a responsive full screen gallery based on quite a simple idea, but without success. Idea is to have full screen view of many pictures that are adapting to screen resolution responsively.

The idea you can see here: http://css-tricks.com/seamless-responsive-photo-grid/

I'm working on D7.20, Omega 3.x

And what I want to do is to have content type, let's say, "picture" and create a view, which is displayed in a fluid full screen layout and is shown in such a way like in a given example.

But no success, it looks like it should be simple, but I cannot manage to understand how should I change the CSS to make it work...

It is probably possible to make similar effect using jQuery Masonry module, but I would like to do this with only CSS.

I have a kind of similar issue. I was actually trying to display different packages where the packages div's had variation in heights. I tried to align them using css without any luck.

so I then tried Isotopes and that worked perfectly.

You should also try https://drupal.org/project/isotope it comes with Example Context Reaction for Isotope.

there is also https://drupal.org/project/views_isotope module

You can also use

https://drupal.org/project/views_fluidgrid
https://drupal.org/project/masonry
https://drupal.org/project/masonry_views


TableSelect with drag-and-drop weight I have a tableselect and I have been looking all over the internet for a tutorial on how to make a tableselect have sorting/drag-and-drop functionality. I have found tutorials for making normal lists have click and drag, but not a single mention of tableselect.

I would like to know if making a tableselect draggable is possible. I'm not asking for a tutorial. At this time I just want to know if it is possible.

This the form element I am using.

$form['mod_setttings']['settings'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No settings available')
);

This tableselect is inside a vertical_tabs element.

i think you are looking for tabledrag option.If so please refer  drupal_add_tabledrag


Drupal 8: Prevent webform from saving IP About the webform module: It always stores the IP with a submission unless it's set as confidential. Is there a way to not store the IP while leaving it as not confidential?

In webform/src/WebformSubmissionForm.php is the function save where it sets the remote_addr. Is there any way to hook this? I don't think it works with a custom webform handler...

Thanks! Looking forward for your answers!

You could override the save function of webform/src/WebformSubmissionForm.php, but as you specifically ask for a hook and because this is probably also the easiest solution you can remove the field value set by the form before the entity gets saved:

use Drupal\webform\WebformSubmissionInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for webform submissions.
 */
function mymodule_webform_submission_presave(WebformSubmissionInterface $webform_submission) {
  $webform_submission->remote_addr->value = '';
}


Change the default selection for a Views 2 exposed filter I have an exposed filter in my View that allows users to choose between two different content types. The default value for the exposed filter seems to be chosen by whichever content type comes first alphabetically. So, if I let users choose between "Band" and "Song" content types, the default is "Band". I want to change this default value to a different content type ("Song" in the example here). I can't find an option in the Views interface for this. Do I have to do this via hook_form_alter? If so, how exactly would I do that?

So, I tried the way that @David Lanier suggested, but couldn't quite wrap my head around it. So I went back to Drupal basics and tried it from the hook_form_alter() approach. After some troubleshooting, I also found a post about changing default Views filter values. I took the same approach and got it working. Below is the code a used, with a couple of modifications to take out my site-specific stuff. As always, be sure to replace "modulename" with the name of your module.

function modulename_form_alter(&$form, $form_state, $form_id) {
 // is this the right form?
 if($form['#id'] == 'name-of-the-views-form-displayed') {
   if (empty($_GET['label-of-the-filter']))  {
    $form_state['input']['label-of-the-filter'] = 'default-value-for-filter';
   }
  }
}

Just replace name-of-the-views-form-displayed with, you guessed, the name of the views form you want to change. The easiest way to find this is to inspect the source of the View in the browser (I love Firebug for this) and find the form element, then grab it's id attribute. To find the name of the filter and the value you should set, change the filters and perform the "search". Look in the address bar and you'll see the values you need to use here as parameters in the url.

Hope this helps get others around this issue too!


Do private properties persist between submissions on multi-step form? I'm creating a 3-step (3-page) form in Drupal 8.  One property I use for all three pages is $continue - which triggers an exit process (redirect) if an error condition is encountered, or allows the process to continue through all three pages.  Also, there is a node created during submitForm() in step 1, and the node id is needed in steps 2 and 3.

I'm struggling with exactly how to pass data of that nature through the multiple steps.  Initially, the form is built, and properties can be initialized in the constructor.  But after the user submits the form, that's an entirely new request, right?  So doesn't the form class have to be instantiated again before the submitForm() method is invoked?  If so, it doesn't seem like properties could persist from buildForm() to submitForm() and back to the buildForm() for step 2?

In Drupal 7, I had to save all values I wanted to persist into $form_state.  Do I still need to do the same in Drupal 8?

Yes, do the same in D8, use $form_state. There is one caveat though. The form object and form state doesn't persist for the original form build. This was removed in the early stages of Drupal 8, because the form cache table was growing too fast. Since then forms are only cached after the first rebuild.

Normally this isn't a problem. If you store for example the form step in $form_state and it is initialized again with 1, but you have a form action triggered incrementing it to 2, your form then can use the cached $form_state to move back and forth.

This doesn't work however for data no longer available in later rebuilds. In this case use a hidden form value which will be cached together with the rendered form. Add the correct cache metadata for this value so that the rendered form can be invalidated when the value is changed.


Programmatically subscribing user to a organic group I need to expose OG memberships within API functions calls and wonder how to programmatically subscribe a user to a group (pending state) and then i need to approve him programmatically and change from pending to member. Im using OG 7.2.

function ask_membership($uid, $gid){
  ????
}

function approve_membership($uid, $gid){
  ????
}

Any help appreciated

Ok got it working, its still the og_group() function.

function group_membership($type, $gid, $uid){
  $group_type = 'node'; //All our/my groups are of type node
  $entity_type = 'user'; //All our/my members are type users
  $values = array(
    'entity_type' => 'user',
    'entity' => $uid,
    'field_name' => FALSE,
    'state' => 1,
  );
  $return = FALSE;

    switch ($type){
        case 'subscribe':
          $values['state'] = 2;
          og_group($group_type, $gid, $values);
        $return = 'SUBSCRIBED TO TEAM';
          break;
      case  'approve':
          $values['state'] = 1;
          og_group($group_type, $gid, $values);
        $return = 'APPROVED TO TEAM';
        break;
      case 'delete':
        og_ungroup($group_type, $gid, $entity_type, $uid);
        $return = 'REMOVED FROM TEAM';
        break;
      default:
        $return = 'FALSE TYPE';
        break;
    }

  print json_encode($return);
}

Not that pretty but it works for now.


Comment template for specific comment type How can I have a comment template (comment.html.twig) per comment type?

The Twig Template naming conventions documentation explains how I can get a comment template per node content type (comment--node-[type].html.twig), but it doesn’t mention comment types.

I have a node content type with multiple comment fields (one for each comment type), so filtering by node content type doesn’t help me.

Enable Twig Debugging, then you'll get template suggestions printed as HTML comments directly into the markup.

I did that and got the following output:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'comment__field_my_comment_field__article' -->
<!-- FILE NAME SUGGESTIONS:
   * comment--field-my-comment-field--article.html.twig
   * comment--field-my-comment-field.html.twig
   x comment.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/content/comment.html.twig' -->

So, the templates are supposed to be named like the following pattern:

comment--field-name-of-the-comment-field-in-the-content-type--content-type.html.twig
comment--field-name-of-the-comment-field-in-the-content-type.html.twig


error creating a basic page when I create a simple basic page like About Us and I click Save Preview I get the errror ”The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "" (without the quotes) to fine-tune where your post gets split.” How can I get rid of this?

saadlulu is right - this is a notice (not an error) provided by the core node module and relates to the preview functionality you have enabled. Are you trying to disable preview?

If you just want to disable the message, try the 'disable messages' module and make sure to heed the advice here and use the following wildcard:

The trimmed version of your post shows what your post looks like when promoted to the main page.*


Delete all empty orders on user login Case: Delete all empty orders for a user when he/she login to the website.

We are using drupal commerce.

Please Help.

It seems that these orders, where in the shopping cart when the current user log off, and never proceed to pay. In order to not lose this product in the cart for the next login, there has to be a relation to the user and product.

If your eCommerce module doesn't have any configuration to delete products on logout, try using hook_user_logout

  Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and user_save() goes out of scope. You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately.


How to display node's taxonomy child items in node using views for multiple parents I have a vocabulary with child terms

term
-child_term
-child_term_1
-child_term_2
-term_1
-child_term
-child_term_1
-child_term_2

Nodes have multiple parent terms assigned.

The goal is to display all parent and child terms in the exact node using views field.

I tried to implement it using taxonomy tree view with contextual filter (taxonomy term ID from the URL), but it displays only child terms for the first (one) parent item of the node.

Even view's "Preview with contextual filters" does not understand multiple contextual filter values with a "/"

How can I do this?

The goal was to display child items for multiple taxonomy terms of the node in a node's field using views.

Solution:

Create content type with:

Taxonomy term field (multiple values) - it's for parent items
Views field - it's for displaying child items for ALL parents

Make standard taxonomy tree view with ajacency model (search google)

Add a contextual filter with parent term ID

Provide default value
Taxonomy term ID from the URL
filter to items that share any term
When the filter value IS available or a default is provided

Specify validation criteria - taxonomy term ID
Filter value type - Ternm IDs separated by , or +

Edit view field of previously created content type

Select the view created as a default value for this field
From placeholder list select [node:field_bla_bla] (that's taxonomy parent field in the node) as an argument passed to default value


How to login to an external website after drupal-login? I would like know how I can login my user to an external website after drupal-login please ?

I use :

    $xenAPI = new XenAPI('http://xen.dev/api.php', 'MY_API_KEY', 'MY_API_KEYSALT');
    $xenAPI->login('Kyna', 'secret_password', 'http://theming.dev');

The login work on all page when I use HOOK_user_load(), but if I use HOOK_user_login(), don't work. I don't have an error, but ->login() create a redirection with an header and I think drupal-login overwrite my header on external script or create a redirection before my script.

Yes, the login form has a redirection(see the \Drupal\user\Form\UserLoginForm::submitForm()), so you need to remove that redirection with $this->getRequest()->query->remove('destination').


Redirect customer to specific order checkout later I'm using Commerce Quotes sandbox project (https://www.drupal.org/sandbox/xatoo/1860944) to get quote system in commerce. Customer add products to cart and requests a quote instead of checkout. Then store owner can respond to quote (store owner may give discounts to product s unit price) and system sends new quote to customer by email. Then customer can accept or decline the offer.

My problem is that if customer accepts the offer he/she should be able to pay the order in the website. Is there some url I could redirect customer to? I tried following approach with Rules:

After accepting quote change Order status to "Checkout: Shipping"
Redirect customer to /checkout/[order_id]/shipping

The problem was that now in checkout product prices were original, not the discounted one that store owner was saved to order. Any idea why is that?

Is there better way to let customer pay the accepted offer?

Big thanks in advance!

Sounds to me like the sandbox isn't using pricing rules to set the "new offer."

Here's what I would do (without knowing what the sandbox is doing):

I would create a custom line item type using commerce_custom_product
I would then add a price field called "price_override"
I would then create a pricing rule that overrides the original price of the line item with the "overridden price" if it exists.
I would then make sure that the sandbox or a custom module sets that line item field when a new offer is made

The above approach has the benefit that the price is actually using pricing rules, but the "custom price" is per-line-item instead of per-order. Now it might be possible, depending on how the sandbox is functioning, to access the "custom pricing" and use it in a pricing rule. But the same approach would still be taken above.

// Edit

You can always just send users to "/checkout" ... but likely they would need to be logged in first to be connected to their order (this would be based on default permissions). So I would use the Drupal system to your advantage, this little link will present anonymous users with a login form, then redirect to checkout (and will simply redirect to checkout if logged in):

/user/login?destination=checkout


How do I get the ID value from a URL example.com:8080/browse?category=137 is my URL for a taxonomy category page.

How am I supposed to take the category ID (137) from that URI?

You can take that id from get array, try

print $_GET['category'];


Commerce 2 | Quantity Dropdown with Default Values -> Error I need to allow the costumers to choose specific quantities for specific type of products but I would like to avoid adding 2 extra modules to my website ( Commerce Extended Quantity & Extended Number Field). So I used a form alter function like here Set default "Quantity" dropdown select in product. Commerce Kickstart.

The issue is that the input is transformed to a dropdown but when the form is submitted, a blank page appears with the message "The website encountered an unexpected error" and the error in admin/reports/dblog is Cannot unset string offsets in Drupal\Core\Field\WidgetBase->extractFormValues()... Here is the code I use:

function mymodule_form_alter(&$form, $form_state, $form_id) {

  if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {

  // Change widget type of quantity to select list
 $form['quantity'] = array(
'#title' => t('Quantity'),
'#type' => 'select',
'#datatype' => 'integer', // <-- I added this one to fix Notice: Undefined index: #datatype in commerce_cart_add_to_cart_form_validate() when you click add to cart button
'#options' => array(
  1 => '1',
  2 => '2',
  3 => '3'
)
);

 }}

Does anybody know if there is a way to fix this error? Thanks!

I found the solution to my issue:

 function mymodule_form_alter(&$form, $form_state, $form_id) {

 if (strpos($form_id, "commerce_order_item_add_to_cart_form") !== false) {
$form['quantity']['widget'][0]['value']['#default_value'] = 1;
 $form['quantity']['widget'][0]['value']['#step'] = 0.5;
   $form['quantity']['widget'][0]['value']['#min'] = 1;
    $form['quantity']['widget'][0]['value']['#max'] = 3;
    $form['quantity']['widget'][0]['value']['#type'] = 'select';
 $form['quantity']['widget'][0]['value']['#options'] = array(
 '1' => t('1 hour'),
'1.5' => t('1,5 hour'),
  '2' => t('2 hours'),
   '2.5' => t('2,5 hours'),
   '3' => t('3 hours') );
    }}


Ouput yes/no in commerce product table if product image available/not available I am using Drupal 7 together with Drupal Commerce (not Kickstart). I am using a Bootstrap theme.

I have list of products displayed in a table that I created with Views. If you click on the Title, it goes to the product content page (display). Obviously, a product has an image if one is available. What I would want to do is to have a column in the table (Image), that would print out Yes or No, depending on if the image is uploaded (available) for the product.

Is this something that can be done in Drupal?

Simply add your image field. When you add it, or if you click on it if you already added it, you will see something similar to the following date field screenshot.

Click on rewrite results and put "Yes" here.
Click on no results behavior and put "No" here.

  Is there a way to solve this in a similar way if you have a default
  image set - if none is uploaded a default image shows up?

In this scenario you would have to use Image URL Formatter and set the view image field formatter to display url.

Then you would simply perform a conditional check to see if the URL is equal to the default image url either using Views template file & custom code OR alternatively using Views Conditional for a zero coding solution.


Have user register or login on cart instead of checkout in drupal commerce Is it possible to have the user account pane in the cart instead of the checkout?

I need to have users logged in or registered on the cart, because when users checkout I have a custom rule to change the order to a custom state "awating approval", and sends the user to a custom page with some text. Once the order is approved by the staff the state is changed to another custom state "approved" and a custom rule sends an email to the user so he can checkout and finish paying.

The problem is that if the user hasn't enetered his details before attempting to checkout, the email won't be saved and we have nowhere to send the user an email to finish checking out once the order is appproved.

Is it possible: Yes.
Should you do it: No.

Why?

Having the user account pane at the the cart is a bad idea, since it probably would be very complex to do, and that there isn't really anything that hinders the user to start the checkout flow. You are also forgetting a very important thing.

The Commerce checkout flow is very customizable. This means that you can define extra pages in the checkout flow, and via the interface customize what should be displayed in each page. A much better solution would be to create an initial checkout page with account info only, an extra page that displays info about the order being validated and not allowing to process the order until it is approved. Once approved, the link could simply be that checkout page which with the updated order status can be skipped.

This will keep the customer in the checkout process and leverage the Commerce flexibility.


Mutlti level filter with search api and facet in commerce kickstart I'm using commerce kickstart, I want to use the built-in filter blocks (facet & search-api).
I have multi-level categories (taxonomy), but filters just display parents categories.
For example I have as categories:

  computers
  -laptops
  -desktops
  -notebook
  Networking
  -routers
  -modems

Filters just display computers and networking

It sounds like you need to enable the "Expand Heierarcy" option under Facet Display settings (for the search index you are working with).


Composer doesn't see that updates are needed My Drupal version is 8.5.1, and yet when I run...

composer outdated drupal/*

It says "nothing to install or update".

What to do?

This is the relevant part of my composer.json...

"require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/core": "^8.5"
    },

Looks fine to me, but composer says no update is available.

Update:  This is not a good answer.  Leaving it here for reference, but this does not solve the underlying problem, whatever it is.

Fixed by deleting vendor and core directories and composer.lock and then running...

composer update drupal/core --with-dependencies

It seems there must be some circumstances when the 'composer outdated' command doesn't work, but it's still possible to upgrade.


Expose date filter in views So, what I want is a dropdown to filter news by months, the select box is like that(months are grouped by years):

- All
-- 2013
--- Jan
--- Feb
--- Mar
--- ...
-- 2012
--- Jan
--- Feb
--- Mar

How I can do that ?

Thank you for your Help.

You just need to create groups for these results:

you want to group the results by Year and Month, so you need to add two fields:

First field for group by Year [Content: Post date]:

Second field for group by Month [Content: Post date]:

Add filters and sort criteria:

Choose format settings:

Group yearly results:

Group monthly results:

That's it!

Your results:

- 2013
-- Jan
--- tilte #1
--- ...
-- Feb
--- title #4
--- ...
--- Mar
--- title #6
--- ...


Add lightbox to product list in Ubercart I'm trying to enable lightbox2 for product listings in Ubercart for Drupal 6. This is simple via views, but I think the product list is being generated by uc_catalog module. How can I add classes to the product thumbnails or enable lightbox2 for them? Are tpl.php files available to customize output? Thanks for any help.

Maybe you should create the product list with Views instead. Not only can you easily add lightbox like you write yourself, but you can make a lot of customizations should the need arise.

If you don't want to use Views, it's most likely the taxonomy module that generates the product list, that's how it's done on many UC sites. You could install the devel_themer and inspect the product list page with it. It should allow you to see what theme functions is being used to create the page. This should also help you figure out how you can add the customizations your want via template files or theme overrides.


AJAX callback issue when using 'Manage Form Display' and 'Manage Display' Good day everyone,

So I have an issue that I haven't been able to google. The issue seems rather simple but I don't know what's causing it. When i'm managing field displays in either the form or a view, the ajax 'throbber' icon pops up and the ajax request is never completed. It will continue to show the throbber indefinitely. If I drag the field to another location, it will create another instance of the throbber icon and no ajax request is ever completed. I can do this any amount of times. When I save the form and a field is in the AJAX state, it just reverts back to whatever it was originally. The weird thing is, if I press the cog to change the settings of the field and that field was in the 'perpetual ajax request' state, it will then complete the ajax request as expected.

This leads me to believe that dragging and dropping the fields (and changing the formatter/widget) aren't actually sending any ajax requests. This is also confirmed by checking the Network tab in Chrome's tools. Nothing is sent when dragging fields but when pressing the cog "teaser?ajax_form=1&_wrapper_format=drupal_ajax" request is sent.

I'm at a loss as to what is happening. It only started recently (last couple hours of development) and I went through the changes I've made in that time to try and identify the problem and have come up with nothing. I checked for differences from the production site and nothing... I'm not sure what to do next. Has anyone experienced this problem and successfully fixed it?

Well, I feel like a fool as the answer was actually simple... I had forgotten about switching all input elements to actual button elements. This broke any AJAX request only when the type was a submit button.


Views Tables on Responsive Layout I have a views table block within a panel.

The table is overflowing the panel and I am trying to understand how to constrain it. I have tried setting it's CSS to various widths but they are always ignored. I can change individual column widths, colours etc but not the width.

Do views tables ignore these settings and just display to the width of their content?
What is the best way to set their width?

Any tips for using views tables in responsive themes(within panels)?

I'm using Drupal 7.23 , Views 7.37 , Panels 7.33 , Omega-4

Update:
In my CSS for this table I have previously tried setting table {
  width: 100%; (and with !important). I know it is being applied to the table as when I have very colums it increase the width of the whole table to 100% of it's panel.

The problem occurs when there are a lot of columns and the content text of the column is wide. Then the table overflows past 100%. I can make it thinner by changing font size but I am trying to understand how the views table width is set.

In terms of Views table plugins / modules I am looking at FooTable , Responsive Tables and (sandbox) Better Views Tables. None of these are mature modules so I am quite nervous about using them.

Set the table width to 100% with css. If some other rule is overriding this, you may have to increase the specificity or add !important.

If you need more control of your table columns, there is a cool module for responsive tables: https://drupal.org/project/responsive_tables. Haven't yet tried it myself.


How to set a value for a date field? I need to set a value for a date field with type datetime in hook_form_alter. I tried with below codes. But it is not working.

$form["field_event_date"]["und"][0]['#default_value']['value'] = $new_date;
$form_state['values']['field_event_date']['und'][0]['value']['date'] = $new_date;
$form['field_event_date'][LANGUAGE_NONE][0]['#default_value']['value'] = $new_date;

This $new_date will be a value from another field in this form and it should be in '2014-09-23 00:00:00' format. And 'field_event_date' will be a hidden field.

I can save the value to this field using the node_presave function. Please see the below code. If anyone trying to save a value to a date field with a static value, you can use this method.

function MY_MODULE_node_presave($node) {
     $node->field_event_date['und'][0]['value'] =  '2014-09-23 00:00:00';
}

But in my case, I need to get the value from a field that defined in the form alter. And need to set this value to the field_event_date. Can anyone help me on this? Is there any way to get a custom field value in node_presave function?

To set a value to a date field follow below codes.

Using hook_form_alter

$form["field_event_date"]["und"][0]['#default_value']['value'] = $new_date;

Using hook_node_submit or hook_node_presave (Saving the value to the database)

 function MY_MODULE_node_presave($node)
  {
      $node->field_event_date['und'][0]['value'] =  '2014-09-23 00:00:00';
  }

Or if you need to save value of one custom field(defined in hook_form_alter) to another, see below codes.

function MY_MODULE_node_submit($node, $form, &$form_state) {
  if($node->type == 'my_node_type') {
    $test_date =  $form['test_date ']['#value'];
    //Ensure that $test_date format is '2014-09-23 00:00:00'
    $node->field_event_date['und'][0]['value'] =  $test_date ;
   }
}

I think it may help anyone who is searching for the solution.


How to check programatically whether a comment is new? I'd like to make some changes to a new comment programatically. I'm using the following code:

function MYMODULE_comment_presave($comment) {
    $user = user_load($comment->uid);
    $uid = $user->uid;
    // if ($comment->is_new) {
        $comment->field_image['und'][0]['fid'] = $user->field_image['und'][0]['fid'];
        }
    // }
}

I don't know how I can check whether the comment that's about to be saved is new or edited. $comment->is_new doesn't work.

How can I solve this?

Use hook_comment_insert() instead, that should work.


Disable a 'enter/return' key function in a form I have a form in which a user needs to fill the fields. As only two fields are the required fields, so when user fills the required fields and press enter(windows)/return(mac) key the form gets submitted. I'm trying to disable the enter/return key function. So, for this I tried to inject a jQuery within the form.

my jQuery is as follows:

(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {
$("input").keypress(function (evt) {
var enterCode = evt.charCode || evt.keyCode;
if (enterCode  == 13) { return false;
}
});
  }
});
}
};
})(jQuery);

The jQuery part is familiar to me, but it doesn't work in the site. And the form responds to enter/return key press.

Is there any other way to disable enter/return key press. something like a module..

You need to use evt.preventDefault();

I wrote a blog post on making this work with drupal and ajaxified forms, which may let you see a slightly larger example including Drupal.behaviors.


How can I set a default value for the country in an addressfield? I'm trying to set the default value for a country in an addressfield (caught in hook_form_alter) and ensure that the associated fields (administrative area, etc.) are refreshed properly. How can I do this?

Finally figured it out. The idea is to emulate the code in addressfield_field_widget_form(). Here's the recipe:

 /**
  * Implements hook_form_FORMID_alter() for `commerce_checkout_form_checkout`.
  */
 function mymodule_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
    // Get the addressfield element we're modifying.
    // Adapted from addressfield.module/addressfield_field_widget_form()
    $element =& $form['customer_profile_shipping']['commerce_customer_address'][LANGUAGE_NONE][0];
    $element_key = $element['element_key']['#value'];
    $field = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['field'];
    $instance = $form_state['field']['commerce_customer_address'][LANGUAGE_NONE]['instance'];
    $delta = $element['#delta'];
    $settings = $instance['widget']['settings'];
    $langcode = $element['#language'];
    $items = array($delta => $element['#address']);

    // Get the default address used to build the widget form elements, looking
    // first in the form state, then in the stored value for the field, and then
    // in the default values of the instance.
    $address = array();

    if (!empty($form_state['addressfield'][$element_key])) {
      // Use the value from the form_state if available.
      $address = $form_state['addressfield'][$element_key];
    }
    elseif (!empty($items[$delta]['country'])) {
      // Else use the saved value for the field.
      $address = $items[$delta];
    }
    else {
      // Otherwise use the instance default.
      $address = (array) $instance['default_value'][0];
    }

    // Merge in default values to provide a value for every expected array key.
    $countries = _addressfield_country_options_list($field, $instance);
    $address += addressfield_default_values($countries);

    // Set our default country.
    // THAT'S THE PAYLOAD!
    if ($address['country'] != $my_default_country) {
      $address['country'] = $my_default_country;
      $address['administrative_area'] = '';
    }

    // Add the form elements for the standard widget, which includes a country
    // select list at the top that reloads the available address elements when the
    // country is changed.
    if ($instance['widget']['type'] == 'addressfield_standard') {
      // Generate the address form.
      $context = array(
        'mode' => 'form',
        'field' => $field,
        'instance' => $instance,
        'langcode' => $langcode,
        'delta' => $delta,
      );
      $element = array_merge($element, addressfield_generate($address, $settings['format_handlers'], $context));

      // Mark the form element as required if necessary.
      $element['#required'] = $delta == 0 && $instance['required'];
    }
  }


Drupal 7 Does “New Node Creation” initiate/prepare the Fields for different Content Types? In Drupal 7, i need to Programmatically create the Nodes. As usual, there are Different Fields set for Different Content Types.

For very simple example:

Content Type: "car"
Fields: "Model", "Engine", "GearType"

Content Type: "article"
Fields: "Title", "Author", "Media"

What i want to be confirmed here is, while i am creating a new node, for e.g by using:

$node = new stdClass();
$node->type = "car";

Then..

Is that (currently creating) new $node has been initiated/loaded with its related/corresponded fields, already before get saved?
To be more clear, if i just suddenly Save a node node_save($node) (without filling any other related fields) will that node be still having (following) its proper Content Type structure?

The node can have fields attached to it. If any are required and not provided then I believe your save() will fail with an error message. If your fields provide a default value that value will be used for those fields.

If there are no required fields. The basic node information (nid, type, title?) will be the only values set on your new node (and timestamps, owner uid).

I believe it's up to you the developer to assure the fields have the data you want when you save the node (and meet the Requirements of the node/fields configuration) from the Field UI.


Same user for multiple sites I am planning to use different server for multiple purpose.
like

Groups.eg.com

Privatecontent.eg.com

review.eg.com

etc...
I have up to 5 different subdomains and everything runs in different server and different drupal installation.

I want to use the same user base across all these sites.

I am aware that if a single drupal installation have multiple sites we achieve this using domain module.

Is there a best solution for my use case.
Because we are going to load 10k users in the site.

Sounds like Bakery module would meet the requirements for you. It will handle single sign-on between Drupal sites on different sub-domains.

As far as performance goes, Bakery is used by drupal.org when you switch between https://www.drupal.org, https://groups.drupal.org, https://assoc.drupal.org and others.

What it doesn't do is to switch between different domains like drupal.org and drupal.com. Bakery also doesn't sync user information, if you have user fields.

For more advanced features like SSO between Drupal and non-Drupal, look at CAS module, or some of the other single sign-on solutions.


Make a carousel of every node associated with a term in a particular vocabulary I have a vocabulary with a lot of terms in it, I want to show list of each term's nodes as a carousel using views.

I rather using OwlCarousel module to achieve this.

Can you guide me how to configure the views to achieve this?

Here are the steps

Make a views of taxonomy terms.
Add a relationship referencing node from that taxonomy terms
Now you will have the required node fields available in views field
Add the required field and change the display to carousel.

I hope this will help.


Extract final value from nested field collection I have a content type with a field collection. This field collection has, as fields, other field collections. It works well, it groups the content for a node perfectly, but when trying to extract the data programmatically, I cannot access the values introduced. How would be the method. I tried with this piece of code, but it throws an error. Also not sure if adequate to my case (nested field collections):

$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group as $field_collection_wrapper) {
            $field_collection = $field_collection_wrapper->value();
                print_r($field_collection);
}

Try this :

$node = node_load($node->nid);
$node_wrapper = entity_metadata_wrapper('node', $node);

foreach ($node_wrapper->field_rich_text_group->value() as $value) {
  $field_collection_wrapper = entity_metadata_wrapper('field_collection_item', $value);
  $field_collection_myfield = $field_collection_wrapper->field_myfield->value();
  print_r($field_collection_myfield);
}

Field Collection is an entity, so if you want to access its field you have to pass the field collection in entity_metadata_wrapper. Then you can access the value of your fields in field collection like you do with your $node_wrapper


Unpublish node based on field option Is there a way to unpublish a node if a user selects an option from a select list in field?

I have a field that has a list of cities. What I would like is if the user selects a certain city like London for example, the node is automatically unpublished so it can be moderated.

I have been trying with rules but every time I test my rule nothing happens so I'm sure there is something wrong with my rule or maybe there is an easier approach?

You could also hook on hook_node_presave() and check here the value of the field... No ?

mymodule_node_presave($node) {
if($node->yourfield[.....]['value'] == 'London') {
$node->state = '0';
}
}


Using RegEx with Rules to compare email addresses I have a client content type with an email address and when a user creates an account I want to verify the users email address with the email address of the client content type to make sure that the user is an employee of the client and if so let them create an account.

My question is, can I make a rule which uses Regular expressions to compare the domain name of the two email fields?

Thanks

Kieran

You can use access rules which is built into core drupal.

Go to "/admin/user/rules" and add a new rule, for example %@domain.com, this will allow anyone to register who has that specific domain.


Javascript not loaded in loading ctools modal I have a some modal forms, the link of those embedded in views result,
link are somethings linke share/nojs/2 , I register a menu in callback of the links,
It work correctly  for root user, but I test it with 2 authenticated user, It work correctly for one of them and in another when I click link instead open modal form redirect me to /share/nojos/2 and tell me Javascript required,according to my codes,It means the javascript not load,
I really confused what happening and what can be reason of this ?

my codes :

$items['share/%ctools_js/%'] = array(
    // 'page callback' => 'ym_alter_sharing_content',
    'page callback' => 'ym_alter_sharing_callback',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
);

function ym_alter_sharing_callback($js = FALSE) {
    global $user;
// If people aren't using javascript, then I just boot em. sorry. its 2011.
    if (!$js)
        return "Javascript required";
// Include your ctools crap here
    ctools_include('node.pages', 'node', '');
    ctools_include('modal');
    ctools_include('ajax');

// Create a blank node object here. You can also set values for your custom fields here as well.
    $node = (object) array(
                'uid' => $user->uid,
                'name' => (isset($user->name) ? $user->name : ''),
                'type' => 'share',
                'language' => LANGUAGE_NONE,
    );

    $form_state = array(
        'title' => t('sharing'),
        'ajax' => TRUE,
    );

    $form_state['build_info']['args'] = array($node);
// change this to your type node form
    $output = ctools_modal_form_wrapper('share_node_form', $form_state);

// This means the form has been exectued
    if (!empty($form_state['executed'])) {
        $output = array();
// Close the modal
        $output[] = ctools_modal_command_dismiss();
// I use this method a lot on pages that have views, so what I do is get the latest view content
// with the latest node and replace the current view. magic!
        /*
          $html = views_embed_view('my_view', 'my_display';
          $output[] = ajax_command_html('.view-display-id-my_display', $html);
         */
    }
    print ajax_render($output);
    exit;
}

this looks like a hook_menu() implementation:

$items['share/%ctools_js/%'] = array(
// 'page callback' => 'ym_alter_sharing_content',
'page callback' => 'ym_alter_sharing_callback',
'page arguments' => array(1),
'access callback' => 'user_is_logged_in',
'type' => MENU_CALLBACK,

);

you should wrap it in a corresponding function and return menu items:

function your_module_name_menu() {
  $items['share/%ctools_js/%'] = array(
    // 'page callback' => 'ym_alter_sharing_content',
    'page callback' => 'ym_alter_sharing_callback',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

other code seems to be ok.
Hope this helps someone.


How to programmatically search content with a specific taxonomy term with Search API? I'm working on programmatically searching content with the Search API module. Ideally I would like the ability to select which taxonomy term of a content type is being searched. For example, if I have a content type of 'restaurants' and three taxonomy terms representing the style of restaurants, lets say 'Italian', 'Chinese' and 'Fast Food'. I would then like the ability to search and get results of all the restaurants content entities associated with, lets say, just the Chinese taxonomy term.

Here is the code that I have so far:

$search_entry = $form_state->getValue('search');

$query = \Drupal\search_api\Entity\Index::load('forum_ct_search')->query();
$query->keys($search_entry);
$query->range(0, 5);

$result = $query->execute();
$items = $result->getResultItems();

This is working as far as I'm able to search the specific content type I'm interested. However I'm assuming there is a way to ask the Search API to just search by taxonomy terms. If it's possible, my best guess is that it is with the addCondition method, such as this:

$query->addCondition('type', ['article', 'snippet'], 'IN');

If this is the correct method for filtering by taxonomy term what are the correct parameters? If not how may I?

The other alternative would be to weed out the taxonomy terms from the results. This would work but it strikes me as cleaner to do it the other way.

Any ideas? Thanks!

(I'm running Drupal 8.6 with Search API 1.12)

Yes that's right to do addCondition here's a page with some examples https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

So you'd just need to do the machine name of your indexed taxonomy field

$query->addCondition('my_indexed_field', $myvalue)


entity_metadata_wrapper langcode always prints default language I'm using entity_metadata_wrapper with entity translation to print fields in a template, but it always prints the default language when using a langcode in the options.

$wrap = entity_metadata_wrapper('node', $node->nid, array('langcode' => 'zh-hans'));
print $wrap->field_main_subtitle->value(); // Returns English value

Printing out the $wrap array shows the following towards the end which might give some clue (langcode:protected => und):

[propertyInfoAltered:protected] =>
    [langcode:protected] => und
    [propertyInfoDefaults:protected] => Array
        (
            [type] => text
            [getter callback] => entity_property_verbatim_get
            [clear] => Array
                (
                )

        )

    [type:protected] => node
    [data:protected] =>
    [info:protected] => Array
        (
            [langcode] => zh-hans
            [type] => node
            [property defaults] => Array
                (
                )

        )

Any ideas?

Try this

print $wrap->language('zh-hans')->field_main_subtitle->value()


How to send email to "anonymous" user when a new node is created I've been looking at a couple of modules and none of them seem to work the way I want to.

I'd like to display a textfield for an anonymous user to enter his email. Everytime a node of a certain type (blog post) is created, an email would be sent to every person who gave their email.

How could I achieve that in Drupal 7 ?

Thanks

Simplenews looks like it would work perfectly for this.

  Simplenews publishes and sends newsletters to lists of subscribers. Both anonymous and authenticated users can opt-in to different mailing lists. HTML email can be sent by adding Mime Mail module.


How to print H1 instead of H2 for Panel This is the template currently being used:

panels-pane.tpl.php

<?php if ($pane_prefix): ?>
  <?php print $pane_prefix; ?>
<?php endif; ?>
<div class="<?php print $classes; ?>" <?php print $id; ?> <?php print $attributes; ?>>
  <?php if ($admin_links): ?>
    <?php print $admin_links; ?>
  <?php endif; ?>

  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <<?php print $title_heading; ?><?php print $title_attributes; ?>>
      <?php print $title; ?>
    </<?php print $title_heading; ?>>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

  <?php if ($feeds): ?>

      <?php print $feeds; ?>

  <?php endif; ?>

    <?php print render($content); ?>

  <?php if ($links): ?>

      <?php print $links; ?>

  <?php endif; ?>

  <?php if ($more): ?>

      <?php print $more; ?>

  <?php endif; ?>

<?php if ($pane_suffix): ?>
  <?php print $pane_suffix; ?>
<?php endif; ?>

The variable $title_heading is h2. It comes in $content

panels.module

  $vars['title_heading'] = !empty($content->title_heading) ? $content->title_heading : variable_get('override_title_heading', 'h2');

However, I see no way of supplying it, and cannot create it in my Fieldable Pane Panel:

If I try to add a field, it comes with the field_ prefix, and I just need a plain title_heading.

How can I overcome this?

This feature is intended for Node title not Fieldable Panels Panes as per the screenshot  below:

Your best option is to override the panels-pane.tpl according to theme suggestions for your target pane and manually add the <h1> tag in place of the $title_heading variable.
It might not be an elegant solution but it works!


AutoSKU and Commerce Kickstart 2.0 or Commerce backoffice I would like to use the AutoSKU module with the functionality provided by commerce backoffice.  Right now what I have done is installed the module commerce_backoffice with my commerce module which is the functionality from Commerce Kickstart 2.0 from my understanding.

I then installed the AutoSKU module.  However, since the software design has changed there are no longer product types, there are product variation types.  It doesn't seem that AutoSKU works with the new functionality.

Has anyone ported AutoSKU to work with Commerce Kickstart 2.0?

The AutoSKU that works with product variations is part of Commerce Kickstart 2.0.  You will have to enable the module of AutoSKU once you have installed Commerce Kickstart 2.0.


Tracking isotope clicks with Google Analytics? Is there a way to track the clicks of the views isotope header through Google Analytics?

If so how would I set that up? Where would I put the file or code and in what type of file and how would that code be set up?

I'm using:
Drupal 7
Views module
Views isotope module
Google analytics module

You can use Google Event Tracking.
There is a great module for that already Google Analytics Event Tracking

Just enable both the main and the example module included so you can try it out.
In the selectors array you can define wich element you want to track (e.g. a#logo)
By setting 'label' => '!test' you can test if the click works (will show an alert box)

$selectors = array(
array(
  'event' => 'mousedown',
  'selector' => 'a#logo',
  'category' => 'Home Link',
  'action' => 'click',
  'label' => 'Logo',
  'value' => 0,
  'noninteraction' => TRUE,
),


How to select fields from content type What is the best way to do a db query for fields in a content type?

I need to get specific fields from a content type, but only where the 'featured' field value is 1.

<?php
        $query = new EntityFieldQuery();

        $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', 'mycontenttype')
          ->propertyCondition('status', NODE_PUBLISHED)
          ->fieldCondition('field_mypdf', 'value', 'NULL', '!=')
          ->fieldCondition('field_mypdf', 'fid', 'NULL', '!=')
          ->fieldCondition('field_mypdf_image', 'fid', 'NULL', '!=')
    ?>

Originally, I was doing something along the lines of:

<?php
$query = "SELECT node.nid AS nid, 'node' AS field_data_field_news_node_entity_type, 'node' AS field_data_field_news_date_text_node_entity_type, 'node' AS field_data_field_news_teaser_node_entity_type, 'node' AS field_data_field_news_body_node_entity_type, 'node' AS field_data_field_news_video_node_entity_type, 'node' AS field_data_field_news_video_image_node_entity_type, 'node' AS field_data_field_mypdf_node_entity_type
    FROM node
    INNER JOIN field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')";
?>

$result = db_query($query);

<?php foreach ($result as $row) : ?>

    <div class="featuredArticle">
        <?php print $row->field_mypdf_value; ?>
        <?php print $row->field_mypdf_fid; ?>
    </div>

<?php endforeach; ?>

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

Reference Link: EntityFieldQuery vs Db_select() -

@Bart says: -

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

@Berdir comment:-

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


Drag ad drop images to make a customised gallery So I have a content type "Albums" which has a field "image". This allows a user to upload several pictures into this album.

What I have done next is made a view that displays all the different albums. So you see a thumbnail for each album.

Once you click on an album you are taken to the contents of that album. The content is basically a list of image fields with some other stuff like date published etc...

What I want to do now is being able to pick a picture from this album and drag it to like some sort of panel at the bottom and drop it there, then navigate around the website dragging and dropping different pictures from different albums.

Once you have finished with the selection there should be a button called "create" or something similar which will maybe call a script through some trigger which will zip the pictures and download them to your pc.

I have no idea how to do this. Help!

Thanks!

I'm using Drupal 6.

This is actually a nice idea but probably not so easy to implement.

jQuery UI could help you with the drag and drop features. http://jqueryui.com/demos/droppable/
Drupalgardens does some galerie configuration through drag n drop - so there you may be able to get some inspirations on this. Especially since you can export the site and then look how exacly they do it. http://drupalgardens.com


How can I restart the PHP environment installed with Drush for Windows? I have installed Drush for Windows, works great, but it installs its own version of PHP in a subdir of the install directory.  I've increased the memory limit and execution times in that ini but how can I restart that PHP environment (if in fact that is even the correct PHP environment).  Short of restarting my machine (which is fine) just wondering what would be the way to do this?

Drush works using CLI. It means it is not dependent on web server you are using. "Restarting environment" simply does not apply, Command Line Interface PHP is started each time you call drush, and stops when drush finishes it's job, that's all.


How to set Drupal Commerce shipping rules by the longest of the shortest dimensions of a product? How can I create shipping rules which will base the shipping charge on the length of the package? Specifically, I need two rules for shipping: 1) if the length is less than X, then charge Y; 2) else/if the length is greater than X charge Z. Finally, I only need longest of the shortest dimensions for the shipping price.

I have a use case where the shipping charge is determined by the length of the packaging, not weight, or number of units. The products are posters, which will be rolled along the shortest side, such that I cannot simply base the shipping on a specific physical dimension (e.g. the length) as the posters are sometimes horizontally oriented and for this reason the dimension which needs to be used for the shipping calculation should be the shortest, but shipping must be calculated on the longest of the short dimensions. I'm only just now diving into the shipping rules and I've looked at Commerce Physical and Physical Fields, but I'm not sure how to take the shortest of two dimensions of the products, and then base the shipping on the longest of these.

As always, any advice would be greatly appreciated.

The best way to do this will be to create a custom rules action that sets this the way you want it. Writing rules actions isn't very scary. It's mostly a wrapper around a PHP function. Then you can get the logic just right. You could:

Write an action that takes the order as a parameter, returns the dimension you want, and then calculate the shipping in Rules, or
write a function that applies a shipping line item directly to the order.

Option 1 is easier to write and would be my initial tack on the problem. Option 2 is a bit more holistic but requires that you look at the shipping modules to see how they properly add a shipping line item to the order.


Cron jobs stuck in drupal 6 I am maintaining a site on drupal 6. I have installed a birthday module which can send mails to users on their bday. But it doesnt do so. None of the other cron related tasks are done, though cron runs daily, and I do get a notification on mail . I tried to install a new module called ultimate cron (6.x-1.7), this could solve my problem earlier when I last installed it. But on re-installation this also doesnt work. None of the triggered rules that should be fired on cron run are fired.

On site config -> cron it lists all the processes, but they are in starting state. And on background process page , it shows first task with 0 progress n none other are being processed.
I have tried to install latest version of ultimate cron modules, but that gives some error saying "Unknown field: start stamp".
Please help me with this.

For the latest version of Ultimate Cron, you also need the latest versions of Background Process and Progress. The versions might not match, or the database schema may not have been updated properly. Try completely uninstalling Ultimate Cron, Background Process and Progress, and then re-install them.


How can we output unfiltered HTML in a CCK field This seems like the simplest thing but for some reason we just cannot get this to work.

We have create 4 additional CCK fields for our "product" content type.

We enter simple HTML in to these fields and want to display these, as is, unfiltered on the node output.

Whatever we do, it always outputs as plain text, stripped of all html. Weve seen numerous references to the "Text Processing" options within the field settings, but they dont appear for us.

Ive even gone in and changed the text_processing value within the database for the field, Ive tried manually setting the filter type within the text.module code, weve spent days on what seems to be a simple and fundamental task.

How can we achieve this?

OK after searching high and wide for a solution, I finally came across this article: http://drupal.org/node/1100430

Basically the CCK component module "Text or Node Reference" causes an issues that hides the "Text Processing" options, disabling this module allowed us to change the input filter format!


How cron.php works for watchdog? I want to truncate the table 'watchdog' once a day.

So I heave:

to set the maximum rows number from the 'Logging and Alerts' (of Site Configuration) to 1000
create a crontab on my system to run the root/cron.php once a day

But I can't understand how the process goes. The crontab calls the cron.php . What is the process next?

I see the file cron.php includes the bootstrap.inc. Why is that?

Where is the actual code with the mysql queries (truncate) inside?

I need to understand the process to make some changes to a site.

I have googled it enough and have not find any information.

cron.php initiates a call to function drupal_cron_run() (in common.inc) which will finally make all calls to all cron tasks.

/**
 * Executes a cron run when called
 * @return
 * Returns TRUE if ran successfully
 */
function drupal_cron_run() {
.
.
// Iterate through the modules calling their cron handlers (if any):
module_invoke_all('cron'); // This will call all cron functions defined in modules(enabled)
.
.
}

dblog_cron() will get invoked by module_invoke_all('cron') This is responsible for clearing old entries in your watchdog table. If this function does not suit your requirements you can use Ultimate Cron to disable it alone. This is a good admin tool to manage your cron jobs. Then you can write your own cron task in another module and enable it.

function dblog_cron() {
  // Cleanup the watchdog table
  $max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
  db_query('DELETE FROM {watchdog} WHERE wid <= %d', $max - variable_get('dblog_row_limit', 1000));
}

Note : This is wrt Drupal 6. in D7 module invoke is slightly different


How to override views-view-field.tpl.php in custom module? I am trying to override views-view-field.tpl.php in my custom module as suggested in override views-view-fields.tpl.php in custom module but looks like it's syntaxes are old.

My codes are like:

In mymodule.info

 ; $Id$

  name = My Module
  description = Create custom views template.
  package = Views
  dependencies[] = views
  core = 7.x

  files[] = mymodule.module
  files[] = includes/mymodule.views.inc

 ; Information added by drupal.org packaging script on 2011-07-21
  version = "7.x-4.1"
  core = "7.x"
  project = "mymodule"
  datestamp = "1311290520"

In mymodule.module

function mymodule_views_api() {
  return array(
   'api' => 3.0,
   'path' => drupal_get_path('module', 'mymodule') . '/includes',

   );
 }

function mymodule_theme($existing, $type, $theme, $path)
  {

   return array(
    'views_view_field__views__ticker' => array(
    'variables' => array('view' => NULL, 'options' => NULL,'row' =>NULL),
    'template' => 'views-view-field--views--ticker',
    'base hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'mymodule') . '/includes',

         ),
       );
    }

In /mymodule/includes/mymodule.views.inc

  function theme_views_view_field__views__ticker($vars) {

    $view = $vars['view'];
    $field = $vars['field'];
    $row = $vars['row'];

    return $vars['output'];
   }

  function template_preprocess_views_view_field__views__ticker(&$vars)
   {

    $vars['output'] = $vars['field']->advanced_render($vars['row']);
   }

My custom template file views-view-field--views--ticker.tpl.php in /mymodule/includes

 <?php print $output; ?>

Problem: it is not overriding views-view-field.tpl.php

I am using drupal version 7.41

You should add the template file on your module info file:

name = My Module
description = Create custom views template.
package = Views
dependencies[] = views
core = 7.x

files[] = mymodule.module
files[] = includes/mymodule.views.inc
files[] = includes/views-view-field--views--ticker.tpl.php

version = "7.x-4.1"
core = "7.x"
project = "mymodule"
datestamp = "1311290520"


Show access denied page to the user I need a function that checks a condition; for example, if $a == $b it should return the access denied page to the current user.

What function should I use?

I think you are looking for the function which returns the access denied page; that is  drupal_access_denied(). Just call this function inside your conditional statement.


How can I act on a taxonomy term in my twig template? I'm trying to use two taxonomy items to build a button on my template. The logic is:

If this node is exactly equal to taxonomyTermFromVocabularyA
Print a button on the page with a URL built out of taxonomyTermFromVocabularyB

I thought I was doing well when a simple test proved that my terms were available. In the template, I tested by adding:

{{ content.field_taxonomy_resource_type }}

{{ content.field_taxonomy_topic }}

And out came the expected values on the page:

  Topic Page

  Oral Health

However, once I tried to actually use the terms I captured it never worked. The first part of the logic, where the button will eventually be built, I wrote as:

{% if content.field_taxonomy_resource_type == "Topic Page" %}

 hello, it's working!

{% endif %}

produces no content at all. I expected to see my test paragraph sentence "hello, it's working!" appear on the page.

My best google-foo hasn't helped me at all and, alas, my soul is being crushed. I fear it's something completely obvious that I am just ignorant about.

Can anyone point me to the error of my ways? Why doesn't my twig if statement work?

@clive was absolutely right in the suggestion below that I was naming the array and not the particular item I needed when constructing my if statement. His correction to my code:

{% if node.field_taxonomy_resource_type.entity.label == "Topic Page" %}

is not working though, and the best I can tell is that the variable is unavailable to me. When I dump the variable using {{ dump(node.field_taxonomy_resource_type.entity) }}, I just get NULL.

Clive's answer worked as soon as I changed out node to paragraph. Thanks!

{% if paragraph.field_taxonomy_resource_type.entity.label == "Topic Page" %}

content.field_taxonomy_resource_type is a render array, which you're comparing against a string. Instead, you need to get access to the label, and extract the term name.

Try this instead (if in a node template):

{% if node.field_taxonomy_resource_type.entity.label == "Topic Page" %}

Or, as we know it's a paragraph template:

{% if paragraph.field_taxonomy_resource_type.entity.label == "Topic Page" %}


Features - Custom User Fields Not Available after Import I have two Drupal sites.

On Site1, I created 4 custom text fields for the User Profile. I created a Feature that included these fields. I didn't see an area where I could export the settings for Custom User fields, so I searched for their respective machine names and added them.

On site #2, I added the feature and the fields now appear to be imported.

Despite this, when going to Configuration > People > Account settings, going to "Add existing field" does not list the newly imported fields to that list. They also are not available as "Existing Fields" when modifying a Content Type.

On top of that, when attempting to create a field with the same machine name, it states that it is already taken.

It seems the Features has indeed imported the desired fields but they are for some reason inaccessible.

How can this be fixed?

Solution

You have to add the corresponding field instances in feature as well. The field instance name should be in this format:

[entity_type]-[bundle]-[field_name]

In your case, they should be:

user-user-field_first_name
user-user-field_last_name
user-user-field_title
user-user-field_email

Sub Question 1

  Despite this, when going to Configuration > People > Account settings, going to "Add existing field" does not list the newly imported fields to that list. They also are not available as "Existing Fields" when modifying a Content Type.

Answer

You cannot find existing fields because there is no field instance attached on the field base. Drupal won't be able to load those field base without field instance.

Sub Question 2

  On top of that, when attempting to create a field with the same machine name, it states that it is already taken.

Answer

The field base is stored in database and also the table is created. So Drupal will stop you from recreation.


Getting a list of nodes of a certain type sorted by number of votes I would like to get a list of nodes of a certain sorted by votes (voting api) in one of my modules. Is there an entityFieldQuery that could do this? If not, is there a sql query I could use that might accomplish this task?

You can use views module to list nodes sorted by votes..

You can see the query executed in views when you enable Show SQL Query in views settings (admin/structure/views/settings) in the view preview...


"Edit layout" form missing revision log message field When I edit the layout for a given node it is missing a log message field in the revision area. Is anybody else seeing this or am I alone? In trying to diagnose:

Where that particular revision log field would be defined to check if it's defined at all. If it's not then this is probably a core bug that should be addressed.
If it does exist, where this particular form is defined to make sure that the revision log field is actually being included in the form definition.

Any insights on the above? I'm using the lightning distribution, so it's possible that there's some sort of override going on there, but I figured I should be checking in core first just in case.

The overall goal here for bounty award is to have a functional revision log message field on the form.

I've added my initial patch to the issue - https://www.drupal.org/project/drupal/issues/3033516#comment-13136184

Adding this chunk to the init method of the OverridesEntityForm seems to do the trick, at least for nodes. We'll see what core maintainers come back with, but hopefully this can help you in the meantime.

  /**
   * {@inheritdoc}
   */
  protected function init(FormStateInterface $form_state) {
    parent::init($form_state);

    $form_display = EntityFormDisplay::collectRenderDisplay($this->entity, $this->getOperation(), FALSE);
    $form_display->setComponent(OverridesSectionStorage::FIELD_NAME, [
      'type' => 'layout_builder_widget',
      'weight' => -10,
      'settings' => [],
    ]);

    $section_storage = $this->getSectionStorage();
    $entity = $section_storage->getContextValue('entity');
    $entity_type = $entity->getEntityType();
    if ($entity_type->isRevisionable()) {
      $revision_log_message_form_item = $entity_type->getRevisionMetadataKey('revision_log_message');
      $log_field_definition = $entity->getFieldDefinition($revision_log_message_form_item);
      $log_field_revision_message_form_data = $log_field_definition->getDisplayOptions('form');
      $form_display->setComponent($revision_log_message_form_item, $log_field_revision_message_form_data);
    }

    $this->setFormDisplay($form_display, $form_state);
  }


Unable to jump to a specific spot (seek) when mp4 or mp3 is in private field I'm serving .mp4 videos and .mp3 audios using private download (field's upload destination: Private files), and they play OK on native html5 player, but seeking doesn't work, as in I can't jump to the middle of a video or audio.

This happens on Chrome and doesn't happen on Firefox. Also no problem playing and jumping on public download or when the file is saved on local drive and played from there.

After comparing the response headers in several different scenarios I have concluded that the only consistent difference between working and non-working is that Accept-Ranges and Last-Modified headers are missing when seeking is not working. These can be added at hook_file_download but then the media won't play at all.

This a pain to test with Chrome Developer Tools > Networking as Chrome pulls old headers from its memory, so you never know which input is producing which output.

Solution

Install https://www.drupal.org/project/resumable_download. Despite its name and the fact that it's at beta1 (it gives some notices) it does the job. It takes completely care of feeding the media to the browser.

Edit: If the module doesn't work, check out this patch: https://www.drupal.org/node/2362393

Problem

Chrome makes multiple HTTP request with Range header for media file and expects HTTP Content-Range and Content-Length response header with 206 Partial Content status (read this). If server send '200 OK' status Chrome will not play the media file, but Firefox will.
If server send '200 OK' status with response header 'Accept-Ranges: none' then Chrome will play media file, but jumping will not work.
I assume you have implemented hook_file_download() already. That hook should return array of appropriate HTTP headers. It's enough to return Accept-Ranges header (only if your module should handle the media file and current user has permission):

return array(
  'Accept-Ranges' => 'bytes',
);

Solution - Drupal 7

Accept-Ranges response header with value 'bytes' is a signal to client that server supports Range request. If you don't want to support Range request you should use 'none' instead of 'bytes'. There is no server support for Range request for private files. Therefore you should install Resumable Download module which will setup other HTTP response headers like: Content-Range, Content-Length and ETag, and set HTTP status 206 Partial Content. Drupal core module File will setup other HTTP response header like Content-Type.


Display block content in current language I have multilingual Drupal 8 site.

I want to display views block in home page.

It should display block contents in current site language.

Example:

I have content type called "Book". Which has translated content in EN & NL.
Created views block for "Book" content type.
Placed this block in Home page.
Enabled language switcher block in Home page.

When I visit my home page mysite.com & mysite.com/nl above views block shows always English contents.

When I visit site in NL language, I want to display this block in NL language.

Added language condition in Filter Criteria to fix it.


Zendesk Webform hook_alter Im trying to alter the module "zendek_forms"

It states:
There are four fields in the form (name, e-mail, subject, and description), but
more fields can be added in hook_form_alter and the submit handler will
recognize fields prefixed with "zendesk_" and pack them in the API call to
Zendesk.

I am absolutely clueless on how to do this, even where to begin.  Any help would be greatly appreciated.

hook_form_alter is a drupal API function. You can google "hook_form_alter" and the 1st result will be the API documentation for this function; it includes examples.

Using this "hook" function you can inject, or otherwise change, any form in your drupal website. A "form" is an HTML construct that can send data to a webserver via either POST or GET.

So, you can create a custom drupal Module (which consist of in this case an .info file and a .module file). In your  module you can create a function that implements "hook_form_alter" and adds in the zendesk field.

A simple simple example of this would be:

# in the below examples lets assume you have named your module folder as "zext" (kinda short for zendesk extensions .... i dunno :P

# in zext.info
name = Custom Zendesk Form Extensions
descrption = We want to add custom fields to the zendesk form.
package = Other
core = 7.x

# in zext.module
<?php

/**
 * Implements hook_form_alter().
 *
 * Alter the zendesk form and add a custom color text field.
 */
function zext_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'zendesk_form') {
    $form['zendesk_favorite_color'] = array(
      '#type' => 'textfield',
      '#title' => t('Favorite Color'),
      '#description' => t('Please tell us what your favorite color is!'),
      '#weight' => 99,
    );
  }
}

# that is all the code that would be in the 2 files.

With the above 2 small pieces of code we have modified the default zendesk_form (I assume its $form_id is zendesk_form ... it may be different examine the module's code to see how it IDs the forms ...) and added 1 single new custom field to allow the visitor to submit their favorite color. Drupal doesn't store these values anywhere -- they are just passed onto Zendesk upon form submission; You simply need to create the folder + 2 files and install the module in the drupal administration. Your module folder should be called zext.

There is alot of documentation online for creating modules, and using hook_form_alter. Look on drupal.org and Google.

Happy Coding!