Which is the equivalent of php drupal format_interval for javascript? I want to use with JavaScript and Drupal.t() the equivalent of format_interval().

With PHP I would use the following code.

print t("!date ago", array("!date" => format_interval(time() - $lastActivity, 1)));

What would the equivalent in JavaScript be?

Drupal doesn't implement a JS version of format_interval(); this is a rough (minimally tested) port:

Drupal.formatInterval = function(interval, granularity, langcode) {
  granularity = typeof granularity !== 'undefined' ? granularity : 2;
  langcode = typeof langcode !== 'undefined' ? langcode : null;

  var units = {
    '1 year|@count years': 31536000,
    '1 month|@count months': 2592000,
    '1 week|@count weeks': 604800,
    '1 day|@count days': 86400,
    '1 hour|@count hours': 3600,
    '1 min|@count min': 60,
    '1 sec|@count sec': 1
  },
  output = '';

  for (var key in units) {
    var keys = key.split('|');
    var value = units[key];
    if (interval >= value) {
      output += (output.length ? ' ' : '') + Drupal.formatPlural(Math.floor(interval / value), keys[0], keys[1], {}, { langcode: langcode });
      interval %= value;
      granularity--;
    }

    if (granularity == 0) {
      break;
    }
  }

  return output.length ? output : Drupal.t('0 sec', {}, { langcode: langcode });
}

Some random results using the above (they seem to match up to the PHP function as expected):

3643       => 1 hour 43 sec
92900      => 1 day 1 hour
2592000    => 1 month
9331200    => 3 months 2 weeks
297605232  => 9 years 5 months


Renaming a content type during migration I am migrating a Drupal 6 site to Drupal 8. On the Drupal 6 site I have a content type called book_page but would like it be called faq on the new site.

I set the default_bundle to faq in my yml file but it still migrates as book_page.

Here is my yml file:

uuid: a67dbd6f-416c-44c0-9698-05ec3bb3c5a9
langcode: en
status: true
dependencies: {  }
id: upgrade_d6_node_book_page
migration_tags:
  - 'Drupal 6'
migration_group: d6_migrate_group
label: 'Nodes (book_page)'
source:
  plugin: d6_node
  node_type: book_page
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration
    migration: upgrade_d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_image:
    plugin: d6_cck_file
    source: field_image
  field_upload_files:
    plugin: d6_cck_file
    source: field_upload_files
destination:
  plugin: 'entity:node'
  default_bundle: faq
migration_dependencies:
  required:
    - upgrade_d6_user
    - upgrade_d6_node_type
    - upgrade_d6_node_settings
    - upgrade_d6_filter_format
  optional:
    - upgrade_d6_field_instance_widget_settings
    - upgrade_d6_field_formatter_settings
    - upgrade_d6_upload_field_instance

Anyone have an idea what I am doing wrong?

Update:

I have also tried adding the following under process under each of my node yml files?:

type:
  plugin: default_value
  value: faq

I wonder if the All node types are created in ....node_type.yml?

As you've figured out, modifying the d6_node-based migration affects how the content of a given node type is migrated, but does not affect how the actual node type itself is migrated - that is done in d6_node_type. To rename the types themselves in migration, while you could modify the source query as you did, it's simpler to modify the .yml to remap values.
In upgrade_d6_node_type.yml,  you can replace

process:
  type: type
  name: name

with

process:
  type:
    plugin: static_map
    bypass: true
    source: type
    map:
      story: post
      book_page: faq
  name:
    plugin: static_map
    bypass: true
    source: name
    map:
      story: post
      'Book Page': Faq


Pagination for image field in one node page I made a custom node type with following fields:

Title
Body
Image (Unlimited)

I need to have a few pages from this content type and on each page I need to print the title field, the body and all images, but I need a pagination for the image field - lets say 9 images per page. (pagination only for one field in current node).

Is that possible without using Views, and using theming? For example, making a custom "field--field-images.tpl.php" template file, but instead of using the following code, printing the field with Pagination.

foreach ($items as $delta => $item):
  print render($item);
endforeach;

You can use the CCK Pager project.

  CCK Pager allows to page the item list of any CCK field with multiple values.

  The module extends others CCK formatter by paging the field item list; setting the number of elements per page and pager type (full or mini) can be made per field.
  It only works with versions of CCK >= 6.x-2.5.

Look at this demonstration, and if you are using Drupal 7, follow the status of these issues.


Access denied for user anonymous while accessing custom table data I am trying to fetch custom table result anonymously with services but I am getting

<?xml version="1.0" encoding="utf-8"?>

Access denied for user anonymous

My Code are as follow :

    function custom_data_services_resources() {
  return array(
    'getdata' => array(
      'retrieve' => array(
        'help' => 'Retrieves a data',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'id',
            'type' => 'int',
            'description' => 'The id of the note to get',
            'source' => array('path' => '0'),
            'optional' => FALSE,
          ),
        ),
      ),
      'index' => array(
        'help' => 'Retrieves a listing of notes',
        'file' => array('file' => 'inc', 'module' => 'custom_data'),
        'callback' => '_get_data',
        'access callback' => TRUE,
        'args' => array(
          array(
            'name' => 'page',
            'type' => 'int',
            'description' => '',
            'source' => array(
              'param' => 'page',
            ),
            'optional' => TRUE,
            'default value' => 0,
          ),
          array(
            'name' => 'parameters',
            'type' => 'array',
            'description' => '',
            'source' => 'param',
            'optional' => TRUE,
            'default value' => array(),
          ),
        ),
      ),
    ),
  );
}

I tried with "X-CSRF-Token" also But no luck :(

Any help appreciated

Following up with an answer from our comments...

Here's an example custom service resource:

custom_data.module

function custom_data_services_resources() {
  $resources = array(
    'custom_data_resources' => array(
      'actions' => array(
        'getdata' => array(
          'help' => t('Gets custom data.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'callback' => 'custom_data_getdata',
          'args' => array(
            array(
              'name' => 'data',
              'type' => 'array',
              'description' => 'The data dude.',
              'source' => 'data',
              'optional' => FALSE,
            )
          ),
          'access callback' => 'custom_data_access',
          'access callback file' => array(
            'type' => 'inc',
            'module' => 'custom_data',
            'name' => 'custom_data.resource',
          ),
          'access arguments' => array('access user profiles'),
          'access arguments append' => TRUE,
        ),
      ),
    ),
  );
  return $resources;
}

custom_data.resource.inc

function custom_data_getdata($data) {
  return array('foo' => $data['bar']);
}

function custom_data_access($permission) {
  return user_access($permission);
}

After that, just enable the custom resource under your endpoint's configuration and clear all of Drupal's caches. Then you can make a POST to:

?q=[my-endpoint]/custom_data_resources/getdata.json

If you need to send along custom arguments, I usually recommend a single array parameter, that way you can easily expand upon it and send as many variables/properties you need along with the payload:

{ "bar": 123 }

Which will then return to you:

{ "foo": 123 }

Don't forget to attach a header to your request with a name of X-CSRF-Token and value retrieved from: ?q=services/session/token


I want to know the module through which any user can add his own tags for the content on the pages I want to know the module from D7 which i can use to add tags for the any content.
Suppose i have one page Guide for beginners
then on this page there is word "Guide"
So at the bottom of the page there should be Add tag option in which i can add the tag for the word "Guide".
once i tagged it should display at the bottom in my tags.
So this facility should be for any user.
Please let me know the module if any available or the method for implementing this.

Thanks in advance.

Looks like you need to know how to use the Taxonomy module, which comes with Drupal core.

Good place to start would be its documentation.


How can I change theme? I tried drush disable theme-name and afterwards drush enable theme-name, but it didn't work.

How do you change theme with Drush?

For Drush 9.5.2 and Drupal 8.6.5 I use the following:

drush theme:uninstall THEME_MACHINE_NAME
drush theme:enable THEME_MACHINE_NAME
drush config-set system.theme default THEME_MACHINE_NAME


How do I retrieve an entity from an entity reference I have a custom module with three entities. The first represents a chemical compound. The second is a list of the periodic table of elements. The third is a many-to-many binding between these two, and also contains a "quantity" field. This last entity is to be able to create each chemical's chemical formula.

Example-combining the quantities and element symbols to produce CH4O

Entity:chemicals
id   name
1    Methanol

Entity:elements
id    symbol   name
1      H       Hydrogen
2      C       Carbon
3      O       Oxygen

Entity:chemical_formulas
id     element    chemical   quantity
1        2          1           1
2        1          1           4
3        3          1           1

I have the three entities working to the point that I can get all the correct data in the database. However, retrieving has proven a challenge.

My ChemicalFormulas class contains this function, and this seems to be where the problem is because it always returns 'null'. The ChemicalFormulas->getQuantity() function is basically the same, and it works fine.

//in the ChemicalFormulas class
public function getElement() {
   return $this->get('element')->value;
}

The field is defined as

$fields['element'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Element'))
  ->setDescription(t('The Element.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'elements')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'string',
    'weight' => 0,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I am trying to produce the formula with this function

public function getFormula(){
  $query = \Drupal::entityQuery('chemical_formulas')
    ->condition('chemical', $this->id());

  $ids = $query->execute();
  $entries = entity_load_multiple('chemical_formulas', $ids);
  $formula = "";
  foreach ($entries as $entry){
    //Is element supposed to be an entity or the id of an entity?
    //$element = $entry->getElement(); //If it's an entity
    $element = entity_load('elements', $entry->getElement()); //If it's an integer.
    $symbol = $element->getSymbol();
    $quantity = $entry->getQuantity();
    if ($quantity == 1) {
      $quantity = "";
    }
    $formula .= $symbol . $quantity;
  }
  return $formula;
}

Entities part:

I think (as much you showed) your entity definition is wrong:

Entity names should be always SINGULAR: Chemical, Element, Chemical Formula
Your Chemical Formula should have the ability to hold reference to MULTIPLE elements (H20 for example, has H and O elements). Which means you won't able to store this information in this entity table, but you will have to create an external table to hold this information. You can find example for this in core entities (like taxonomy_terms, if I remember good).
If you make this changes right, you won't have query anything, since the referenced entity ids (elements, chemical) will be present in your entity.
You only have to load via EntityTypeManager.

Final hint again: always examine core / contrib entities. Node, Taxonomy terms are pretty good examples.


How to change textformat of many nodes at once? How to change textformat of many nodes at once,

module? drush? or script

UPDATE (sorry I was on the run at first edit)

I had imported hundred or more nodes I had to migrate from an old site. Did it via node_export. The new site has a textformat with same name, but defined another way so I decided all nodes should be plain text .

I websearched a bit but could not found anything. So i thought there might by a module with VBO support for that?

In previous instances where this has happened to me, I've just updated the *_format column in the field_revision_* & field_data_* tables, flushed the Drupal cache, and things worked without issue.

For example, if you're looking to change the nodes' body format for all imported nodes of type my_type from my_format to plain_text, you could execute this query:

UPDATE field_data_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';
UPDATE field_revision_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';

NOTE: There's probably a better, programmatic way, than touching the database directly, but I've never seen any adverse effects from this method.


Database in settings.php doesn't exist yet site is live. Where is the data? I've inherited a Drupal 6 site running on an Ubuntu 10.04.4 LTS server. I'm trying to understand the configuration of it to create a local version of it work on.

I can't figure out how the data is being accessed. The settings file shows the following:

$db_url = 'mysql://root@localhost/drupal';
$db_prefix = 'dru_';

However when I list the databases, I can't find it:

mysql -u root
mysql> show databases \g
+--------------------+
| Database           |
+--------------------+
| information_schema |
| gitpull            |
| mysql              |
+--------------------+
3 rows in set (0.01 sec)

In addition running drush status says it can't find it either.

$ drush status
SQLSTATE[42000] [1049] Unknown database 'drupal'                   [warning]

The site is up and running so it's got to have access to the database somehow.

I figure I'm in the right directory because it's defined in /etc/apache2/sites-available and /etc/apache2/sites-enabled/

Any help would be greatly appreciated.

The hints from Tony Mao & Alexei pointed me in the right direction. It turned out there were a bunch of backups in non-intuitively named folders, so I was looking in the wrong place.

I ended up finding the right settings.php file with sudo find . -name settings.php.


Send personalized email to a particular role I want to send a PERSONALIZED email to all users of a particular role on my site starting with for example: Hello [first_name] [surname],

I have tried using the Rules module but was not successful.

Please is there a way to use Rules module to achieve this or is there another way?

Thanks in anticipation.

Try using the views_send module instead. This powerful module acts like views_bulk_operations in that it lets you create a view to execute an action using Drupal's batch API for processing. For your case (roughly following the directions on the project page):

Create a view of users and add the user email field to the list
Add the field 'Global: Send e-mail' to activate the Views Send functionality
Add any other fields that you want to include in your customized email as fields in the view (ex. User: First Name, User: Last Name)
Finally, add a filter to filter by the particular role(s) you want to filter on.
You probably also want to secure the views permissions so non-authorized users can't use the view to send to your users.

If that's all setup then when you visit your page, you will see a list of all users in that role with the option to send an email to them. When you select your users and are ready to send your email, you will then see on the next page the option to use any of the fields you've selected above as tokens in your email (thus the customizable option):


How do I redirect to the login page? I have a custom search form which appears in the modal and is accessible only to logged in users.
The ajax url of the form is /my/custom/search/modal/{nojs}.
The router definition is the following one.
mymodule.my_custom_search_form:
  path: '/my/custom/search/modal/{nojs}'
  defaults:
    _form:  '\Drupal\mymodule\Form\MyCustomSearchForm'
    _title: 'My Custom search'
    nojs: ajax
  requirements:
    _user_is_logged_in: 'TRUE'

How do I redirect users to the login page when the anonymous user tries to access /my/custom/search/modal/{nojs} via an AJAX call?

There are a couple of modules that do this

Redirect 403 to Login: https://www.drupal.org/project/r4032login
Anonymous Login: https://www.drupal.org/project/anonymous_login
You could probably also do it with the Rules module
Simplest: You can also go to admin/config/system/site-information and set the "Default 403 (access denied) page" to "/user/login"

This page was old, but looked like it had been updated along the way for Drupal 8.


List parent terms by vocabulary I want to list only parent terms in order to rearrange the orders like /admin/structure/taxonomy/vocabulary_name. Given url have displayed all terms included child terms. I want to avoid term terms. So i've tried to create custom page.
I've tried below code but i can't make it work.

function test_menu() {
  $items['manage_category/%taxonomy_vocabulary_machine_name'] = array(
   'title' => t('Manage category'),
   'page callback' => 'arep_manage_category',
   'page arguments' => array(1),
   'access arguments' => array('administer taxonomy'),
   'type' => MENU_CALLBACK,
 );
 return $items;
}

function arep_manage_category() {
  $category = arg(1);
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $taxonomy = taxonomy_vocabulary_machine_name_load($category);
  $form = drupal_get_form('taxonomy_overview_terms', 'taxonomy_term', $taxonomy);
  return drupal_render($form);
}

I've tried to access this page by vocabulary name. How ot make it work? Is any other idea?

Firstly you add a cck field named flag for levels to your vocabulary when created, then after that when you import or add terms in this then fill flag value like "My First Level"/"My Second Level". then you can fetch very easily like that..`

/* Get All States From Taxonomies */
  function get_taxonomy_by_flag($flag) {
       $VocabName = "Master Data";
          $myStateArray = array(0=>'-- Select --');
        $Vocabluary = get_vocabulary_by_name($VocabName);
         $query = new EntityFieldQuery();
          $entities = $query->entityCondition('entity_type', 'taxonomy_term')
->propertyCondition('vid', $Vocabluary->vid)
->fieldCondition('field_flag', 'value', $flag, '=')
->execute();
if(sizeof($entities)>0)
{
  foreach($entities['taxonomy_term'] as $tid) {

    $term = taxonomy_term_load($tid->tid);
    $name=$term->name;
    $myStateArray[$term->field_code['und']['0']['value']] = $name;
  }
  return $myStateArray;
}
else
{
    return 0;
 }
}

    function get_vocabulary_by_name($vocabulary_name) {
        $vocabs = taxonomy_get_vocabularies(NULL);
         foreach ($vocabs as $vocab_object) {
          if ($vocab_object->name == $vocabulary_name) {
            return $vocab_object;
         }
      }
            return NULL;
      }
     call this function by flag name and you can easily get all parents. because i have used this for **State/District/Block/Village** purpose.
      get_taxonomy_by_flag('STATE');

hope this helps you lot...


Alter form after submit I'm creating module to use similiar words to get better search result. I have API which will returns top X similiar words for entered word. What I want to achieve is this workflow:

User enter some word into the search form and submit the form
My module call the API, gets the similiar words and change the search query

--- That is what I have done. But next part is problem ---

After sucesful search, alter the form to show user the similiar words I used to change the query.

At the start I expected, that I can save similiar words in hook_search_api_solr_query_alter and then in hook_form_alter change the form to show the words. But after some research I find out that is not possible, because hooks are called in different order.

Is there any way how I can alter form after submit (or validation)?

I also tried to set form_state['rebuild'] in validation hook, but when the form is rebuild, the entered values are erased.

hook_form_alter is probably a good approach for displaying the search words in the form.

Assuming you're not submitting the form via AJAX, you need a way of passing the search words to the next page load. One way might be to redirect to the same URL but adding your search words as URL query parameters. You could do that by setting $form_state['redirect'] or calling drupal_goto in your submit function.

Another way, maybe easier, would be to save your search words in the user's session and reading them back in the subsequent page.


How to check if (unmanaged) file exists? I can't find a Drupal API function in D7 that tells me if an (unmanaged) file exists.
D6 had a file_check_location but not for 7.

How to check if (unmanaged) file exists?

You could just use the old bog standard PHP function file_exists() if I understand you right:

$uri = 'public://images/an-image.jpg';
if (file_exists($uri)) {
  // Do something
}

This also works for normal (absolute) paths as well, e.g.:

$path = '/var/www/drupal/sites/default/files/images/an-image.jpg';
if (file_exists($path)) {
  // Do something
}


How do I remove the text "webform content" at the top of a block? I have several Drupal 8 webforms, some of which are embedded as blocks. At the top of each webform, I'm getting the "webform content" text.

How do I safely remove that text?

It looks like you are including the field label in the display. If you created the block using a custom block type do the following:

Go to Admin->Structure->Block Layout->Types
Then select your WebForm block type
There will be a tab labeled "Manage Display"
On this page, mark the field label as hidden.

Not sure what to do if you are using the built in Webform blocks


Sometimes shipping and/or billing address is missing Unfortunately I have to ask a pretty vague question, and I can't provide much background because I can't reproduce.

Working on a Drupal 7 Commerce install with Domain Access we are (seemingly) randomly missing shipping and/or billing information on orders.  Sometimes the order has a billing name (or shipping name) but no address information.  Others, either shipping or billing is completely missing from the order view.

This is happening on ~1% of orders and I can't find any way to link them with consistency.  It has happened on PayPal Express Checkout orders, Authorize.net orders, orders with different shipping methods, orders from different domains, etc.  The stored API responses from the payment processors are normal.

In testing (on production), I can't reproduce; I've tried both payment methods, anonymous accounts, existing accounts, etc.  I can't even get past the Billing/Shipping form without completing all the information, no matter what I've tried.

Hopefully someone has experienced this before; if not, I'm totally open for "try this" or "look here" suggestions.

Thanks

I've had similar problems before, never did get to the bottom of it. I think it's related to the Commerce Addressbook module and the way it copies profiles but time ran out before I could confirm.

As a rather hacky (but effective) workaround I used the following to make sure the profile had been copied:

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) {
  $form['buttons']['continue']['#submit'][] = 'MYMODULE_commerce_checkout_form_submit';
}

function MYMODULE_commerce_checkout_form_submit($form, &$form_state) {
  // If the copy address checkbox is selected.
  if ($form_state['values']['customer_profile_shipping']['commerce_customer_profile_copy']) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $form_state['order']);
    $shipping_address = $order_wrapper->commerce_customer_shipping->commerce_customer_address->raw();
    $billing_address = $order_wrapper->commerce_customer_billing->commerce_customer_address->raw();

    // If the shipping and billing address aren't the same then we need to fix it.
    if ($shipping_address != $billing_address) {
      $order_wrapper->commerce_customer_shipping->commerce_customer_address = $billing_address;
      $order_wrapper->commerce_customer_shipping->save();
    }
  }
}

It may or may not work as-is, but even if not it might provide a starting point for debugging.


How do I programmatically get the field type of a specific field? I'm able to get a list of the field types with the following code.

$defs = \Drupal::service('plugin.manager.field.field_type')->getDefinitions();

I want to get the field type of a specific field. How do I get it?

For example, I'd like to check if the field type of field_image is _image. Is there code similar to the following one?

$fieldType = \Drupal::service('plugin.manager.field.field_type')->getDefinition('field_image');

With "get the field type of a specific field" you probably mean a specific field of an entity. There can be fields with the same name that have different types in different entities.

For example the field type of a field in a node:

$field_type = $node->get($field_name)->getFieldDefinition()->getType();

can be different than that of the same field in a comment:

$field_type = $comment->get($field_name)->getFieldDefinition()->getType();


How do I implement hook_views_post_execute I am attempting to modify the output of view programmatically using hook_views_post_execute.

I created the usual module structure (in this case using drupal generate:module.

I am able to use other hooks (such as hook_entity_view)successfully.

However, hook_views_post_execute causes blows up the website with the message

  The website encountered an unexpected error. Please try again later.

The code block is right out of api.drupal.org.

/**
 * @param ViewExecutable $view
 */
function idm_views_post_execute(ViewExecutable $view) {

  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  $temp = $view;

  if ($view->total_rows > 100) {
    \Drupal::messenger()
      ->addStatus(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}

My guess is you did not include the use statement at the top of your file that tells the application how to locate the class ViewExecutable. This is a PHP construct and not Drupal specific, which is why it is not always mentioned explicitly in the documentation.

At the top of your file, add:

use Drupal\views\ViewExecutable;

The incoming argument to the hook is of type ViewExecutable, but PHP does not know how to find that class, so it errors out unless you either use the use statement, or change the function signature to:

function idm_views_post_execute(Drupal\views\ViewExecutable $view)

Clear cache and reload. If the error persists, you'll need to provide log(s) to indicate what the actual error that occurred was.

If you copied and pasted the code here for hook_entity_view that would explain why that worked for you:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_view/8.6.x

The example here has the full path in the argument list.

hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)


db_query() not compatible with IN operator? I ran into a snag setting placeholders for the IN operator, and then I ran into a webpage that basically says, if I'm reading it correctly, that they are not compatible. I also found a forum post on this subject in which the questioner gave up and expanded his IN into a series of ORs.

Apparently, I have the choice of either expanding the IN into ORs or learning to do dynamic queries. Since db_select() apparently comes with a lot of overhead, I suppose the ORs will run faster.

Is this correct, or is there a way to use IN with db_query?

You can use placeholders in IN conditions, but you need to set them up correctly first.  Using the example in your first link, this should work:

$replacement_values = array();
foreach(array_values($your_values) as $i => $val) {
  $replacement_values['@val' . $i] = $val;
}
// Should look something like:
// $replacement_values = array(
//   '@val1' => 'your first value',
//   '@val2' => 'your second value',
// );

$placeholders = array_keys($replacement_values);
$placeholders = implode(', ', $placeholders);
// Should look something like:
// $placeholders = '@val1, @val2';

$res = db_query('SELECT field FROM {table} WHERE cond_field in(' . $placeholders . ')', $replacement_values);

n.b. I haven't tested this so it might need some tweaking.

That said, I'd urge you to look into dynamic queries.  They're not that hard to get your head around and if you wan't to right modules that might ever be used on another Drupal site that uses an alternative database to MySQL then they are a must.


Webform api - using the included hooks to change email destination? I am looking to have a webform posted to specific destination depending on submitted values.

I thought this could be done through the webform api, webform.api.php line 209 has this hook defined:

/**
 * Alter the display of a Webform submission.
 *
 * This function applies to both e-mails sent by Webform and normal display of
 * submissions when viewing through the adminsitrative interface.
 *
 * @param $renderable
 *   The Webform submission in a renderable array, similar to FormAPI's
 *   structure. This variable must be passed in by-reference. Important
 *   properties of this array include #node, #submission, #email, and #format,
 *   which can be used to find the context of the submission that is being
 *   rendered.
 */
function hook_webform_submission_render_alter(&$renderable) {
  // Remove page breaks from sent e-mails.
  if (isset($renderable['#email'])) {
    foreach (element_children($renderable) as $key) {
      if ($renderable[$key]['#component']['type'] == 'pagebreak') {
        unset($renderable[$key]);
      }
    }
  }
}

So I set out to use it with the following ina custom module:

// Implements hook_webform_submission_render_alter
function formHelper_webform_submission_render_alter(&$renderable) {
  // Just a dump to confirm hook was invoked...
  kpr($renderable);
  dpm($renderable);
}

However, it seems the hook is not being called. Am I missing something in here to use webform api? Is this even a regular hook? it seems I could get away with just calling the api's function but I would like to be sure of the Drupal way to go.

Was not sure wether to delete original question or not, but decided on leaving it here since it is listed by google when searching for webform api help.

Turns out the code above does execute the hook. I went for lunch, came back, retried and suddenly the hook is invoked as expected.

To anyone needing to change form values or email info on submission of a webform, this hook is the real deal.

Cheers!


How to resolve message ' Requires: Commerce_checkout (missing)'? I have installed the Commerce Checkout Pages module (as the tar.gz file), as shown in this image:

Note the message shown within its description, i.e:

Requires: Commerce_checkout (missing)

Now I want to enable it, but I don't know how I resolve the missing part of the module.

Any help?

You need to install the Commerce module.

Commerce Checkout is a submodule thereof.


Login form on restricted page doesn't accept login credentials I took over a d7 page from another dev to whom I currently don't have contact. Now I'm digging through the different configurations and settings etc. trying to fix various minor issues. One of the issues is a strange behavior that prevents users from logging in in case they access a restricted node. In detail:

The website I'm working on has a restricted area "intranet" which is only accessible for logged in users. Users that are not logged in trying to access the "intranet pages" see only the login form with the message "You have to be logged in to access this page". So far so good.

But when I (not logged in) then actually enter the correct login credentials on  the form that appears on those restricted nodes, I'm just getting the error message "You have to be logged in…" again, together with the login form. Logging in through the regular login page "/login" works perfectly fine.

I hope somebody knows a way around this problem? Any pointers appreciated…

A possible explanation for what is happening is that this is implemented via some custom rule, created with the Rules module (at least that's how it "could" have been implemented with a rather basic custom rule).

So if you have the Rules module enabled in your site, you may want to do some Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".


Printable Templates for Views using Print Module Any views related report can be printed using the Print module when enabled. This can be achieved by simply using /print/views-url. It uses the standard print.tpl.php.

I do not want the print version of views output to display the exposed filter. At the same time, I would not want to modify the default print.tpl.php.

Is there a way to use alternative print templates for views in the same line as for content types: print[--html|--mail|--pdf][--node--node-type].tpl.php

Thanks.

I faced a similar issue quite a while back and below is how I solved it:

Create another display of the same view (clone page)
Choose 'Remember last selection' in the Views exposed filters' settings in the original page view
In the cloned page view, set 'Expose form in a block' to 'Yes'
Use the regular 'print/view-url' wherever you want but remember that 'view-url' in this case is the path of the cloned page view.

Hope this helps,

Regards,
Supriya Rajgopal


Multiple Date field with term attached to each instance I have a need to build a "Project" content type that has a multiple date field. This date field will be used to mark particular "Milestones" within a project. I am attempting to attache a small text field or term to each instance of the multiple date field so I can plot each date on a calendar with description.

Is there a combination of modules I can achieve this with? I was reading about Field API but was hoping there was an alternative way.

Any help is much appreciated.

I can confirm that Field Collection is the answer with a little themeing of the node edit page -thanks for your help.


D8 Install/uninstall custom module - 'field_storage_config' entity with ID already exists I created a custom module which essentially is a replica of the Article CT .yml files which come with the D8 standard install-profile.

When I installed the custom module, it successfully created everything i expected it too. I then disabled it, then re-enabled and the module will not re-install giving the following error:

  Drupal\Core\Entity\EntityStorageException: 'field_storage_config'
  entity with ID 'node.custom_field' already exists.

I originally solved this issue by declaring the module as a Enforced dependency on the node.type.yml

langcode: en
status: true
dependencies:
   module:
    - menu_ui
   enforced:
     module:
       - custom_module

This worked for the body field and allowed me to enable/disable the module without getting the duplicate ID error. but as soon as i added the image field the ID is a duplicate and I cannot re-enable the module. The id is unique, and module will enable if i change the ID prior to enabling, but thats unacceptable.

  EDIT: appears after removing the image field from the CT, the body
  field now is now being affected by the same error. So enforcing the
  module doesnt work.

I would assume this is because it is inside of the config/install folder, but there are no examples on custom modules that install content types when installed. at least I cannot find any at the moment.

My question would be: What is the proper way to add content types when enabling a custom module?

how to avoid the duplicate ID error when installing content types when disabling/enabling the custom module?

Try putting the files in the config/optional directory either at first install or after uninstalling (because they will already exist). They should get installed even on first install if all dependencies are met. From the docs:

    For example, in the scenario that module A has optional configuration which requires module B, but module A is installed first and module B some time later, then module A's config/optional directory will be scanned at that time for newly met dependencies, and the configuration will be installed then. If module B is never installed, the optional configuration item will not be installed either.

https://www.drupal.org/docs/8/api/configuration-api/configuration-storage-in-drupal-8


Insert form values in the database I am new to Drupal 7, and I am trying to insert the form values in a database table. I used many ways to do that, but I am not getting successful result. What is wrong with the code I am using?

drupal_write_record('formtest', $data);
function form_test_form_submit($form, &$form_state) {
  $id = db_insert('formtest')
    ->fields(array(
      'First name' => $form_state['values']['firstname'],
      'Lastname' => $form_state['values']['lastname'],
      'Email' => $form_state['values']['email'],
      'Password' => $form_state['values']['password'],
      'Year of birth' => $form_state['values']['birthdata'],
      'Image' => $form_state['values']['fileimage'],
  ))
  ->execute();
  drupal_set_message(t('your messagees is added is sucessfule'));
}

Is your submit function getting called to begin with?  Just put a dsm in the beginning of your submit function and make sure it is being called.  If it is, then, dsm your form_state['values'].  If you can see all the values in form_state, then, make sure your table name and column names are spelled exactly the same as they are case-sensitive.


What is the system log and where is it? at admin/config/workflow/rules/settings one can configure settings for logging related to rules and it states that: "Evaluations errors are logged to the system log".  What and where exactly is the 'system log'?

By default the logs are saved at /admin/reports/dblog for which the dblog module in the core is responsible. More about dblog : https://www.drupal.org/docs/8/core/modules/dblog/overview

You can also have the logs stored on the file system by enabling the syslog module (also in core). More about syslog : https://www.drupal.org/docs/8/core/modules/syslog/overview

It is recommended that you should not use the dblog module if you need to log messages more frequently as it does a write operation to the database.


How to automatically populate a field with a value part of another field I will try to be as specific as possible.

I have a required text plain field in a content type, say 'field_A'.  This will have values of minimum 2 words, maximum 5 words. Words will be separated by spaces.  I can be certain of this.

What I want, is to have another field, say 'field_B' in which I want to keep the last word of field_A.  I would like this to happen automatically (upon creation of a node of this type).

I have no idea if this is possible ...

So, say I 'm adding new content of this type, and use value "lorem ipsum whatever" for field_A, upon submitting I would like the word 'whatever' to be inserted as a value in field_B.

I 'd be grateful of any help ..  I couldn't find relevant info on this, it's kinda hard to describe in a few words.

Working on D8.

You probably need a custom module for this.

Add  MODULENAME directory inside your modules directory.  Inside the directroy create file MODULENAME.info.yml with contents:

name: Last word copy
description: 'gets last word from field_a and saves it to field_b'
core: 8.x
type: module
package: COMPANYNAME
dependencies:
  - node

This module implements hook_form_alter that will make field_b readonly / disabled and hook_entity_presave which will get the last word added to field_b upon save or update of a node of CONTENTTYPE

Create also MODULENAME.module file with contents:

<?php
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if(in_array($form_id,['node_CONTENTTYPE_form','node_CONTENTTYPE_edit_form'])) {
    $form['field_b']['#disabled'] = 'disabled';
  }
}

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if($entity->bundle() == "CONTENTTYPE"){
    $pieces = explode(' ', $entity->field_a->value);
    $last_word = array_pop($pieces);
    $entity->field_b->value = $last_word;
    //save is done automatically
  }
}

You NEED to replace MODULENAME and CONTENTTYPE in the above code.

If all is correct go to Extend (admin/modules) and enable the module.


How to ajaxify webform submit in Drupal 7? I have tried to alter the webform rendering using hook_form_alter() and hook_node_view() in a custom module so I could add '#ajax' somewhere.

Has anybody already had some experience working with webform and ajax on D6 or D7 ?
I guess the logic would be the same for D6 and D7 then just the implementation changes.

The Ajax Module works for me in Drupal 6.

For Drupal 7:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
      // see if webform_client_form_ is in the form_id
      if(strstr($form_id, 'webform_client_form_')) {
        // get the nid so we can use it in the wrapper value
        $nid = $form['#node']->nid;
        // add the ajax properties to the submit button
        $form['actions']['submit']['#ajax'] = array(
          'callback' => 'mymodule_webform_js_submit',
          'wrapper' => 'webform-client-form-' . $nid,
          'method' => 'replace',
          'effect' => 'fade',
        );
      }
    }

function mymodule_webform_js_submit($form, $form_state) {
      // define the $sid variable (submission id from webform)
      $sid = $form_state['values']['details']['sid'];
      // if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
      if ($sid) {
        // first we have to load up the webform node object
        $node = node_load($form_state['values']['details']['nid']);
        // create an array up with the confirmation message, retreived from the webform node
        $confirmation = array(
          '#type' => 'markup',
          '#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
        );
        // return the confirmation message
        return $confirmation;
      }
      else {
        // return the form
        return $form;
      }
    }


What happens to fields that don't have corresponding database columns? I'm doing some work around the Salesforce Suite in Drupal 7. It's a suite of modules that load the Salesforce REST API, map objects and fields between Drupal and Salesforce, push data from Drupal to WordPress, pull data down from Salesforce, manage queues for the data, etc.

I'm trying to understand how Drupal handles a flag called salesforce_pull (from the salesforce_pull module within the Salesforce Suite). This code runs when Drupal knows about a new Salesforce row (presumably on cron or on an Ajax call):

  try {
  // Create entity from mapping object and field maps.
  $entity_info = entity_get_info($sf_mapping->drupal_entity_type);

  // Define values to pass to entity_create().
  $values = array();
  if (isset($entity_info['entity keys']['bundle']) &&
    !empty($entity_info['entity keys']['bundle'])
  ) {
    $values[$entity_info['entity keys']['bundle']] = $sf_mapping->drupal_bundle;

    // Because creating term via entities actually needs vid and won't be
    // fixed in Entity API (https://www.drupal.org/node/1409256).
    if (isset($values['vocabulary_machine_name'])) {
      $vocabulary = taxonomy_vocabulary_machine_name_load($values['vocabulary_machine_name']);
      $values['vid'] = $vocabulary->vid;
    }
  }
  else {
    // Not all entities will have bundle defined under entity keys,
    // e.g. the User entity.
    $values[$sf_mapping->drupal_bundle] = $sf_mapping->drupal_bundle;
  }

  // See note above about flag.
  $values['salesforce_pull'] = TRUE;

  // Create entity.
  $entity = entity_create($sf_mapping->drupal_entity_type, $values);

  // Flag this entity as having been processed. This does not persist,
  // but is used by salesforce_push to avoid duplicate processing.
  $entity->salesforce_pull = TRUE;
  $wrapper = entity_metadata_wrapper($sf_mapping->drupal_entity_type, $entity);

  salesforce_pull_map_fields($sf_mapping->field_mappings, $wrapper, $sf_object);

A comment there says "// See note above about flag." but the only thing I found was the same flag for other events (update, delete of Salesforce rows). It looks like this (which is fine, but I still am unclear how it works/how to use it):

// Flag this entity as having been processed. This does not persist,
// but is used by salesforce_push to avoid duplicate processing.
$entity->salesforce_pull = TRUE;

That part about salesforce_push using it is what I'd like to understand.

I have not found a database field for salesforce_pull (on any of the entities). I've also done a database search (through phpMyAdmin so it could search the whole thing) for TRUE values and the salesforce_pull phrase with nothing that seems to be related to this, including in the cache tables.

It seems like the Fields API (at least in D7) has a way to save data that doesn't have a corresponding field in the database. If this is the case, where does the field get saved? How long does it stay before it gets reset? How does it get reset? How do I access it?

I'd like to be able to use this convention, but I don't understand how it works and haven't been able to find any documentation on it.

Interesting question, had a quick read through the module's code.
I came across this comment that should answer your question:

@salesforce_pull.module:335

  // Flag this entity as having been processed. This does not persist,
     // but is used by salesforce_push to avoid duplicate processing.
     $entity->salesforce_pull = TRUE;

It seems that this is not an entity field (or rather an entity property) that is attached to an entity (and therefore stored in the db), but, as the above comment mentions, simply a short-lived flag.

The way this goes is like this:

The salesforce_pull module sets the flag on an entity (see @salesforce_pull.module:335)
salesforce_pull conditionally wraps that entity in an entity_wrapper object and calls the ->save() function on the object (see @salesforce_pull.module:341)
This call will call hook_entity_update implementations, including the one from salesforce_push (see @salesforce_push.module:20)
salesforce_push will call the salesforce_push_entity_crud function that checks the value of that flag before using the Salesforce API to sync data (see @salesforce_push.module:44)

All the steps above take place in the same request, which is why persisting the flag is not required.

Hope this helps, good luck!


Is it possible to create a references from text? I'll explain problem with an example:

We have:

Text about apples
List of types of apples

Problem:

User inputs text about apples.
User selects text that describes certain type of apple, and then click 'magic button'
'Magic button' creates a small window with input field for type of apple.
User enters type of apple, drupal creates that type of apple in list of types of apples.

Details:

Apples are described in text.
Types of apples will not be a plain text(fieds in content type called 'Apple Types')

Is this even feasible in drupal?

Can you point me in right direction of search? What kind of modules(combination of modules) would help me?

It should be simple and straight forward as far as i understand. Below steps should solve the problem. You can solve it using Drupal Core itself and taxonomy module that comes with core.

Create a Content Type called "About Apples".
Add a text area field called "Apple Details".
Create a Vocabulary called "Apple Types"
Add a field called "apple type" , select field type as "term reference" and widget types as "Auto Complete term widget (Tagging)"

That's it ! You just created a content type called About apples which gives you a form to add Apple Details & Auto Complete Category widget which stores new terms to Apple Types vocabulary and shows autocomplete results when user tries to add categories.


Alter product variation view I want to alter product variation view and want to display a new form which value depends on variation price. I can add the field to the node using hook_node_view_alter() but i want to add it to the product variation right after the price field. I just need to display an integer dependent of the price.

Any help with this?

Thank you

You can try hook_entity_view_alter() API function provided by Drupal Core to alter any entity.

If you want to alter how the entity will look, you can also try using Display Suite or Panels module which are used to override the display.


How do I change a field with hook_node_presave()? In Drupal 7, I was using hook_node_presave() to update some hidden fields in a node.

function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->field_fieldname['und'][0]['value'] = importantfunction();
    }
}

In Drupal 8 I cannot do the same thing. Looking into the object I tried this:

function mymodule_node_presave($node){
    if ( CONDITIONS ) {
        $node->values['field_fieldname'][0]['value'];
    }
}

It won't work though. I am aware that a lot have changed in Drupal 8 and I am studying it, but I did not find an answer to this yet.

A bit outdated but still a great resource:

http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet

Also the documentation on drupal.org: https://www.drupal.org/node/1795854

In short, fields are lists of objects that use property and array access magic methods to simplify reading and writing values to them:

// Set a value, the field class will decide what to do with it, usually write to the primary property...
$entity->field_fieldname = importantfunction();

// The default property is often called value, but for reference fields, it is target_id, text fields also have a format for example
$entity->field_fieldname->format = 'full_html';

// By default, you access delta 0, you can also set other deltas.
$entity->field_fieldname[1] = importantfunction();

// You can also append a new item, without hardcoding the delta.
$entity->field_fieldname->appendItem(importantfunction());

// Note that when accessing fields, you must always specify the property:
print $entity->field_fieldname->value;
print $entity->field_fieldname[1]->value;

// What basically happens internally for the above is:
$entity->get('field_fieldname')->get(0)->get('value')->getValue();


How to have CCK "Select list" field on my content type? I want to include in my content type a CCK "Select List" field.
Which module(s) should I enable so as to have it as a choice?
Thanks

You have to enabled Option Widgets, as well as Number and/or Text.

Create a new field by going to admin/content/node-type/%content-type%/fields  (where %content-type% is the machine name of your content type)

Create a new field.  If you enabled Text module, you have the option of Text.  If you enabled Number, then you have the option of Decimal, Float and Integer.

Select the Operations you want

Clicking Save will take to the Field setting page. Scroll down to the bottom and type in the allow values for your option widget.

And you are done.


Custom container.html.twig I need to delete a div made by the container.html.twig. How can I rename this template to this specific region?

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'container' -->
<!-- BEGIN OUTPUT from 'themes/newbikes/templates/system/container.html.twig' -->
<div class="form-group">

thx.

Copy core template to your theme template folder (yourtheme/templates) core/themes/stable/templates/form/container.html.twig and clear caches.


Date of Birth in Views: Age is 1 day ahead of desired value Drupal 7.15 with Date module version 7.x-2.6

Date, Date API, Date Views enabled.

I added a date of birth field to a content type, and added 'child' nodes with their dates of birth.

In Views, I want to see the age of the children, so in the View I have:

Configure field: Content: Date of birth

Formatter = Time ago

Display = Time ago

My problem is this.

Right now, it is Thursday 6 September 2012 1500

A person has Monday 7 September 2009 as their date of birth.

The 'time ago' is showing as 3 years 15 hours ago.

However in real life they haven't yet reached their third birthday, so I want the result to say 2 years until midnight tonight when the child becomes 3.

How can I fix this?

The problem is that "Time ago" has no understanding of leap years so when it is calculating an interval it uses a "common year" which is 365 days.

If we go back 30 years ago from today (2018-11-08) to 1988-11-08 and then use a date time calculator we get 30 years exactly, OR 360 months, OR 10957 days.

If the "Time ago" was smart enough to subtract the years, following by the months, followed by the days then it would come up with 30 years, 0 months, and 0 days. The problem is that it does all of its math in days and then tries to convert to years.

10957/365 = 30.019 common years or 30 years and a week. This is because there was 7 leap years between 2018 and 1988...

So there isn't anything wrong per say. It is actually doing exactly what you asked it to do.

You can get much closer if you divide the date by 365.2425 which is the average length of the year of 365.25 which is defined as a Julian year. Julian years are used in astronomy.


Custom field values are not importing with Features I would like to export example data(nodes) in feature for others to kick start some reusable module that i developed. The example data contains nodes with custom fields. The problem is that while nodes and default field values(title, body) are importing the values for the custom fields are not. I am new to features. I must be doing something wrong.

For the example data I have selected the nodes, field bases, field instances and rest of the dependencies detected, but this is not export/import the custom field values. I am guess i have to select some more StrongArm variable values since these custom field instances are shared across multiple nodes? if so, how do i detect the dependent variables to particular node instance?...strongarm does not provide any drush command for that purpose...Any help is much appreciated

p.s. Are you using features for exporting/importing Sample Data of you custom module? I may have taken the wrong approach

Features: 7.x-2.0,
uuid_features: 7.x-1.0-alpha3,
strongarm: 7.x-2.0,
Drupal: 7.26

To clarify, the custom fields of nodes that reference to Taxonomy elements did not export/import via features. The reason is that Taxonomy term references(tid) are stored by ID instead of UUID with stable version of uuid_features and uuid as of Feb, 2014

The solution was to use dev version 7.x-1.x-dev for uuid as well as uuid_feature module. This will export/import custom fields (term reference) into UUID instead ID that solved the problem


Best practices for copying data (only) back from production site to testing site after exporting views as features to prod? After building/testing a Drupal 7 site, I deployed it to prod server, exporting all views as features. Now the views are all 'in database' on test site, but 'in code' on live site - on the theory that no views editing should be done in prod. Now if I want to copy my prod database (but not code) back to my testing site for a new phase of development, what's the best way to avoid overwriting (or wiping out) views 'in database' on my dev site?

Should I have renamed the views when creating features?
do I export/import the views, either from/to testing or from prod to testing?
is there some other way to selectively preserve views in the testing db when copying back an sqldump?

Thanks much!

We have the following:

DEV code base. (dev-code)
DEV database. (dev-db)
PROD code base. (prod-code)
PROD database. (prod-db)

Here is a simple dev flow to change a view, deploy to prod and then continue development:

[dev-db] Create a new view or modify an existing view.
[dev-code] Create a feature module out of that view or re-create an existing one.
[dev-db] Enable the feature module on DEV.
[prod-code] Commit the change and push it to PROD or upload the changes to PROD.
[prod-db] Enable or Revert the feature on PROD.
[prod-db] Export database from PROD (and preferably sanitize it to remove sensitive data)
[dev-db] Import the database dump to DEV.
[dev-code] Continue development!

You shouldn't have any problem if you are following this flow.


How to access fields value in views-view--[viewid]--[view-display-id].html.twig template I'm trying to customize a View in Drupal 8 where I display a Bootstrap Carousel.
What I've managed to do so far was the right template name, by specifying the viewid and view-display-id.
The view name is homepage-carousel and the view display id is block 1, therefore the template name views-view--homepage-carousel-block-1.html.twig or views-view--homepage-carousel.html.twig.

Now I need to show the content of the fields of a specific Content Type. I've tried with {{ fields.title }}, but it doesn't work. I've also tried to change the template name in views-view-fields--homepage-carousel-block-1.html.twig, but the system doesn't recognize it, so it displays the default view.

Here is the code:

{{ fields.title }}

          {{ fields.field_carousel_subtitle }}

How can I show the fields from this kind of view template?

UPDATE
I've tried to rename the template as suggested JeremyM4n, I've flushed all the cache, but it still doesn't work. The view is displayed as default, namely how it is set up in the /admin/structure/views/view/ section.

I haven't mentioned it yet, so I specify it here: the format of this view is Bootstrap Carousel

UDPATE 2

I managed to find a solution by by overriding the views-bootstrap-carousel.html.twig template in view_bootstrap module. In my case, the name of the template is the following: views-bootstrap-carousel--homepage-carousel--block-1.html.twig

Here is the code:

  {# Show indicators if set in view. #}
  {%  if indicators %}

      {% for key, row in rows %}
          {% set indicator_classes = [loop.first ? 'active'] %}

      {% endfor %}

  {% endif %}

  {# Carousel body. #}

    {% for row in rows %}
      {% set row_classes = ['item', loop.first ? 'active'] %}

          {{ row.image }}
          {% if row.title or row.description %}
            {%  if use_caption %}

            {% endif %}
              {% if row.title %}

{{ row.title }}

              {% endif %}
              {% if row.description %}

{{ row.description }}

              {% endif %}
              {{ row.field_carousel_button_text }}
            {%  if use_caption %}

            {% endif %}
          {% endif %}

    {% endfor %}

  {# Controls #}
  {% if navigation %}

      {{ 'Previous'|t }}

      {{ 'Next'|t }}

  {% endif %}

The template name needs double dashes between each section views-view--homepage-carousel--block-1.html.twig.

At the views-view level all of your data is in rows. You would need to loop through your rows and then get the fields. But it's much easier to just override the main structure you need to in views-view, and then use views-view-fields--homepage-carousel--block-1.html.twig to change the structure of the actual fields, in which case they are available under fields like your example code.


what when displaying a variable with kint crashes? I am trying to find the variable name for the content link in a view.

{{ kint(content) }} makes the page crash, probably because the variable is too big.

The same is true for the following code.

function my_theme_preprocess_field(&$variables, $hook) {
    var_dump($variables);
}

How can I find out what I am looking for?

Usually D8 $variables contain way too much data, and browser struggle to render it for you.
I strongly suggest to use xdebug or similar debugger, all modern IDEs support it. It makes developer's life much easier.
However, there is a workaround without having xdebug configured:

function my_theme_preprocess_field(&$variables, $hook) {
    var_dump(array_keys($variables));
    // or better:
    kint(array_keys($variables));
    // or:
    dpm(array_keys($variables));
}

This will return you top-level keys, then you can drill down to the next level:

dpm(array_keys($variables['some_key']));

For objects use type casting:

dpm((array) array_keys($object));

Set Kint as Variables Dumper on /admin/config/development/devel (with Devel Kint module enabled) and you'll get nicely structured output.

In Twig templates you can use something like this:

{% for key, value in content %}
    {{ key }}
{% endfor %}

UPD: Valuable comment from Kevin for TWIG:

{{ kint(content|keys) }}


How to add order number to multivalue fields classes? A node with a multivalue image field looks something like this in html (the part which displays images):

....

I would like it to look like this:

....

One way is to write a node--contenttype.tpl.php and inside, instead of print render($content); make a big loop which will render the fields one by one, adding the necessary class with number to images.

Is there a simpler way to achieve this?

template_preprocess_field(&$variables, $hook) gives you the ability to manipulate fields before they are printed. Just like with template_preprocess_page() and template_preprocess_node(). Not sure what the $hook parameter is for and I have never needed it myself.

Since this is a preprocess function that will be executed for each field, you should add a condition for your field name. Something like this will do:

function THEME_OR_MODULE_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'FIELD_NAME') {
    // Manipulate the data. use dsm() or print_r() to see the array structure.
  }
}

Edit: It would seem as if $hook is always passed as the string 'field', which would be quite useless. Can anyone confirm this?

Edit 2: Okey, so you actually don't need template_preprocess_field() at all if you can override theme_field.

Below is a working example of a extended theme_field($variables) function based of the original version. There is also a good tutorial/example here, which @camcam shared in a comment.:

function THEME_NAME_field($vars) {
  $output = '';
  $i = 0;

  // Render the label, if it's not hidden.
  if (!$vars['label_hidden']) {
    $output .= '
' . $vars['label'] . ':&nbsp;
';
  }

  // Render the items.
  $output .= '
';
  foreach ($vars['items'] as $delta => $item) {
    $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');

    // Add Row index to classes and iteriate row index variable.
    if ($vars['element']['#field_name'] == 'FIELD_NAME') {
      $classes .= ' row-' . $i;
      $i++;
    }

    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}


How to rename installation profile name in existing website in D8 I have installed Drupal 8 with a custom subprofile. 'my_custom_profile'.

Development of site is almost completed and we have added all the contents in the site.

In this stage how can I rename my installed subprofile name from 'my_custom_profile' to 'custom_profile'?

Is it possible to update DB entries manually for subprofile?

Ok here is the way to do it:

Edit this line in core.extentions.yml in your config directory to your new name

my_custom_profile: 1000

Rename your profile directory and clear the cache


Event related to node - how to display? Thinking how to achieve what I need, looking into possibilities. I have a content type that is used for all kind of locals: restaurants, clubs and so on. Now, what I want is to have a list of nearest 3 events that will take place in that specific place.

So far I was thinking about creating new type of nodes for events. Let's say: Event content. Seems logical, right? Now, using Entity Reference I should be able somehow to add relation between an event and club (not sure about this one yet). Next step would be displaying this added event on the node of that club. How could I achieve that? Creating a View and putting it into the node display somehow? Block?

Really could use some ideas for that.

You should create a view and add relationship using node reference(entity reference) and after adding relationship you should add fields corresponding to node for which relationship has been added.
Check the link on how to add relationship in views


How do I specify in which database my schema should be created? When using multiple databases in Drupal 7, how can I specify that a table is to be created in a different database on a different server?

By default, when you install a module, Drupal assumes that everything in hook_schema() should be installed in the default database. Is there a way to specify that a table should be created on a different database, or is there some kind of manual workaround I can use?

I have achieved this with the information provided by Berdir. My code looks like:

<?php
function mymodule_schema_otherdb() {
  $schema['mytable'] = array(
    'description' => 'My table description',
    'fields' => array(
      'myfield' => array(
        'description' => 'My field description',
        'type' => 'serial',
        'size' => 'medium',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
    ),
    'primary key' => array('myfield'),
  );
  return $schema;
}

function mymodule_install() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
  db_set_active();
}

function mymodule_uninstall() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_drop_table($name);
  }
  db_set_active();
}


Use AJAX with form button to clear checkboxes in separate forms I have a case where I need to have a Clear button on a form that not only clears out the form it's on, but also clears out checkboxes in other forms and clears data from ctools_object_cache.

The page is a custom search page created by the apachesolr module.  In the sidebar I have multiple blocks that are just 'checkboxes' form elements of taxonomy terms (each block is a separate vocabulary).  The checkboxes are used to select terms, which are written to ctools_object_cache using #ajax in the form when selected.  What I need is to have a Clear button (or link) on the search form that does a few things:

Clears the search field
Deletes items from ctools_object_cache
Deselects the checkboxes in the sidebar forms
Selects a specific checkbox in another sidebar block (labeled "All")

Is it possible to do this using a #ajax button with Forms API?  Or do I need to just write it as a separate Drupal behavior in jQuery?  I know Drupal forms can be handled in jQuery, but I haven't used it before, so I'm not sure where to start.

Thanks.

In talking to Randy Fay, this will not work for a number of reasons, of which security is a big one.  Form API was written to avoid one form modifying other forms (among other things), so I re-architected the form elements to be all in one form instead of separate forms.


How do I properly add css to my feature? I have a feature that just contains a few views. How do I properly add a stylesheet to it?

You add the css file to the module.
Use drupal_add_css to include the css file in the .module, this could be done in hook_init and would look something like this:

module_name_init() {
  if (arg(0) == 'views_path') {
    drupal_add_css(drupal_get_path('module', 'module_name') . '/path_to.css');
  }
}


Create Taxonomy term with added text and date fields, then display them in "add content" I'd like to add a date field ("date") and a text field ("notes") to a taxonomy term ("Category").  Easy enough.

When I add content, I have the taxonomy term linked using term reference, and it is working fine.

What I can't figure out is this: I'd like the "date" and "notes" field to also appear on the add content screen once the "Category" is selected, and be fully editable.  How would I go about this?

Specifically, when I add content, I select the category and enter all other relevant data. I then enter a date and notes that apply to that node being created, and also apply to any other node of the same category.

Thank you for help!

Am not familiar with any contributed module which will server your requirement.
But i can help you to achieve this functionality.

Add the Date and Notes field to the specific content type using the 'Add Existing field' option. Since you have already created the fields for taxonomy term, its not necessary to create a new fields.

While adding a new content of that particular content type, mention the category , date and notes in the respective fields.

Now what we need to do is to hack-into the node submit flow and update the specific taxonomy term with the newly entered date and notes values.

Easily do this by using a single hook : hook_node_presave($node)

You can using this hook in any of the custom module. The '$node' variable will contain the date and notes values. We can easily load the selected taxonomy and update the date and notes of the taxonomy via DB queries

Thanks,
Vineeth


Custom javascript file not working in mobile browsers I have added a custom jQuery file to my theme with the theme.libraries.yml. In my laptop and fullscreen browsers the added javascript is working without any issues. But it seems the javascript does not have any effect in mobile browsers(I'm testing with ipad and iphone browsers in both safari and chrome). My custom_theme_libraries.yml is as following

global-scripts:
  js:
  js/jqueryfile1.js: {}
dependencies:
- core/jquery

And my jqueryfile1.js is as following

(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

Is there any additional configurations to be considered to get the code works in mobile browser also?

It seems like your code is the problem. You have extra });

Should be

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      $(document).ready(function() {
        // code goes here
      });
    }
  };
})(jQuery);

But it is nonsense to use $(document).ready as it is already handled by Drupal.behaviors.

So the proper way is.

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      // code goes here
    }
  };
})(jQuery);

The attach() method is called when the DOM has loaded both initially and after any AJAX calls.

See this doc for more info. https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview


What happens when an email from webform fails to deliver? If webform attempts to send an email but cannot connect to the smtp server, what happens to the email? Does it get dropped on the floor? Does it throw an error in a log? Does it try to resend later? Does it mark it somewhere as unsent?

It throws an error and drop it on floor like below:

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in DefaultMailSystem->mail() (line 76 of \modules\system\system.mail.inc).
Unable to send e-mail. Contact the site administrator if the problem persists.


Tokens not working in entity form I put together a simple entity form and am trying to enter a few default token values for fields on the form.
But when I choose something like [site:current-user:mail] from the list of available tokens, it displays literally as typed.
Which is to say that, in the input box where the user's email is supposed to have been inserted, I'm seeing the text - "[site:current-user:mail]" instead in that field, which is a bit strange, since tokens seem to be working everywhere else on the site.

I'm using the latest stable version of drupal 7 and the entityform module.

Install the Field default token module and then edit the entityforms type and save again with the desired tokens selected, and it should work.


How do I set the total submissions limit when I create a node? I'm using "Webform Node" module to create event registrations.

Now I can set the total submissions limit of event in Structure> Webforms> my webform type

and when I create a webform node, there is no setting option:

Because every event has different submissions limit, I want to set the limit when I create the webform node, instead of in the webform type, how can I do it? thank you so much!

Go to the Webform's settings
(/admin/structure/webform/manage/contact/settings)
Scroll to 'Submission Limits'
Set 'Total submissions limit per entity' or 'Per
user submission limit per entity'

I think the labeling and additional help text could help better define this features.  Feel free to create a ticket in the Webform module's issue queue


Is there a pre-styled Omega subtheme out there? I am after a theme that looks good out of the box and I don't need to make a lot of theming changes. The customer is not fussed about the styling but obviously doesn't want a stark/bare looking site either. The omega theme fits the bill functionality wise, it's responsive and the regions/sections suit us. However, it is way too bare/stark. I've so far tried Omega kickstart, omega and omega-alpha.

Any suggestions on a pre styled free theme I can used that is based on the Omega "framework"?

Here is the complete listing of themes which uses the omega theme as a base theme.

Apart from that you can get the list of various themes/sites which uses omega theme on omega theme project page


How to set start slide for views slideshow jcarousel I am using viewsslideshow and viewsslideshowjcarousel modules. I am displaying image thumbnail as jcarousel bottom of the Gallery slides using viewsslideshowjcarousel module. It's working perfectly.

Here is the problem. I would like to navigate to slide directly using the URL. Views slide show support this by passing #unique-id:slidenumber as discussed here. But, i can not able to slide automatically to the the thumbnail of the jcarosel pager that image belongs to. I see setting start option as discussed in Documentation should do the job. But adding that is breaking the carousel in below code inside views_slideshow_jcarousel.js file.

// Add views slieshow api calls for views slideshow jCarousel pager.
Drupal.behaviors.viewsSlideshowJcarouselPager = {
  attach: function (context) {
    // Process pause on hover.
    $('.views_slideshow_jcarousel_pager:not(.views-slideshow-jcarousel-pager-processed)', context).addClass('views-slideshow-jcarousel-pager-processed').each(function() {
      // Parse out the unique id from the full id.
      var pagerInfo = $(this).attr('id').split('_');
      var location = pagerInfo[2];
      pagerInfo.splice(0, 3);
      var uniqueID = pagerInfo.join('_');
      $(this).jcarousel({
        vertical: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].orientation),
        scroll: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].scroll),
        visible: parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].visible),
        wrap: Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].wrap,
        animation: (isNaN(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation)) ? Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation : parseInt(Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location].animation),
        initCallback: function(carousel) {
          Drupal.settings.viewsSlideshowJCarouselPager[uniqueID][location]['carouselObj'] = carousel;
        }
      });

      $(this).find('.views_slideshow_jcarousel_pager_item').each(function(index, pagerItem) {
        $(pagerItem).click(function() {
          Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
        });
      });
    });
  }
};

Any idea how to start jcarosuel based on the slidenum passed in the url ?

Try to add a contextual filter to the view that sorts the results putting the desired element in the first position of the carousel.

There is a nice reference for that: http://www.metaltoad.com/blog/using-drupal-contextual-filters-views


Is there a way to display basic site statistics in a block? I am trying to find a way to display basic site statistics in a block. I have enabled the core "Site Statistics" module but I cannot find a block that would provide me this functionality. I do not want to display anything fancy; just some pageviews and unique pageviews and perhaps, optionally, the 5 most visited pages in the website.

Am I missing something here or do I need a separate module (that I can't find) to add this functionality to my website?

Thanks in advance.

This is a job for the views module. Using views in its most basic form you could have a block for the below in under 30 secs.

Content statistics: Most recent view

The most recent time the node has been viewed.

Content statistics: Total views

The total number of times the node has been viewed.

Content statistics: Views today

The total number of times the node has been viewed today.

Install views module, add new view, view name = stats, uncheck create a page, check create a block, continue and edit. Add fields and add the 3 above. Remove title. Add a contextual filter under advanced and use Content: nid, provide default value = content ID from url. Get rid of any filter and sort criteria and you should be good to save the view. You will now have a view block that you can place in any region to display this info.

The 5 most visited block would be similar except you would keep the content published filter and add a sort (descending) on Total views. You could use the "Use pager: Display a specified number of items | 5 items" to get a list of the top 5 most viewed nodes.


How to submit a form with javascript? I have an exposed views form, am geolocating in javascript and setting the co-ordinates in the exposed form.

This form submits properly when I click on the 'apply' button but does not when I use javascript to submit the form. The page refreshes, but the values have not been changed.

The form is standard FAPI. It is not a views-ajax form although I would like to move to ajax at some point in the future when I sort out the problems with gmaps + ajax.

Both of the following fail.

jQuery('#edit-submit-studio-locations').click();
jQuery('#views-exposed-form-studio-locations-page').submit();

The full code is in github.

Add this code inside Drupal.behaviors.

$('.views-exposed-form APPLY_BUTTON ID/class').click(function() {
  // Submit the form
  (this).parents('form').submit();
});

Hope it works.


Error when creating taxonomy term programmatically I'm trying to create a term programmatically:

$term = Term::create([
  'vid' => 'vocabulary_mane',
  'name' => 'term_name',
]);

$term->save();

I can see my term in my overview page in the back-end:

But when I click on modify, I will receive an error page:

In the journal this is the log:

What is wrong?

i found the solution.

the problem was with uppercase/lowercase vid value.

If your vocabulary starts with an uppercase letter ex: 'Animal', thr vid value will starts with a lowercase letter ex: 'animal' otherwise you will have an error

This was my problem, hope it will you help.


Drupal pagination help I am not sure how this works, hence need a little help. I am fetching some nodes using db_select and rendering this in a foreach loop in a custom template file. I would give a hint of my code :

$nodes = db_select('node', 'n')
// Some fields...
// Some conditions...
// ->execute();
$nodes = $nodes->fetchAll();
return theme('my_custom_callback', array('nodes' => $nodes));

Now I get this $nodes in my tpl file and print them to the design. But what I want is to have the Drupal default pagination effect (probably using the PagerDefault facility). I have come accross many examples of the use of PagerDefault but I am not sure how to render the pagination in my tpl file.

Please note using a Drupal view or a table theme is not an option in my case.

Help appreciated...

Well as no one responded, I searched a bit and found a normal PHP function to achieve the same. I know it may not be a Drupal way, but its for them who are looking for a quick solution for now (like me). But would like to add that other answers to achieve this the specially the Drupal way is very much welcome. Also please note, I almost copy pasted the actual function, so you probably may want to modify that as per your UI (for actual function I have given the reference below) :

// This is the menu callback where $data are the records fetched to be displayed in this page, and $total_count is the total number of count of all the records.

$pager = pagination($current_page, $total_count, $record_limit, 2, "url-menu-page?page=%d");

$return_val = theme('my_callback_function', array('data' => $data, 'pager' => $pager));

return $return_val;

And here goes the actual pagination building function :

/**
 * Displays pagination links based on given parameters
 *
 * @param int $currentPage - current page
 * @param int $itemCount - number of items to paginate, used to calculate total number of pages
 * @param int $itemsPerPage - number of items per page, used to calculate total number of pages
 * @param int $adjacentCount - half the number of page links displayed adjacent to the current page
 * @param (string|callable) $pageLinkTemplate - pagination URL string containing %d placeholder or a callable function that accepts page number and returns page URL
 * @param boolean $showPrevNext - whether to show previous and next page links
 * @return void
 */
function pagination($currentPage, $itemCount, $itemsPerPage, $adjacentCount, $pageLinkTemplate, $showPrevNext = true) {
  $pager = '';
  $firstPage = 1;
  $lastPage  = ceil($itemCount / $itemsPerPage);
  if ($lastPage == 1) {
      return;
  }
  if ($currentPage <= $adjacentCount + $adjacentCount) {
      $firstAdjacentPage = $firstPage;
      $lastAdjacentPage  = min($firstPage + $adjacentCount + $adjacentCount, $lastPage);
  } elseif ($currentPage > $lastPage - $adjacentCount - $adjacentCount) {
      $lastAdjacentPage  = $lastPage;
      $firstAdjacentPage = $lastPage - $adjacentCount - $adjacentCount;
  } else {
      $firstAdjacentPage = $currentPage - $adjacentCount;
      $lastAdjacentPage  = $currentPage + $adjacentCount;
  }
  $pager = '

Pages

';
  if ($currentPage != $firstPage) {
    $pager .=  '
&laquo; first
';
  }

  if ($showPrevNext) {
      if ($currentPage == $firstPage) {
      //$pager .= '
< previous
';
      } else {
      $pager .= '
&lsaquo; previous
';
      }
  }
  if ($firstAdjacentPage > $firstPage) {
      if ($firstAdjacentPage > $firstPage + 1) {
      $pager .=  '...';
      }
  }
  for ($i = $firstAdjacentPage; $i <= $lastAdjacentPage; $i++) {
      if ($currentPage == $i) {
      $pager .=  '
' . $i . '
';
      } else {
      $pager .=  '
' . $i . '
';
      //$pager .=  "
$i
\r\n";
      }
  }
  if ($lastAdjacentPage < $lastPage) {
      if ($lastAdjacentPage < $lastPage - 1) {
      $pager .=  '...';
      }
  }
  if ($showPrevNext) {
      if ($currentPage == $lastPage) {
      //$pager .=  '
next >
';
      } else {
      $pager .=  '
next &rsaquo;
';
      }
  }
  if ($currentPage != $lastPage) {
    $pager .=  '
last &raquo;
';
  }
  $pager .=  '

';

  return $pager;
}

Hope this helps somebody...

Original code credit goes to the author of this blog : http://salman-w.blogspot.in/2014/04/stackoverflow-like-pagination.html


How to change a Textfield into a Select list in a Views Exposed Filter Figured this question would be asked before, but don't see it.
I have a views exposed filter with a Text Field as one of the filters. I'd like to display this filter as a Select List instead of the standard text input or autocomplete.
Any advice on how to?

Okay, figured out a solid solution using hook_form_alter.
function MODULENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

    if ($form['#id'] == 'EXPOSED-FORM-ID') {

        $nids = \Drupal::entityQuery('node')->condition('type','CONTENTTYPE')->execute();
        $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
        $options = ['' => 'All'];

        foreach($nodes as $nid => $node) {
          $value = $node->get('FIELD_NAME')->getString();

          if (isset($value)) {
            $options[$value] = $value;
          }
        }

        if (isset($form['FIELD_NAME_value'])) {
          $form['FIELD_NAME_value']['#type'] = 'select';
          $form['FIELD_NAME_value']['#options'] = $options;
          $form['FIELD_NAME_value']['#size'] = 1;
        }
      }
    }

}


Update default value of form element with AJAX I have an email field on node add form , I want to check if this email exist fill the city field in the same node form , then my code is :

function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );
}

function user_ajax_check($form,$form_state){
    // load the user then
    $form["field_user_city"]['und'][0]['value']["#default_value"] ="foo";
    return $form["field_user_city"];
}

The value must be set in the hook_form_alter, not in the callback of ajax :

function custom_code_form_car_node_form_alter(&$form, &$form_state, $form_id){
  $form["field_user_email"]['und'][0]['email']['#ajax'] = array(
      'callback' => 'user_ajax_check',
      'wrapper' => 'field-user-city-add-more-wrapper',
      'effect' => 'fade',
  );

  if(!empty($form_state['values']['field_user_email']){
       $form["field_user_city"]['und'][0]['value']["#default_value"] = "foo";
  }
}

function user_ajax_check($form,$form_state){
    // load the user then
    return $form["field_user_city"];
}


Set the effective log severity level In a Drupal 8 site, on the page /admin/config/development/logging, I can specify if I want warnings, errors and other messages to be displayed. But either I want them displayed or not, they exist.

On this other page, admin/reports/dblog , I can see all the logs available in database.

But if my site has many visitors, Debug, Info and Notice logs are constantly inserted in the database. Which causes high charge on the database and "hides" the important logs (errors and warnings).

How can I tel Drupal "Do not insert in database any log with a severity level below WARNING" ? The equivalent of the level value we find in every logging framework.

There is no such setting unfortunately. There is a module for 7.x, but not 8.x port yet: https://www.drupal.org/project/watchdog_filtering.

You could use a different watchdog backend that supports filtering, or log to syslog or some other system that is better at dealing with a lot of log entries.

And if those notices/warnings are caused by PHP notices/warnings, then you should fix them.


Maximum on date field and Views aggregation issue I am running a Drupal 8.0.5, I have a content type called show which has fields title, an entity referenced called movie and a date time.
I am trying to create a view of the latest shows of each movie. The initial view is like this which shows the movie and show time

I enabled aggregation. Aggregation functions i used are For movie - group results together and for datetime - maximum. The result is as follows

it just gives 2,016 as date time field where i was expecting Mon 03/21/2016 15:00:00. Are we not supposed to aggregate on date field? I thought since MAX usually works in database for timestamp, it is valid here also. Can anything be done to achieve this result?

First of all, select "None" for "Thousands marker" to have a properly formatted timestamp value;
In the "REWRITE RESULTS" section you can override the output of the field.
Given I have the aggregated field "created" overriding the field would look as following:

{{ created |timestamp_format('Y-m-d') }}


CKEditor adds extra  tag CKEditor inserts extra <p> tags when users enter a newline.

How do I disable this automatic paragraph tag?

You need to modify these settings to CKeditor.

// The writing rules for the <p> tag.
writer.setRules( 'p', {
// Inserts a line break after the <p> opening tag.
        breakAfterOpen : true,
}

This can either be set programmatically, via JS or I believe you should be able to add it directly via the UI, if you visit the Ckeditor settings page, there should be a box where you can enter ckeditor settings.

For more info see ckeditor docs: https://docs-old.ckeditor.com/CKEditor_3.x/Developers_Guide/Output_Formatting


How to add a 'flag link' in an email? I want to add a 'flag link' in an email. I have an event content type, and every time a new event created, the users get an HTML Email. I have a flag that the users can flag this event if they want to attend. I want to embed the flag link in the email, so that the users click the link and redirected to the flag confirmation page.

I've tried that with flag_create_link() in the email-template but it has two problems that makes it unusable in an email. First, I'm getting 'Bad token' error if click the link in the Email. Second, the URL generated is a relative URL, so I had to manually change the URL in browser to test, which got me to the first problem.

Is there any proper way to embed a flag link in an Email? So that, the user can click and directed to the confirmation page of the flagging, or login page if he's not already logged in.

UPDATE:

I've changed the link type to 'confirmation form' and that solved the first problem. I'm not getting 'Bad token' error anymore. However, the link path is still relative.

With the following code I managed to create the flag link to embed in the email body:

global $base_url;
$flag_url = $base_url . base_path() . 'flag/confirm/flag/my_flag/' . $nid;


Can I upgrade from Drupal 7.10 directly to Drupal 7.12 Should I upgrade from 7.10  to 7.11 first, then upgrade from 7.11 to 7.12?

Or can I just upgrade from 7.10 directly to Drupal 7.12?

You can update directly to 7.12 without any problems. Drupal 7.11 contains security fixes while 7.12 contains bug fixes. Updating to 7.12 would also add the security fixes from 7.11.


Method to test if site has rss view Our group has a multi-site drupal-D7 installation -- approximately 70 sites -- we need to identify which site have an RSS view. I've been trying to find a signature in the databases' that we could search for to identify which ones have one or more. So far we've been unsuccessful. Is there a way, perhaps a drush command?

You can run the follow SQL command on the databases of the sites:

SELECT * FROM `views_display` WHERE `display_plugin` = 'feed'

Maybe you can use a script to loop through all the databases and get those with results


How to change value of hidden field on node publish? My client has a system in which they allow nodes of certain content types to be created by authenticated users. The nodes are unpublished until they are reviewed by someone with the proper role and this all works correctly.

One of the requirements was allowing users to save a node as draft. I initially used the Save Draft module but found that was defaulting nodes to be published which caused problems. I worked around this by adding a hidden field called status that would change values based on which submit button was clicked via hooks.

Now, the issue comes when the node is reviewed. At that point, an admin will change the node to published. They would also like automatically like this hidden status field to change from "submitted" to "published". Normally, I would use a hook for this but through my testing, I can't seem to get form alter hooks to work in the admin section.

I suppose I have two questions here:

Is there an easier way to achieve my end result here?
Failing that, is there a way to automatically change the value of one field when a node is updated via the admin section?

Piece of cake, if you are willing to use the Rules module for this ... like so:

Rules Event: before saving content, which covers all variations of updates of nodes, and creations of new nodes (and does not require an explicit "entity save" action).
Rules Conditions:

Entity has field, for your hidden status field, that way the logic implemented via this rules only applies for nodes that use this field.
Node-unchanged has status unpublished.
Node-changed has status published.

Rules Action: Set a data value, for your hidden status field, to assign the value 'published'.

With the above in mind, have a look at this rule (in Rules export format), in which I'm using a status field with machine name field_status (and for which a value of "P" reflects "Published" status:

 "rules_change_value_of_hidden_field_on_node_publish" : {
    "LABEL" : "Change value of hidden field on node publish",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_status" } },
      { "NOT node_is_published" : { "node" : [ "node-unchanged" ] } },
      { "node_is_published" : { "node" : [ "node" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-status" ], "value" : "P" } }
    ]
  }
}

If you adapt the machine name field_status to match your own field's machine name, together with the value used to reflect "Published" status, you should be able to import the above rule in your own site. After doing so ... you should be done!


entity_get_controller Fatal error entity_get_controller() is giving me an error when I try to use a class. This class is defined in another file called ingredient.controller.inc

  Fatal error:  Class name must be a valid object or a string

The following code doesn't work:

 function ingredient_add() {
   $ingredient = entity_get_controller('ingredient')->create();
   return drupal_get_form('ingredient_add_form',$ingredient);
 }

The following one works;

function ingredient_add() {
  $ingredient = (object) array('iid' => '','name' => '',);
  return drupal_get_form('ingredient_add_form',$ingredient);
}

The class code is the following one:

class IngredientController extends DrupalDefaultEntityController {

    public function create() {
      return (object) array(
        'iid' => '',
        'name' => '',
      );
    }
}

function nutrition_entity_info() {
  $return['ingredient'] = array (
    'label' => t('Ingredient'),
    'controller class' => 'IngredientController',
    'base table' => 'ingredient',
    'uri callback' => 'ingredient_uri',
    'fieldable' => TRUE,
    'entity keys' => array (
      'id' => 'iid',
      'label' => 'name',
    ),
    'static cache' => TRUE,
    'view modes' => array (
      'full' => array (
        'label' => t('Full content'),
        'custom settings' => FALSE,
      ),
      'teaser' => array(
        'label' => t('Teaser'),
        'custom settings' => FALSE,
      ),
    ),
  );

  return $return;
}

Do you have any idea?

Should the implementation of hook_entity_info() be nutrition_entity_info() or ingredient_entity_info()?

Nutrition is the module name, ingredient the entity I am creating.

There was some kind of typo on the code, as it seems to work now.

I suspect that you haven't implemented hook_entity_info(), which is why entity_get_controller() returns nothing, and you can't call a method of nothing.

The Examples project has an issue in the queue for an entity example. Give it a read. :-)

Hooks have the module name, so if the module is called nutrition, you'd declare nutrition_entity_info().


Need of re-indexing on search on Drupal site? My client site has a table whose data is coming from Indexed view, sometimes updates made to the data wont reflect in the view table. Elysia cron is installed and up running, which should update the content when changes are made.

Then what is need of re-indexing the search index?

I could see my index only 1% indexed even though I ran the cron 2-3 times.
Can anyone help in this?

Thanks in advance

Cron by default only indexes a certain number of items each run.  I believe it defaults to 100 items.  The number is configurable from admin/config/search/settings.

The easiest way to force a reindex of an entire site is to use drush:

drush -y seach-reindex
drush -y seach-index

This will clear the index, and then index all unindexed items.  Be prepared, this can take a long time.

Sometimes, though, if you have some weird custom logic in the node load or field attach process, the search can get caught up.  When cron runs, the PHP timeout would eventually be hit.  When run from drush, you would see no progress running.