In Commerce 2, how can we allow users with a role to bypass payment during checkout (bill me later) We have a Commerce 2 site that we need to be able to assign users a role ('Bill Me Later') that will allow the user to select the payment option 'Bill Me Later' during checkout.

I have not found a module that provides this functionality. I started to dive into creating a custom payment processor but I'm not sure if this is the correct route to go. If the user were to select 'Bill Me Later' then no further information would be needed. The order would go through (completed) but now marked paid.

Could someone offer some insight into the best way to achieve this? We're open to building a custom payment gateway module if that is required but could use a little guidance as to get started since this technically is not a payment gateway.

You can enable the "Commerce Payment Example" module that comes with commerce2. From there on, go to commerce->settings->payment->payment gateways and add a new payment gateway. Choose the "Manual" plugin and set the proper roles on the bottom and you should be done.


Is it possible to add java script to webform? I would like to have a field in module webform that uses javascript f.e that

 <script type="text/javascript">

var geocoder, location1, location2, gDir;

function initialize() {
    geocoder = new GClientGeocoder();
    gDir = new GDirections();
    GEvent.addListener(gDir, "load", function() {
        var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
        var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
        document.getElementById('d1').value =+drivingDistanceKilometers;
        document.getElementById('twojadres').value = '' + location1.address;

    });
}

function showLocation() {
    geocoder.getLocations(document.forms[0].address1.value, function (response) {
        if (!response || response.Status.code != 200)
        {
            alert("Przykro nam, ale wpisałeś niepoprawny adres. Spróbuj ponownie!");
        }
        else
        {
            location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
            geocoder.getLocations(document.forms[0].address2.value, function (response) {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else
                {
                    location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

</script>

It use js to calculate distance between address which should be get from webform field.

An approach is to use hook_form_alter to alter the webform form and attach the custom JS.

/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'webformCustomID')) {

    $form['#attached']['js'][] = drupal_get_path('module', 'custommodule') . '/custom.js';
  }
}

More info:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7
Adding CSS and JS to form with attachments


Add to Cart Forms Buttons disables Boost Module Caching I've installed boost on my drupal 7 site with commerce setup. Boost is working fine, but any pages with a form, such as an add to cart form. It will disable boost caching. I need a way to ajax load these form buttons after the page is loaded so boost doesnt cache the forms.

What methods are there to solve this solution?

I solve the solution by using the following module:

https://www.drupal.org/project/commerce_cart_link

One issue I had to was getting these links to display in a Views output as this module turns the add to cart input fields into url links. There was no option in views to change this:

I did a work around to get this to work. Apparently you can just append the product id to the form of this link:

/cart/add/nojs/[product-id]/random-token-variable

I'm not sure what the token is for, but you can just put anything in there and it will still add it to the cart. It works for anonymous, but when your logged in, the link will hit you to an access denied page. I had to do the following to get it to work for authenticated users by commenting out 3 lines in commercie_cart_link.module:

I'm not sure what the token is for.


Creating a custom field module I am trying to create a custom field module for views, but I keep getting this error when I add the field to the view.

  SQLSTATE[42S22]: Column not found: 1054
  Unknown column 'views_report_state_field' in 'field list'

This is the code I am using.

views_report_state.info

name = Views Report State
description = Turns short abbreviated states (ex: TX) into fully readable names (ex: Tx = Texas)
package = Views
core = 7.x

files[] = views/views_report_state_field.inc

views_report_state.module

function views_report_state_views_api($module = NULL, $api = NULL) {
  return array("api" => 3);
}

views_report_state.views.inc

function views_report_state_views_handlers() {
  $handlers = array(
    'info' => array(
      'path' => drupal_get_path('module', 'views_report_state'),
    ),
    'handlers' => array(
      'views_report_state_field' => array(
        'parent' => 'views_handler_field',
      ),
    ),
  );
  return $handlers;

function views_report_state_views_data() {
  $data = array();
  $data['views']['views_report_state_field'] = array(
    'title' => t('CRF: Convert US-State Abbreviations'),
    'help' => t('Converts State Abbreviations to their full name'),
    'field' => array(
      'handler' => 'views_report_state_field',
    ),
  );
  return $data;
}

views_report_state_field.inc

class views_report_state_field extends views_handler_field {

  function render() {
    return "working!";
  }

}

views_report_state_field.inc

class views_report_state_field extends views_handler_field {
  function query() {
    // Query
  }

  function render() {
    return "working!";
  }

}


How to supply hidden field value to node based on webform? Using D8 to create a node based on a Webform named "White Paper". I have a hidden field on the webform named white_paper_title.

When creating a node based on this form, I've added the following in the Default webform submission data field, like so:

white_paper_title: 'something'

This works fine if I base the new node on Webform, and select "White Paper" from the list.

The problem is that it never works when I create a new content type based on the White Paper webform. When viewing the node in the browser, the hidden field is there, but the value is never plugged in. How do I get this working?

You can pass a field's value as a token to the webform.

You would need to add 'field_white_paper_title' to your webform node and then change the "Default webform submission data (YAML)" to

white_paper_title: [webform_submission:node:field_white_paper_title]


How to uninstall module if admin/modules path is not accessible due to memory error The problem is - I installed ubercart and was playing with devel module. Now when I'm trying to go to admin/modules I'm getting:

  Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to
  allocate 8642561 bytes)

I would like to uninstall devel module because I think this is its fault, but I can't as I don't have access to admin/modules because of this error :/ . Is there another way to uninstall a module and free some memory?

Edit: Well, turning off some options in devel settings helped, but still it would be nice to know answer to this question as problem can potentially appear for someone :) .

Use drush:

drush dis MODULE-NAME

You can also disable modules manually in the database:

UPDATE system SET status='0' WHERE name='module_name';

Then you need to clear cached system list (Drupal 7 only):

DELETE FROM cache_bootstrap WHERE cid='system_list'


How to form_alter fields attached to an unlimited field collection? Here are 2 unsuccessful experiments I've done:

<?php

/**
 * My first attempt with implementing hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          // None of these work:
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#default_value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#default_value'] = 'test';

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und']['#value'] = 'test';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['#value'] = 'test';

        }
      }
  }
}

/**
 * My second attempt implementing hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {
    // These don't work either:
    $element['field_SOMEFIELD']['#value'] = 'test';
    $element['field_SOMEFIELD']['#default_value'] = 'test';

    $element['field_SOMEFIELD']['und']['#value'] = 'test';
    $element['field_SOMEFIELD']['und']['#default_value'] = 'test';
  }
}

How can I alter the form API elements on fields attached to a field collection?

PS: The hook functions are running fine. The issue is that the form API values I set do not make any change on the loaded form.

Check the array to make sure you are using the correct names and structure.  You can use dpm() from the devel module to check this.

Both hook_form_alter or hook_field_widget_form_alter allow you to alter field collection child field form elements.

<?php

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'MYNODETYPE_node_form':
      foreach ($form['field_MYFIELDCOLLECTION']['und'] as $delta => $field) {
        if (is_numeric($delta)) {

          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';
          $form['field_MYFIELDCOLLECTION']['und'][$delta]['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';

        }
      }
  }
}

The following will also work:

/**
 * Implements hook_field_widget_form_alter.
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_MYFIELDCOLLECTION' && $context['instance']['bundle'] == 'MYNODETYPE') {

    $element['field_SOMEFIELD']['und'][0]['value']['#value'] = 'value';
    $element['field_SOMEFIELD']['und'][0]['value']['#default_value'] = 'default value';

  }
}


Change class on the div wrapper of a form element Is there a way to add or change a class to a form wrapper (the div's) using the form api?

Or is that just done with the theme function ?

If so which theme function is used to change that?

You can override theme_form_element() normally if you want to change the theming globally. If you're interested in modifying just one specific form element then I'm aware of a couple of choices.

You can register a new theme function for the particular type of form element you're interested in (eg. textfield). You then create this theme function (based on the original, eg. theme_textfield()) but that doesn't call theme('form_element', ...) at the end (you could either handle both the wrapper and the element in the one theme function, or you could make a separate wrapper theme function and use that). Finally you add a #theme property to a particular form element, and that element will get your custom theming.
You can create a template file called form_element.tpl.php which just has the default behaviour of theme_form_element() and then use hook_preprocess_form_element() to add a template suggestion. Then you create the new template that matches the suggestion. You often hear people mentioning that templates are slightly slower than functions, and for such a frequently used theme call I can imagine people balking at using a template. I've never done any measurements for this myself however. Also, you need to have enough context at the preprocess stage to be able to make the suggestion.


login destination redirect to previous page adding # The following code works for me to redirect the user back to the previous current page after he/she logs in.

 <?php
    print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination()));
    ?>

However, how can I add # to the previous current page?

For example, if the user was on /node/1 and go to the login page.
Then How can I redirect this user to /node/1#article_1 ?

(How can I add this #article_1? )

This can be done via

<?php
  print l(t('Please Log in'),'/user/login', array(
    'attributes' => array('title' => t('Log in page')),
    'query' => drupal_get_destination(),
    'fragment' => 'article_1'));
?>


how to set a node to anonymous author? Change node author works :
$node = \Drupal\node\Entity\Node::load($nid);
$node->set('uid','45');
$node->save();

But i don't know how to set it to anonymous user ? or unset it ?
 $node = \Drupal\node\Entity\Node::load($nid);
 // set uid to anonymous ?
 $node->save();

$node->set('uid', 0); $node->save should have worked. Maybe you forgot to flush caches.
To programmatically set the author to anonymous user on any entity you can call $entitiy->setOwnerId(0); and then $entity->save();, done.
$entity->setOwnerId(0);
$entity->save();


hook_theme not being called in module I'm working on a module that has a custom output for the form that's being called, and this form has multiple pages. The multiple page part is being called correctly, but I can't get the theme to render the form.

I've got the following code:

<?php

// Page callback to render the form
function mymodule_main() {
    return drupal_render(drupal_get_form('mymodule_form'));
}

// Picks which form to call
function mymodule_form($form, &$form_state) {
    drupal_set_message('Picking form to use');
    if(!empty($form_state['page_num']) && $form_state['page_num'] == 2) {
        drupal_set_message('Form 2');
        return mymodule_form_two($form, &$form_state);
    } else {
        drupal_set_message('Form 1');
        return mymodule_form_one($form, &$form_state);
    }
}

// Form definition for the first page
function mymodule_form_one($form, &$form_state) {
    return array(
        // ...
        '#theme' => 'mymodule_theme_one',
    );
}

// Hook theme call
function mymodule_theme() {
    drupal_set_message('Hook Theme has been called');
    return array(
        'mymodule_theme_one' => array('render element' => 'form'),
    );
}

// My custom theme for the first page
function theme_mymodule_theme_one($vars) {
    drupal_set_message('Theme for first form has been called');
    // Code to style the form
    return $output;
}

In the theme_mymodule_theme_one function I move some of the form definition things around, unset some variables for output, etc. When I visit my page I defined in my hook_menu() call I get the form I defined in mymodule_form_one but without any of the work done in theme_mymodule_theme_one and I only get the following two messages:

Picking form to use
Form 1

I don't see any of the other messages.

Edit

I've cleared the cache manually as well as disabled and re-enabled the module and the theme code still is not being called.

The only thing you should need to do is clear Drupal's cache; hook implementations are cached so once you've written the function you need to clear the cache to get the new data into the registry.

One other small thing, you probably shouldn't be returning an array like you currently are from your form builder function.

I'm pretty sure Drupal sets up the $form variable it passes into the function through drupal_get_form with some required details, so returning an array (and not the original $form element) will probably mean your return from the function is missing something. The usual way would be to do it like this:

function mymodule_form_one($form, &$form_state) {
  $form['#theme'] = 'mymodule_theme_one';

  return $form;
}


Auto delete temporary files after 15 seconds of creation The default setting given to delete temp files is after 6 hours minimum. I have users upload files and I want that if it has temp status, delete it after 15 secs. Tweaking the file module code is risky, if I get the exact location to change 6 hours to 15 sec that will do the job.

The value stored in this config
\Drupal::config('system.file')->set('temporary_maximum_age', '15');

You can update that with the value you wants.
If you want to change the form as well which is recommended use hook_form_FORM_ID_alter to adjust the system file settings from system_file_system_settings
The current implementation looks like this
$intervals = [0, 21600, 43200, 86400, 604800, 2419200, 7776000];
$period = array_combine($intervals, array_map([$this->dateFormatter, 'formatInterval'], $intervals));
$period[0] = $this->t('Never');
$form['temporary_maximum_age'] = [
  '#type' => 'select',
  '#title' => $this->t('Delete temporary files after'),
  '#default_value' => $config->get('temporary_maximum_age'),
  '#options' => $period,
  '#description' => $this->t('Temporary files are not referenced, but are in the file system and therefore may show up in administrative lists. Warning: If enabled, temporary files will be permanently deleted and may not be recoverable.'),
];

You can alter the form and adjust it to what you want.
Keep in mind, to see this happen your corn must run at least every 15 sec.


How do I load specific page template for /store-locator I want to control the region the store locator and panel being placed into. I was hoping I could just use a content-type page .tpl to move things around within the rest of the layout, but that doesn't seem to be working.

After trying it and it not working I'm guessing all that would do is change the display of the actual "/name-of-store" path and not the sitename/store-locator path.

Store Locator seems to be an odd duck. I can't find anything in the code that would point to a tpl file. It certainly isn't a view in a block since it's basically being rendered in the primary content area of my standard tpl file.

My first wish is to have a separate page.tpl so I can get all the parts of pieces of the page where I want them. Being that it looks like all the code is generated in JS, I can't even think of a way load that into a view and then but the view in a panel layout that's full width.

Any thought on what the page tpl needs to be and what the right theme hook would need to be in preprocess? This is what I have working for my other hinting for page tpl's.

  if (isset($variables['node'])) {
  // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $variables['node']->type);
  }

There are many possible ways to solve this problem.  My suggestion, however, would be to use the Page Manager Existing Pages module.  This module will let you easily override the callback at that URL and place the content for the page in any region of your Panels layout.

If you want to do it the same way as you've been doing it for other pages, then there will already be template suggestions automatically provided for you, derived from the path.  So if the path to the item is sitename/store-locator then the template suggestions that will already be automatically created for you are page__sitename and page__sitename__store_locator.  You need only to create those tpls.

That said, I'd still generally recommend the PM Existing Pages module for this type of functionality.


How to save entity from a ajax form I'm running Drupal 8.8.x

The Problem

Entity is not being saved when form is submitted through AJAX. Example:

Build Form

public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $entity = NULL) {
  if($entity) {
    $this->entity = $entity;

    $form['element'] = [
      '#type' => 'textfield',
      '#title' => $this->t('My title'),
      '#name' => 'element',
      '#ajax' => [
         'event' => 'focusout',
         'callback' => [$this, 'myCallback'],
         'disable-refocus' => TRUE
      ]
    ];
  }

  return $form;
}

Submit Form

public function submitForm(array &$form, FormStateInterface $form_state) {
 $element = $form_state->getTriggeringElement()['#name'];
 $value = $form_state->getValue($element);

 $this->entity->set($element, $value);
 $this->entity->save();
}

I've confirmed $element and $value are the correct key and value. However, when I save the entity nothing happens. There is nothing updated in the database. And there are no errors emitted in the console or watchdog.

If anyone knows what could be the issue I'd appreciate some insight! :)

Drupal 8 doesn't cache Ajax forms anymore, so you can't get properties of the form object set in the initial form build. see Bypass form caching by default for forms using #ajax.

Forms are only cached as rendered form. Put the entity id in a hidden form element to load the entity before saving. Add the entity cache tag to the form if you use default values from the entity.

Or consider to switch from a general Form API form to an entity form.


How to preserve form values for user who navigates out of form and back? I have a form that works, essentially, as a search / filter:

 foreach($search_properties as $property) {
    $form['properties'][$property->idProperty] = array(
      '#title' => $property->Label,
      '#ajax' => array(
        'callback' => 'mymodule_filter_ajax',
        'wrapper' => 'category-filter-result',
        'method' => 'replace',
        'effect' => 'fade',
      )
    );
    switch ($property->PropertyType) {

Options are generated by taking only actually used values from possible ones:

  '#options' => array_intersect_key($possible_choices, $used_values),
  '#default_value' => array_keys($used_values),

Nothing interesting here, really, just set of fields that, on change, reloads a list of links using AJAX. Never submitted, never saved.

Problem is - when user clicks on a link, and then clicks browser's "back", all fields have their defaults selected again.

I'm under impression that it was not the case with Views exposed filters. I think I remember these filters was able to keep values when user went back to them. So it is possible.

What is the Drupal way to keep user-selected values in the simple scenario of a link click, and then browser's "back" button?

I'm not aware of a specifically Drupal way to do it.

As I say, I find that if I fill out a form, don't submit, click a link, and then click back, the form elements are still populated, unless perhaps there's some AJAX/JS funkiness going on with them (the actual form elements). However a little digging suggests that's browser-dependent and won't work in certain situations (eg. over HTTPS). I'd love to know more about this behaviour.

I think ideally you'd use JS to put the data in the URL. If you don't need to support older browsers then you can use the History API (not that I ever have...) which would allow you to separate arguments in a more Drupally way: eg. path/arg1/arg2/arg3. Otherwise the traditional window.location.hash can be used instead.

You can use the session variable like Views, which is more flexible and simpler to implement, but can cause anonymous users to bypass caching.


How to perform automated testing of an entire site after core changes? I'm looking for a module which will test an entire site with each OS update, or Drupal core update. E.g. go through each node and let me know there are any 404 returned for JS or CSS files, broken links, any white screens of death, etc. And if possible if the response time of the site has drastically decreased.

I've done some search and can I only see references to SimpleTest used or unit testing. I'm looking at using Selenium at the moment.

How are other people testing sites after a core changes?

http://drupal.org/project/simpletest - it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:

http://drupal.org/project/selenium
http://drupal.org/simpletest


How to split Views exposed filters into separate blocks I would like more flexibility of my exposed filters so styling and organization can be better.

I will be using 3-5 exposed filters and rather that oranizing them by CSS only i thought it would be nice to have each one in separate blocks.

My reason for this is to display filtering options the way most are use to, Ascednig/descending and small to large(or cheap to expensive) up top fairly small

and on the left side a detailed selection of sub category options (size, brand etc...)

If there is a better solution im all ears.

Im using:
- Drupal 7
- Views 7.x-3.8
- better exposed filters

The MEFIBS - More exposed forms in blocks module provides this functionality.


Why can't I find my uploaded file on disk? I have a form with a file upload widget:

$form['myFile'] = array(
    '#tree' => false,
    '#type' => 'file',
    '#title' => t('Choose a file')
);

In the form validation handler, I upload the file and validate it with:

$validators = array(
    "file_validate_extensions" => array(variable_get("allowed_extensions")),
    "file_validate_size" => array(variable_get("max_image_size"))
);
$file = file_save_upload('myFile', $validators);
$form_state['file_storage']['myFile'] = $file;

Then, in the submit handler, I save the file using:

$file = $form_state['file_storage']['myFile'];
file_save($file);

This seems to work fine as I can find an entry for the file in the file_managed table:

+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+
| fid | uid | filename     | uri                         | filemime   | filesize | status | timestamp  |
+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+
|  49 |   1 | download.jpg | temporary://download.jpg    | image/jpeg |     5410 |      0 | 1350312114 |
+-----+-----+--------------+-----------------------------+------------+----------+--------+------------+

The problem is that I can't find the file anywhere on disk:

$ su -
Password:
# updatedb
# locate download.jpg
/home/me/Pictures/download.jpg

As you can see, the only download.jpg found is the one in my pictures folder which I passed into the form. I can't find anything on the server (in /var/www/). So where is the file? Is it a BLOB in the drupal database? Has it simply not been uploaded properly? If so, what did I do wrong?

You're just missing the third parameter for file_save_upload():

  $destination: A string containing the URI $source should be copied to. This must be a stream wrapper URI. If this value is omitted, Drupal's temporary files scheme will be used ("temporary://").

The uri in your table is temporary://download.jpg which seems to support that.

To save your file in the public file system you just need to pass that parameter in:

$destination = 'public://some/folder/';
$file = file_save_upload('myFile', $validators, $destination);


How to apply a Views filter to show fields if a radio button is not FALSE? I have a custom field that is a radio button (from CiviCRM), and I made it available as a filter by implementing hook_views_data().

I'd like to apply a filter to show fields if the radio button is set to true; in other words, if not == false.

I feel like this should be possible without using the Views PHP module, but I have hit a wall.

Often these kind of things come back to deciding how best to bend your requirements to suit the available logic. If I understand correctly, you have a radio button with the value of true, but no other options.

My immediate thought is to change it from a radio to a checkbox and set a default value as false (unchecked).

That way you just need to check for if true or if false and you don't need to concern yourself with if not false which does get tricky.


How to reorder nodes in Drupal 7 using Drag and Drop feature? Can anyone please help me that, how I can reorder the nodes in Drupal 7 using drag and drop feature?

Create a view to list your nodes and use Drupal draggable views module to order your nodes.

  From the documentation page,

  Order any type of entity
  Set different order for different set of arguments
  Create one view that sets the order, and create as many views as you like that shows that order
  Use core tabledrag.js or jQuery UI draggable javascripts to set the order

Steps to use this module and views to order nodes:

Download draggable views and views module and enable in your site.
Create a view to list your nodes say field will be node title and choose Format as Table.
Add draggable fields as additional field in Fields section. You can use submit as well as ajax submit once you ordered your nodes.
Add Draggable weight as ascending order in sort criteria.

Save the view and view it in the page.
My list will be like this:

Drag and drop the pointer to order the nodes and hit submit.


How to add scroll bar to views titles I created a views block to display the titles of nodes. I placed the block in the left side region. In order to see all the titles, I need to scroll down the page. Instead, I would like to add scroll bar to the views titles so I can simply scroll the bar to see the titles. How can I do it?

You will need some css to do this task. Pick a class from view content html and fix its height and set overflow-y property to scroll. Example snippet below -

.view-content{
    height: 50px;
    overflow-y: auto;
}


Pass $form and $form_state as arguments in hook_menu I have a javascript code below:

$.ajax({
    type: "POST",
    url: "?q=myid_print/update_table",
}).done(function(o) {
    console.log(o);
});

It calls a function declared in my hook_menu:

function myid_print_menu()
{
    $items = array();
    $items['myid_print/update_table'] = array(
        'title' => 'ID History',
        'page callback' => 'myid_print_all_submitted_id_callback',
        'type' => MENU_CALLBACK,
    );
    return $items;
}

Below is the function being invoked:

function myid_print_all_submitted_id_callback($form, &$form_state){
    watchdog('myid_print', 'Wow');
    return $form['table'];
}

After looking at my drupal's database, particularly in watchdog table, I saw the message Wow, which indicates that the function myid_print_all_submitted_id_callback has been called but my $form_table is not updated. The obvious reason behind this is I did not pass an argument $form and $form_state. Then, this is what my question is. How will I pass $form and $form_state arguments? Or any way that I could render $form_table invoke by javascript?

If you're using Drupal's form API, it already has support for AJAX built into to it via the #ajax property. For example....

function MYMODULE_example_form() {
  //@TODO: various form elments...

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

function _MYMODULE_example_form_submit($form, &$form_state) {
  //@TODO: process submitted form
}

The examples module has more examples of this if you'd like to see more of it in action.


How to get taxonomy term field values I have created vocabulary "Hospital" and created text and image fields like:

Hospital Image: (machine name: field_hospital_image) // image field
Hospital Contact: (machine name: field_hospital_contact_no_) // text field

My code is:

$vid = 'hospitals';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
  $term_data[] = [
    'tid' => $term->tid,
    'tname' => $term->name,
    'image' => ...???..,    // image field
    'contact' => ...???..,  // text field
  ];
}

Please suggest namespace also.

I alsready tried :

'contact' => $term->get('field_hospital_contact_no_')->getValue(),

and

'contact' => $term->get('field_hospital_contact_no_')->value,

Errors:

  Error: Call to undefined method stdClass::get()

Term object is not loaded with loadTree by default a basic php object is loaded instead.

You have to load the term object for each term using $term_obj = Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid);

Your code should look like this

$vid = 'hospital';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
  $term_obj = Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid);
  $url = "";
  if(isset($term_obj->get('field_hospital_image')->entity)){
    $url = file_create_url($term_obj->get('field_hospital_image')->entity->getFileUri());
  }

  $term_data[] = [
    'tid' => $term->tid,
    'tname' => $term->name,
    'contact' => $term_obj->get('field_hospital_contact_no_')->value,
    'image_url' => $url,
  ];
}

NOTE: Alternatively you can also use loadTree($vid, 0, NULL, TRUE) to load the entities directly on the $terms array but perhaps it should be avoided on very large vocabularies.  More info on the loadTree method


Ho to add mixed multiple fields in a node I'm searching for a way to add unlimited amount of multiple mixed fields in a node.

In few words there is such a situation: let's say, I have a content type with fields "picture" and "text", and for both of them "number of values" is set to "unlimited", which lets user to add unlimited amount of photos and unlimited amount of text blocks.

What I want to achieve is that content editor could mix those two fields together, like it is possible to change places of entries of one field. The example of entry could be like this:

editor is adding a block of text, then a picture, then another picture, then again a block of text, etc.

The problem is that it is not clear what could be the amount of these elements and their sequence may change depending on circumstances.

I know that it is possible to do this with Views, but that makes the work of editor much more complicated and he/she cannot see the "full view" at the same time, so maybe it is possible somehow to merge two types of fields?

Have you looked into Field Collection module ?

Provides a field-collection field, to which any number of fields can be attached.
A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

It allows to combine multiple fields and treated as a single field.
Here is the doc.
Hope it helps.


How to make taxonomy terms link to an external site? I am using the Lexicon module to automatically insert links to a vocabulary with information about words in the lexicon.

But the vocabularies I am using are owned and hosted by a completely different organisation, which means that hosting the information on my website would result in duplicated and outdated information. Therefore I need to link my terms in the taxonomy to an external site (instead of this website).

I tried using the Redirect module but it doesn't manage tokens to external websites.

My question: how to make my taxonomy terms link to an external site?

Solving this issue for me required three modules:

Link module: Creates a link field for external links. Module page
Lexicon: A module that look for keywords and allow you to set up a lexicon that automatically link keywords to a page explaining them. Module page.
Field Redirection: A module that allow you to create pages that automatically redirect the user to a different page. Module page.

Install the modules and activate them.
Go to Manage fields of the vocabulary you wish to use for external links (structure-->taxonomy-->[your vocabulary]--> Manage fields). Add a link field to the vocabulary and set it's format to "redirect" (this is described in the documentation of the Field Redirection module).
Go to Manage display and hide all other fields (also according to FR module instructions).
Now it is time to set up the Vocabulary. Go to configuration-->system-->lexicon settings. Under the General tab, check "Link terms to the taxonomy term page" and uncheck the options that will make several terms appear on the same page (field redirection will otherwise always redirect to the link associated with the first term on the page).
Link targets are edited for each term in the taxonomy and you add the URL in the "Link" field of each term.

Lexicon is the module you interact with to make the links appear as you want them and any issues will probably be caused by improper setup of the Lexicon. Links/Redirect Field are a small add on that transport users to external websites instead of the lexicon page created by the Lexicon module.


How can I update an user field via JSON:API? How do I update user field via JSON API with D8?

EndPoint:https://domainname.com/jsonapi/user/user/

Method:PATCH

Request Header;

Accept:application/vnd.api+json
Content-Type:application/vnd.api+json
X-CSRF-Token:xxxxxxxxxx

Body:

"data": {
        "type": "user--user",
        "id": "xxxxxx-7798-45e5-a16c-xxxxxxxxxxxx",
        "attributes": {
            "field_test1": [
                "data1",
                "dara2"
            ]
        }
    }

But below error

        "title": "Method Not Allowed",
        "status": "405",
        "detail": "No route found for \"PATCH /jsonapi/user/user/\": Method
        Not Allowed (Allow: POST, GET, HEAD)",

You need to also put UUID in your request URL, so it should look like
EndPoint:https://domainname.com/jsonapi/user/user/xxxxxx-7798-45e5-a16c-xxxxxxxxxxxx


The standard method for adding css classes to twig templates What is the standard method for adding classes in twig template?
I'm going straightly to the main subject point:

Scenario-1:
I have some classes and I want to collect them in a group and add this group to the existing group that added before:
I try below code but it seems that something is wrong.

{%
  set classes = [
    'block',
    'block-' ~ configuration.provider|clean_class,
    'block-' ~ plugin_id|clean_class,
  ]
%}

{%
  set my-classes = [
    'class-name-1',
    'class-name-2',
    'class-name-3',
    'class-name-4',
  ]
%}
<div{{ attributes.addClass('classes my-classes') }}>

What tips should I consider for a class group name, For example, Is it important to follow PHP variables name convention, Can I use hyphen character in class group names?

Scenario -2:
I have few classes names and I want to add theme straightly to default added classes, like below:

views-view-unformatted:

<div {{ row.attributes.addClass(row_classes 'class-name-1 class-name-2') }}>

Your variables classesand my_classes are arrays. You could merge them:

{{ attributes.addClass(classes, my_classes) }}

Or add them one by one:

{{ attributes.addClass(classes).addClass(my_classes) }}

Or merge an array constant directly:

{{ row.attributes.addClass(row_classes, ['class-name-1', 'class-name-2']) }}

Or single classes:

{{ row.attributes.addClass(row_classes, 'class-name-1', 'class-name-2') }}

According to the coding standards https://twig.symfony.com/doc/2.x/coding_standards.html you should use underscores in variable names.


How to (truly) alter a URL in Drupal 8 I'm using OutboundPathProcessorInterface. I notice a few odd things about its behavior.

In adding, for example, "/x" to the path, it works in some cases, like admin/structure, but not others, like admin/content or the path I'm interested in, which is defined in a view. This is despite my setting the module's weight to 999 in its install file (before installing), so presumably no other module would be altering the path downstream.
Where it does work, such as admin/structure, the page with the original path loads, with the original URL in the address bar, but all menu links have the altered path.
When I watch it in xdebug, AFTER I alter the path with the query string in $options the URL comes through the function again, with the path set to the original value.

The module weight won't do anything here. You set the priority in the service tag.
You have to look what other path processors do at which priority to find the right place for your custom code. And use an inbound path processor to remove the x you have added outbound.
The outbound processor is called multiple times while building a page, because you usually have more than one link on the site (and not all are visible).
(question in comments) You can do this, outbound transfer query parameters to the path and inbound transfer parts of the path again back to the query parameters. Internally Drupal sees only the short base path with query parameters, externally you see the full path without query parameters. An example for inbound is PathProcessorFiles::processInbound


Condition on $user_storage I am using the following code.

  $user_storage = \Drupal::service('entity_type.manager')->getStorage('user');

    $ids = $user_storage->getQuery()
      ->condition('status', 1)
      ->condition('roles', 'directeur_cr_')
      ->execute();
    $users = $user_storage->loadMultiple($ids);

I want to add a condition that is verified when the role is directeur_cr_ or comptable_cr_.

How can I add this condition?

You can use orConditionGroup, but the IN operator is a shorthand for OR conditions on the same field:

->condition('roles', ['role1', 'role2'], 'IN')


Add field to login block in drupal 7 I am trying to add a custom field to the user login block in drupa 7 for the zen theme. That is, in addition to the username and password fields, I need another field called code. Most of the available documentation on the net is targeted at drupal 6. From what I've read, the template.php file and the block--user--login.tpl.php files need to be modified for the particular theme. Is this right? Also, what functions need to be modified/added?

Any help appreciated.

Drupal forms don't reside in any particular template. They are defined in the code. When a form is displayed, the code is read, it is then made available for modification by other modules before being rendered by a function called drupal_render() this will then use various template files to build the form which its displayed to the user.

It is fairly simple to add a field to the login form using hook_form_alter().

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register') {
    $form['myfield'] = array(
      '#type' => 'text',
      '#title' => t('code'),
    );
  }
}

What is perhaps more tricky is deciding what to do with this, are you using it for a second form of authentication?

A final note is on where to put the code. Drupal is fairly flexible, in that you can put theme files in modules and functionality in themes. However best practice is to keep features in modules, it leeds to a more manageable system in the long run.


EntityMalformedException: Missing bundle property on entity of type node I'm doing a drupal 7 website, I've now started to experience a "EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7820 of C:\xampp----\includes\common.inc)." error whn I try to view a node in full view mode and only if I'm logged in as administrator.

This is happening here:

if (!empty($info['entity keys']['bundle'])) {
// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  var_dump($entity);
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

I found some pages about this error but none seems to apply to my case. I put a var_dump just before the instruction throwing the exception and all I get is bool(false). I've checked all the bool fields of the node and they all have #bundle correctly set.

I think the problem might have started after installing the database optimization module. I found some information regardin this error and clearing the form_cache but I didn't understand if this can apply to my case.

I guess these hints are enough to trace the problem for a drupal expert, unfortunately not for me.

Any suggestion? Thanks


How to format a custom field excuseme if this question can (seem to) be stupid, but I don't figure how to solve...

Shortly, my custom module:

exposes a node type
exposes an entity type
attach to that node a field containing a set of these entities (by using entity_reference)

I would like to customise how those entities are visualised in the node view page: I would like to show more info instead of just the entity label.

I read something about hook_field_formatter_info(), that seems to be the best solution, but my debugger suggests that is not invoked (neither after a cache clear)... on the other I can't find any info about how to explain this to hook_theme().

The ideal behaviour should be to tell to Drupal:

use a specific template file to render all fields belonging to a given field instance
allow a theme to override that representation in a new template file

Do you have a snippet of code or a web resource explaining how to instruct my module to do this?

Thank you

hook_field_formatter_info() hook lets Drupal know about the new display denfinition and field settings, you will see your display type under Manage display settings of your content type. However the actual format of the field is returned with help of hook_field_formatter_view.

Example Code


Author information lost after saving node I am developing a site using Drupal 6. Sometimes, when I edit and save a node, the author information is lost and the node is unpublished.

Some observations:

When I edit the node again, even with the user 1 account, I no longer get the node publication controls on the edit form.
In the content overview admin page, the column for author is empty, not 'anonymous'.
I can force-publish the node again using bulk operations, but not via the edit node page. I cannot seem to restore the/a author for the node.

I have not yet been able to reproduce this problem consistently: it happens on various node types, only sometimes, regardless of using tinyMCE or filtered HTML for content.

It does seem to happen only on edit, not create. I have not recently enabled or disabled any modules.

Has anyone else experienced something similar? Any idea as to what might be causing this?

That sounds strange and like a sideeffect. I would try do debug this using the devel-module. Write a Module and print (with dsm) the $node inside hook_nodeapi. Inspect the content in subject to the operation ($op). Maybe do this two times with diffrent module weights (-1000, 2000) to see if any hook_nodeapi implementation of another module fails.


How to add link around each rows in views? I have article' views with fields like this:

Content Image

Content Date

Content Title

Link to content

I can access to article by my link but I want to render clickable all of row to link .

This is my views-view-unformatted.html.twig file:

{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
 {%
   set row_classes = [
    default_row_class ? 'views-row',
  ]
 %}

   {{ row.content }}

{% endfor %}

and I think I want this:

{% if title %}

{{ title }}

{% endif %}

{% for row in rows %}
 {%
   set row_classes = [
    default_row_class ? 'views-row',
  ]
 %}

 <a href="path to node"

   {{ row.content }}

{% endfor %}

But I don't know how it's possible. Any known workarounds?

Sounds like it would be easier to create a View Mode for this. Add a View Mode under Admin > Structure > Display Modes, arrange the fields and configure their formatters. Then if you need to, create a node--node_type_name--view_mode_name.html.twig template to get the markup you want.

Back in the view, change the output to rendered entity, and select your new View Mode. This reduces complexity when it comes to displaying views that are basic entity fields, because that all happens in the View Mode configuration now instead of dealing with views fields and overwriting and theming.

In your new node view mode twig template, wrap your fields and use the appropriate twig function to wire it up:

https://www.drupal.org/docs/8/theming/twig/functions-in-twig-templates

So, something like:

    // all node content fields + markup here
    {{ content|without('comment', 'links') }}

Also note that your twig file name for the unformatted view will (I believe) affect all views using the unformatted display. You likely don't want that.


How to get statistics of (internal) referrers for landing pages? I'm building a Drupal 7 site. Here's a use case that I'm not sure how to deal with:

for a campaign, we have a specific landing page.
we promote the landing page through different means (newsletter, flyers, website).
we want to track the effectiveness of each promotion.

As a sample, I have mydomain.com/mylandingpage?promoId=[n] and I want to track how many people accessed that page through promoid=1 vs promoid=2.

I do not necessarily have a form on the landing page, i.e. knowing how many users submitted a form after seeing a promotion is a different use case (and one that can be solved with a hidden form field).

How can I get statistics for what I need? The only thing I can think of is making special redirect URLs for each promo, e.g. mydomain.com/mylandingpage/promo1, but that would become messy/cumbersome very soon.

I'm aware of Google Analytics, but I'm looking for an internal solution.

Any ideas?

To answer this question, there are basically 2 approaches possible, as further detailed below (you might want to combine them also ...).

Option 1: Use the Rules module

You can use the Rules module to trigger "some" Rules Actions, based on the actual value specified as your promoid. Use either of these modules to trigger Rules Events based on the 'current URL being viewed' (quotes are from their project pages):

Rules URL Argument:

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

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

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

Path Rules:

  ... implements Rules conditions for checking the URL against a given string for triggering actions.

What the actual Rules Actions should be, is up to your own imagination, but here are just a few possibilities (rather basic, but straight forward to implement using the Rules module):

Perform a redirect to some URL, specific to each promoid (and then you just count the hits for each of these URLs).
Send an eMail each time you have a hit, whereas the content of the eMail somehow reflects the value of your promoid, and/or you use a different eMail ID to send such eMail to, based on that value.
...

Option 2: Use a typical module about statistics

Below is a list of modules to pick from (quotes are from their project pages).

Statistics Advanced:

  Provides a few advanced options to the core Statistics module.

Visitors:

  Displays information about visitors, and integrates with the WhoIs Lookup module

Better Statistics:

  introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.

Piwik Web Analytics:

  Adds the Piwik web statistics tracking system (free open source) to your website.

  Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.

Chartbeat:

  ... to provide third party integration with Chartbeat, for real-time site monitoring statistics.

Stat Counter:

  ... provides an integration between Drupal and StatCounter web statistics.


SMS Reminders for Course Signup module I am using Drupal 7 version of Signup module. It send email reminders before the course starts X number of days. Is it possible to send SMS reminders using another module. If not then where i should be looking in the code ?

thanks

You can use any sms integration api. I personally like Twilio.

There is a module for twilio integration as well: link

You will need to find a place from where the email has been sent, it would be in the code or possibly through Rule module, in either case you need to add a line of code which should utilize twilio api and send sms to the destined users.


Remove "Comments" title section from node template in my node.tpl.php i have this line:

<?php echo render($content['comments']); ?>

It works, but before comments I have a <div> with the text "Comments". I think that it is the section titles. I don't want it. Is there a possibility to remove it before "render" or I need to hide it via css ?

M.

You can hide it via css or you can change the tpl file:

Look for the comment-wrapper.tpl.php file in your theme. If it doe not exist there, you can copy it from the modules/comment folder into your theme folder. Edit the file and remove the line:

<?php print t('Comments'); ?>


how to change the url based on region and language selection in drupal 7 I have five different regions and five different language. When loading my site url like
domainname/regionname/langname .When user change the language or region url will be  change selected region name or language.how can i done this drupal?

You can change language based on such parameters (I am not at the position to check at the moment) under /admin/config/regional/i18n


working with drupal project with team Till this date i was working all alone on drupal projects.  Now i am into a team of 10-15 members. They are using common DB on a machine and different code base on each machine. So was wondering which is the best way to manage and work on drupal project when in a team ?

Any control version tools: GIT, Mercury, SVN and etc for controlling team source.
Also drupal have prepared version of drupal installation for team working for tracking timelines, bugs, etc:
Drupal used as a project management tool
More version controlling tools reviewd here: http://www.smashingmagazine.com/2008/09/18/the-top-7-open-source-version-control-systems/

And there's many ready services (free or usually payment) for working with team in internet, try this search: http://www.google.ru/search?q=project+management, there I see basecamphq.com for example.

More hard thing is DB synchronizing, because it's depend on your tasks, for example, sometime merging portion of content and users are needed, sometime aren't. Some of system variables should be synchronized, some of these not. Some content type or fields are required, some just for test.

Hard solution is writing script (manual) in any language that have access to DBs and track changes.
Other solution is using Features module with some contributed, like Strongarm and etc. This module create module that have changes, where developers export their changes, so it can be controlled via Version control tools as usual plain file. You will just enable it, and their changes will applied to central site. Also with this (and not only) cool tool used: Drush, for me this is the best solution.
Also there's tools of synching depend on DB engine, Best tool for synchronizing MySQL databases for example.


Drupal 8 : Add Product SKU as search filter for Orders view of the Commerce module I like to achieve below solution using Drupal configuration instead of code.

The commerce module has been installed for one of our Drupal CMS site. In the admin interface there is an Orders view for the Commerce module. This view basically shows all orders placed by users on the website.

Within this view I like to add Product SKU field as one of the search filter. I noticed SKU field exists in the Product variations table that is child table of the Products table. And Product table is linked to Order Item table. And Order Item is the child table of Orders table. This is something I checked on the MySQL DB database table relations otherwise I don't know how to find our such relationships from Drupal admin interface.

I went to EDIT section for the Orders view. Then clicked on Add button for Advanced >> Relationship but can't find find any product or product variation entity there. So not sure how to achieve the solution of my problem?

Can you please help?

Looking forward to getting your reply.

Thanks - Hitesh

Ok you all most did it !

first in the view  you need to add the "Order item referenced from order_items" relationship

in your view ->advanced RELATIONSHIPS...

after this you can then add the "Product variation" relationship.

with the 2 relationships added to the view you can now add the exposed filter you require.


Migrating a field collection with a field that has multiple values I have a field collection migration that is taking nodes of type Map List from a D6 site which have two fields, a title, and a node reference to entity of type Venue.  There anywhere between 1-10 node reference fields on any given Map List.

The Map List nodes are to be migrated to a field collection on the D7 site called field_city_map_list which lives on the D7 nodes of type City.  On the D6 site the Map List nodes were referenced on the old City content type via entity reference fields.

With the query and sourceMigrations set I was able to get the field collections to be attached to the correct City node in the D7 site, however in the case where a Map List has multiple node reference fields, the migration creates a single field collection for each node reference.

So where field_city_map_list should have several lists, with multiple node references like this:

CityNode->
  Title: Some Title
  City Map Lists:
    Some List Title 1:
      345
      677
      987
    Some List Title 2:
      876
      678
      908
    Some List Title 3:
      493

It actually gets imported like this:

CityNode->
  Title: Some Title
  City Map Lists:
    Some List Title 1:
      345
    Some List Title 1:
      677
    Some List Title 1:
      987
    Some List Title 2:
      876
    Some List Title 2:
      678
    Some List Title 2:
      908
    Some List Title 3:
      493

I thought ordering the query by the map list nid and then by the delta in the field venue nid list would solve the issue but it didn't change the migration results at all.  There are no errors or migration messages that appear.

Here is my class:

class FCMapList extends myFieldCollectionMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->systemOfRecord = Migration::DESTINATION;

    $this->description = t('Field Collection: Map List Nodes');

    $dependencies = array(
      'VenueProfilePage',
      'City',
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('default', 'legacy')
      ->select('content_type_map_list', 'ml')
      ->fields('ml', array('nid', 'field_link_title_value'));
    $query->join('content_field_venues', 'v', 'v.nid=ml.nid');
    $query->fields('v', array('nid', 'field_venues_nid'));
    $query->join('content_field_lists', 'l', 'l.field_lists_nid=ml.nid');
    $query->fields('l', array('nid'));
    $query->orderBy('ml.nid');
    $query->orderBy('v.delta', 'ASC');
    $query->isNotNull('v.field_venues_nid');

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationFieldCollection('field_city_map_list', array('host_entity_type' => 'node'));

    $this->addFieldMapping('host_entity_id', 'l_nid')
         ->sourceMigration('City');
    $this->addFieldMapping('field_list_title', 'field_link_title_value');
    $this->addFieldMapping('field_venues', 'field_venues_nid')
         ->sourceMigration('VenueProfilePage');

    $source_key = array(
      'nid' => array(
        'type' => 'int',
        'description' => 'List content ID',
        'alias' => 'ml'
      )
    );

    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFieldCollection::getKeySchema());

     }
}

I had found a similar question that was self-answered however as I said above, ordering by source node nid and field delta did not solve the issue.

I'm on migrate version: 7.x-2.6-rc1+57-dev and field collection version: 7.x-1.0-beta7

The only way around the issue I could find was to remove the map of D6 node reference field to the D7 entity reference field.  Instead I set a default value to 1 so that it appears on the field collection in the prepare function, and I then repopulate it with a secondary query there.  This solution was not ideal for me, but due to time constraints I was forced to go with this way.  Hopefully someone can find a real solution to the issue.

One more issue I found while attempting to debug this behavior was that rolling back this field collection migration did not delete the field collections.  It only reset the map messages and numbers of processed rows.  To delete the field collections entirely I had to roll back the migration of the nodes they were on as well: drush migrate-rollback City && drush migrate-rollback FCMapList

class FCMapList extends myFieldCollectionMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    $this->description = t('Field Collection: Map List Nodes');

    $dependencies = array(
      'VenueProfilePage',
      'City',
    );

    $this->dependencies = $dependencies;

    $query = Database::getConnection('mig_dest', 'legacy')
      ->select('content_type_map_list', 'ml')
      ->fields('ml', array('nid', 'field_link_title_value', 'field_link_subtitle_value'));
    $query->join('content_field_lists', 'l', 'l.field_lists_nid=ml.nid');
    $query->fields('l', array('nid'));
    $query->isNotNull('ml.nid');
    $query->isNotNull('l.field_lists_nid');

    $this->source = new MigrateSourceSQL($query);

    $this->destination = new MigrateDestinationFieldCollection('field_city_map_list', array('host_entity_type' => 'node'));

    $this->addFieldMapping('host_entity_id', 'l_nid')
         ->sourceMigration('City');
    $this->addFieldMapping('field_list_title', 'field_link_title_value');
    $this->addFieldMapping('field_venues')
     ->defaultValue(1);

    $source_key = array(
      'nid' => array(
        'type' => 'int',
        'description' => 'List content ID',
        'alias' => 'ml'
      )
    );

    $this->map = new MigrateSQLMap($this->machineName, $source_key, MigrateDestinationFieldCollection::getKeySchema());

     }

  public function prepare($field_collection, stdClass $row) {
    $legacy_list_nid = $row->nid;

    $venues_query = Database::getConnection('mig_dest', 'legacy')
      ->select('content_field_venues', 'v')
      ->fields('v', array('delta', 'field_venues_nid'))
      ->condition('v.nid', $legacy_list_nid, '=');
    $venues_query->orderBy('v.delta', 'ASC');
    $venues_query->orderBy('v.nid', 'ASC');
    $venues_query->isNotNull('v.field_venues_nid');
    $result = $venues_query->execute();

    while ($record = $result->fetchAssoc()) {
      $venue_delta = $record['delta'];
      $legacy_venue_nid = $record['field_venues_nid'];

      db_set_active();
      $venue_nid_query = Database::getConnection('mig_dest', 'default')
        ->select('migrate_map_venueprofilepage', 'mv')
        ->fields('mv', array('destid1'))
        ->condition('mv.sourceid1', $legacy_venue_nid, '=');
      $venue_result = $venue_nid_query->execute();
      $venue_nid = $venue_result->fetchField();

      if (is_array($venue_nid)) {
        $venue_nid = $venue_nid[0];
      }
      if (strlen($venue_nid) > 0) {
        $field_collection->field_venues['und'][$venue_delta]['target_id'] = (string)$venue_nid;
      }

    }

  }

}


Extract Admin OG members from basic page with views I have added a group reference field to basic pages. That is every book page belongs to an OG group. When displaying a basic page, I want to display the list of admin members of the OG group in a block.

So, I have a view in a block with the following :

In contextual filters

Content: Nid

In Relationships

OG membership: OG membership from Node
(OG membership from node) OG membership: Group Node from OG membership
(Group node from OG membership) OG membership: OG membership from Node group
(OG membership from node group) OG membership: User from OG membership

In fields

(user from OG membership) User: Name (User name)

This view display all the users of the group associated to the current basic page.
Now, how can I filter theses users to only keep the ones which have an "administer member" role ?

Any help would be greatly appreciated.

I found the solution by doing the following

In Relationships

OG membership: OG membership from Node
(OG membership from node) OG membership: Group Node from OG membership
(Group node from OG membership) OG membership: OG membership from Node group
(OG membership from node group) OG membership: User from OG membership
(OG membership from node group) OG membership: OG Roles from membership

In filters

(OG Roles from OG membership) OG user roles: Role Name (= administer member)

The idea was to select the roles from the OG membership of the Group.


Phantom template file? I've inherited a site running a custom Zen sub-theme.

It uses standard CCK content types with several "page-node-" and "node-" template files for layout control.

The original designer used the .tpl files to manually embed various views and blocks (with specific HTML structure for styling) into different pages throughout the site.  As you can imagine, these views and blocks can not be directly configured through the UI.

One page however has some block like sidebar image elements that cannot be manipulated through the UI and appear to be embedded via a template file, but I can't find a template file in either the sub-theme or base theme (zen) directory that would affect this page at the page level. There is a node level template, but it only affects the content area, not the right sidebar.

From the source, I can see that they are not actual blocks as they simply have "
" tags around them

 ...

The element between #sidebar-right-inner and #block-block-39 simply has a
 tag with no drupal classes or ids.  This is what needs to go.  Block-block-39 has been configured through the "blocks" administration page and is supposed to be there.

If it were indeed embedded via template file, I should have a file like sites/all/themes/mytheme/pages/page-node-15.tpl.php, but I don't.  I've checked Page.tpl.php in both sub-theme and base theme (and every other .tpl file) and cannot figure out how these elements are getting there!  Is there somewhere else that a block of HTML could be embedded?

I've tried disabling Javascript on my browser with no change.  And if it were created through the UI somehow, I'm thinking it would have additional divs wrapped around it or other classes / ids.

I think I have a pretty good handle on how templates work (hierarchically speaking), and I've spent days searching for an answer. I'm sure I'm missing something silly, but I'm pretty stumped at the moment.

I basically need to just get rid of them.

Ok, these elements do not display an "edit block" option when I am logged in as an admin and mouse hover them, nor do they display any of the HTML class / id properties which are typically associated with a block.  So It had to be somehow injected or modified VIA a template file.

I did however, finally discover that they were in fact being added via a cryptically named block.

This meant that it was likely being acted upon by a "block-" template. Armed with the newly discovered block number, I found that the file "block-block-22.tpl.php" was stripping the edit link and other divs and formatting to prevent the block from having it's own background etc.

The standard "block.tpl.php" file writes all blocks in the sub-theme like:

<div id="block-<?php print $block->module . '-' . $block->delta; ?>" class="<?php print $classes; ?>">

  <?php if ($block->subject): ?>

<?php print $block->subject; ?>

  <?php endif; ?>

    <?php print $block->content; ?>

  <?php print $edit_links; ?>

Whereas "block-block-22.tpl.php" was overriding the default and writing it as such:

<?php print $block->content; ?>

effectively stripping all of the block's formatting so that only the images that it contained would show with no extra margin, padding, background etc.

I had a feeling I was missing something simple...

Furthermore, changing it to:

<?php print $edit_links; ?>
<?php print $block->content; ?>

Enabled the "edit block" link for administrators, so now it can be edited directly from the page.


Page redirect based on referrer I am looking for an option to redirect user referred from a specific url (say abc.com) to domain.com/abc in Drupal 7
if http_referrer='abc.com' redirect to xyz.com/abc
I looked at Redirect, http response headers modules but need something for http_referrer.

Preferably without code modification.

You could add a redirect in the .htaccess file if you're using Apache. Something like this:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_REFERER} .*abc.com  [NC]
  RewriteRule .* http://example.com/abc  [R]
</IfModule>


What are configuration entities used for? I’m trying to wrap my head around D8 Configuration Entities (CFE).  The concept of a Content Entity (CTE) seems easy – if you want an application that keeps the information for a CD music collection you can build a content entity that creates a table and stores the fields of your CDs (e.g. Artist and Title).

What is a CFE is used for?  When the CFE example in the “examples” module is installed the result is a link to a page that shows a table that contains one default “robot” (Marvin) and a button to "Add A Robot".  How is this different from creating a robot entity via a CTE?

I do appreciate that there is a structural database difference. The data for each robot gets stored in the config table.

I would like to add some additional general thoughts on the differences…

Content entities are generally external facing, meaning your site viewers will interact with your content – ie. they will read your pages & articles; they will look at your images, they will browse thru your product catalog, they will post comments and reviews, etc.

Config entities are generally internal facing, normally only site administrators & content editors interact with a config entity such as setting up a new view or adding a block to a page.

There are many, many, instances of content entities – think of a news website and how many hundreds or thousands of articles there are, but there are only a few instances of config entities – with the article, there may just be one content type (content types are config entities) needed for all those articles.

Content entities generally store data in their own database tables and fields though you don’t have to use hook_schema to create them, they are more often instantiated in the class annotations, with yaml files or by using the UI.  Config entities can have database fields, but by default they do not.  That is not to say they don’t have fields, they do have fields.  The content type entity has fields, such as name and description (you just won’t find them in the database as such).


Sending HTML email with drupal_mail() I'm trying to send HTML emails from a module and I'm using drupal_mail().
It's not possible to send HTML email with just drupal_mail() (see here), and I've installed Mimemail. However, the email is still being stripped of all HTML tags.
Do I need to make any extra calls in the email template, or is there something else I've forgotten?
Set-Up
Mail System

format() -- mimemail system
mail() -- SMTP module

Mimemail

Email Format: Filtered HTML (My filtered HTML allows
 and
 tags.
Include all site stylesheets.

SMTP module

Allow HTML formatted emails

drupal_mail
tellafriend_mail($key, &$message, $params) {

  $message['headers']['MIME-Version'] = '1.0';
  $message['headers']['Content-Type'] = 'multipart/mixed;';
  $message['headers']['Content-Type'] = 'text/html;';
  $message['subject'] = t('This is a test email');

  $message['body'][] = t("This is a test email")."

".t("This should be a new paragraph.")."

".t("And a third paragraph.")."
";
  $message['params']['attachments'] = $params;
  }

As it turns out HTML email was infact enabled. The problem was the stylesheets that the email was being bundled with.

If you head to admin/config/system/mimemail you can choose to either bundle the email with your website stylesheets, or set-up a mail.css in your default theme directory.

I suspect if you're using a sub-theme and haven't got mail.css it'll just use the original theme mail.css which is probably not what you want.


Grouping multiple columns in a view result for a report I have a requirement in which I need to display the stock report for an application as in the below image

I want to know how to group the Quantity, Batch no and Expiry date fields together in another column (Opening Stock) in Views. I am using Drupal 7 and Views 3.

Also I need a summary of the quantity in the footer of the view, for example sum of all quantity for a batch in the footer. Any help from the community is highly appreciated...

To group the quantity, Batch no and expiry date fields in another column, use the views secondary row module

  Provides a way to split a views table row into two. In the table style
  settings, select a "Secondary row" option.

  So if a table looks like this: Name | Description | Edit link | Delete
  link selecting "Name" as the secondary row option for "Edit link" and
  "Description" as the secondary row option for the "Delete link" will
  render two rows:

For summary of the quantity in the footer, use Views summarize

  Enables an extra display style which displays summaries of a column on
  the last row.


How can I restrict that only sender and receiver can download the attached file with the private message? I am using drupal 7. I created a new file field in private messages for attachments and I want that only sender and receiver should be able to download the file attachment.

I apologize if this question is duplicate but I didn't find the answer for this.

EDIT: Just one addition. I am using Custom Field permissions module as well. And authenticated users are unable to see the attachment until "View anyone's value for field" is enabled for them.

Your question is fully answered here http://drupal.org/documentation/modules/file

Please read sections:

Managing file locations and access
Accessing Private Files

  You can also specify whether files are stored in a public directory or in a private file storage area. Files in the public directory can be accessed directly through the web server; when public files are listed, direct links to the files are used and anyone who knows a file's URL can download the file. Files in the private directory are not accessible directly through the web server; when private files are listed, the links are Drupal path requests. This adds to server load and download time, since Drupal must resolve the path for each file download request, but allows for access restrictions.


URL Alias for Taxonomy for multiple child terms I am having a problem setting up the url alias for a vocabulary with recurring child terms.
So for instance the vocabulary consists of categories and locations.

Category 01

All
Location 01
Location 02

Category 02

All
Location 01
Location 02

Category 03

All
Location 01
Location 02

At the moment I have 2 separate vocabularies of event categories and event locations.
For the node url I have setup the alias as

events/[node:field_event_category]/[node:field_event_location]/[node:field-event-start:value:custom:Y-m-d]-[node:title]

Now where I am stuck is setting up the url alias for the category and location.

Can anyone help with the best way to setup the vocabulary and url aliases? - Thank you.

From what I'm seeing, you're wanting to represent your 2 different taxonomies as a path hierarchy, but not a taxonomy hierarchy (i.e. Category terms don't have Location child terms). So you're looking to create something like:

events/ : All Events
events/X: Events in Category X
events/X/Y: Events in Category X & Location Y

Pathauto cannot create mixed-vocab url aliases however, so for a path hierarchy you can create a page view with a couple of contextual filters, one for Category & another Location. The linked example should walk you through how to do this.


Search not finding search term from page title Using the default database search index in drupal 8, when I search for a term from the a page title, sometimes it shows the result and sometimes it shows nothing, even though i enter the exact page title in the search. All pages have been indexed.

How can I debug why the search term is not being returned?

This is easy to debug, because the search index is built of rendered nodes with the view mode search_index. So you could build a view displaying all nodes with this view mode and check the result:

Edit:

The node search plugin adds the title to the rendered node, so if the page title is the node label, it should be included in the search index:

NodeSearch::updateIndex():

  $build = $node_render->view($node, 'search_index', $language->getId());
  ...
  // Add the title to text so it is searchable.
  $build['search_title'] = [
    '#prefix' => '<h1>',
    '#plain_text' => $node->label(),
    '#suffix' => '</h1>',
    '#weight' => -1000
  ];
  $text = $this->renderer->renderPlain($build);


drupal 6 NOT showing php notices I am trying to make php show error notices, but it doesn't work. For my error settings I have write errors to screen and log.

I tried this: (in page.tpl.php)

error_reporting(E_ALL);
ini_set('display_errors', 'on');
$abc = array();
echo $abc['test'];

To enable error messages, add the following to your index.php:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


How to fetch a field's values from a lot of nodes? I need to create a list of all submitted values from a field named field_telephone from thousands of nodes from a specific content type.
using the node_load() function takes long time.

What is the fastest way to fetch the field's values?

You can also use field_attach_load, I believe you can pass it just 1 field you want and a set of entity ids and you can get back all the values. The below example is taken from this blog post and I take no credit for the code:

$query = new EntityFieldQuery();
 $query->entityCondition('entity_type', 'node')
   ->entityCondition('bundle', 'article')
   ->propertyCondition('status', 1)
   ->fieldCondition('field_image', 'fid', 'NULL', '!=');
 $results = $query->execute();
 $articles = $results['node'];
 $fields = field_info_instances('node', 'article');
 $field_id = $fields['field_image']['field_id'];
 field_attach_load('node', $articles, FIELD_LOAD_CURRENT, array('field_id' => $field_id));


$page parameter doesn't appear to contain all the information used to render a page I'm using hook_menu to build a series (100+) of pages where the code uses a basic page "master template" and replaces strings in the "master template" node with elements of the URL that reaches the Drupal menu page callback routine.

Once the appropriate strings are replaced, the page callback routine uses node_view() to create the render array, and returns it for further processing and transmission to the client.

The "master template" page is at URL mysite/whatever-string. The problem is that Drupal sticks whatever-string into the page the client receives, and it looks like this:

        ....

I'm using dd($var, 'description') to look at data structures and elements as a debugging tool.  From the callback routine, dumping the unprocessed and processed "master template" node and the render array returned by node_view() and searching for whatever-string returns no results. The string isn't there.  Thinking that perhaps the render array produced by node_view() didn't have all of the elements that the page contained, I implemented hook_page_alter($page) to see if the render array that it gets as a parameter might contain the string.  It doesn't.  Is there some other hook that's available to a module which will have everything that goes into rendering the page ?

As a last resort, I'm sure I can work around this by writing theme/template code to wander through the html (or DOM) and make the changes needed.  I've done this a lot before, but I think it's cleaner (and marginally more efficient) to do it all when the page is generated, rather than looking at all the nodes that get rendered to see if it's a generated one, and make the changes to the HTML directly.

I would suggest using hook_preprocess_HOOK. In this instance I think hook_preprocess_node is what you want but _page may work as well.


Filter User in Views based on taxonomy contextual filter? I have some users with taxonomy term reference fields.
Lets say users can be associated with regions.

When i view  the user page i want to see all other users from the same region as the user i am looking at.

I created a views block on users with a contextual filter based on that taxonomy, but i cant get it to work ? Do i need some relationship ??

My Settings for the contextual filter:

filter on User: Region (field_region) / that is the taxonomy term reference field in the user
provide default value -> user
ID from URL
specify validatiion criteria -> taxonomy term -> vocabularies "Region" , filter value type -> term name converted to term id

You are on the right track, but the contextual filter has to be changed. The user ID is not the region. If you wish to filter on the Region, you must first determine the Region for the user page you are on.

Switch the Provide default value to PHP Code. Then enter something like:

$user = menu_get_object('user');
return $user->field_region['und'][0]['taxonomy_term'];

This will load the term object for the region of the current user, and the filter can then limit the user list based on that term.

To eliminate the current user from this list, set upa second contextual filter in User:UID and set default value to Use ID from URL. Then open up the 'More' settings and check exclude.


Replacement pattern for one value of a multivalue field in views Rewriting the results of a views field, I wonder if there is a way to use a replacement pattern for the first, second and third value of a multivalue field.

In my case, as example:

I have tried to use this rewritten tags field:
   [field_tagging:0]
   [field_tagging:1]
   [field_tagging:2]

However, this is not rewritten/recognized as replacement patterns.

The result I need, is that in the views field has three tag links, which have a rewritten path (in this case it also uses !1 for the contextual value in the URL)

I had a similar problem, although not exactly the same.  Here's what worked for me:
 1. Enable the module entity_token which is a sub-module of Entity.
 2. Use field-tagging:0 (with a dash not an underscore).  Depending on exactly what you are trying to do, you may need a further parameter such as field-tagging:0:url.

It seems that field_tagging and field-tagging are two different things.  The first one doesn't accept :0.


Setting a user as an administrator via drush command line? How can I set a user to a specific role via drush? In my case I want to give the role of administrator to the user.

drush help user-add-role
Add a role to the specified user accounts.

Examples:
 drush user-add-role "power user" 5,user3  Add the "power user" role to the accounts with name, id, or email 5 or user3, uids 2
 --uid=2,3 --name=someguy,somegal          and 3, names someguy and somegal, and email address of billgates@microsoft.com
 --mail=billgates@microsoft.com

Arguments:
 role                                      The name of the role to add
 users                                     (optional) A comma delimited list of uids, user names, or email addresses.

Options:
 --mail=<me@example.com>                   A comma delimited list of user mail addresses of users to operate on.
 --name=<foo>                              A comma delimited list of user names of users to operate on.
 --uid=<3,5>                               A comma delimited list of uids of users to operate on.

Aliases: urol

So, for your use case:

drush user-add-role administrator USERNAME


Add field into other field with Views I have a view with td grid style and two fields: views-field-field-foo-image and views-field-field-foo-title.

The image is linked with colorbox load and the structure of the HTML is like this:

    <a class="colorbox views-ajax-processed-processed"....

How can I put the foo-title into the foo-image field, so the structure to become like this?

        <a class="colorbox views-ajax-processed-processed"....

With views module by changing the order of fields, so the title become on top and with Rewrite results/Rewrite the output on the image field will be possible to change the structure, but I cannot understand the building process with tokens.

EDIT: Unfortunately the answers didn't helped me.

Here's an example http://www.mtv.co.uk/the-valleys when you hover on any latest video, you'll see the title.
This is their structure:

Exclusive

I want to add that
 inside the link, or in my case the title field.
That's what I want to achieve.

I can see they don't use views. If someone knows how to create that even without Views module, please let me know.

One possibility is to use the Views Field View module:

  This module allows you to embed a view as a field in a view. A new field handler is made available, so this can also be used in area (header/footer/empty) handlers as well as rows.

Also, there is the 'Rewrite results' options in Views definition.

Alternatively by code, you can use use a field--[type|name[--content-type]|content-type].tpl.php file to override the rendering of the field. You would then have to access the $element['#object'] to get access to the other field that you would need to render manually. Reference: https://api.drupal.org/api/drupal/modules%21field%21theme%21field.tpl.php/7


How to use a field value in Template.php Im sure this is an easy question, just not for me because of lack of experience with the Drupal preprocess hooks. I am removing the standard "Read More" links from my content. I want the ability to replace them with a css button. I can do that, the tricky part come when I want to use a FIELD from the CONTENT TYPE, as the name for the button.

function bootstrap_preprocess_node(&$variables) {

 unset($variables['content']['links']['node']['#links']['node-readmore']);

   $variables['newreadmore'] = t(' '.$readmoretext.' ',
   array(
    '!title' => $variables['node_url'],
  )
);
}

My question is how can i HOOK into the node and retrieve the field for my variable $readmoretext

Thanks!

You can find the node object in $variables['node'], and from there you can use the field_get_items() function to extract your field value:

$node = $variables['node'];

// field_get_items() always returns an array, even if the field is limited to one value
$field_items = field_get_items('node', $node, 'field_name');

// Get the value from the first item in the array (if that's the one you need)
$title = $field_items[0]['value'];


Issues with the devel module After I install the devel module I can no longer configure any blocks, I get an internal server error. I uninstalled and the issue stopped, re installed and its an issue again.

Furthermore, I cannot see the grey box in the lower left hand side of the browser where I can access all the variables available in a given page. This is the main reason for attempting to use the module. The module is successful in printing all SQL queries at the bottom of the page however. Any insight as to what might be wrong?

Update: I can also no longer uninstall the devel module from within the drupal backend, i receive the same error when trying to access the uninstall page, I will have to remove it manually from the file system

Update: Removed the devel module once again and problem is gone...

Based on your comment about the 500 error and the menu entry problems, I suspect that the problem isn't really with the Devel module, but rather with your server.

Take a look at your Apache error_log to see what is causing the 500.  Following the steps for fixing a WSOD may also help.

A total guess is that you are running out of memory, and this is happening during the menu rebuild phase when you have an empty cache.  Enabling the Devel module likely was just the tipping point and now you are seeing memory problems.  You can try increasing the memory_limit and see if that fixes things.  But, you really do need to look at the error logs and find the true cause of the 500 errors.


How to create custom preview for content type in Drupal 7? I am implementing a content type called "Product" which has some 8 to 10 fields.
While creating new product details under that content type "Product" client wants the custom preview of the content.

The default preview while adding content is really weird and it does not look good.

I have searched a lot on google but there is no any contributed module available for it.

So please tell the way other than custom module to implement it ?

Something like Page Preview may help you.


I want to call ajax callback function from another module's controller in Drupal 8. is it possible? I am giving the code of my main form and the controller of another module where the ajax callback is written. Actually this ajax callback function will be used in different forms. So I want to create a common module to call this function. Kindly help.
This is the form field of main form:

    $form['construction_type'] = array(
  '#type' => 'radios',
  '#title' => $this->t('1. Whether Boiler or Economiser:'),
  '#default_value' => 'b',
  '#options' => array('b' => $this->t('Boiler'), 'e' => $this->t('Economizer')),
  '#ajax' => [
                  'callback' => '\Drupal\common_functions\Controller\CommonFunctionsController :: ajax_load_boiler_size',

               ],
);

And this is the ajax callback function in controller of another module

    class CommonFunctionsController extends ControllerBase{  public function ajax_load_boiler_size(array &$form, FormStateInterface $form_state){
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#boiler_size_div', $form['boiler_size']));
return $response;

}

The error message is Symfony\Component\HttpKernel\Exception\HttpException: The specified #ajax callback is empty or not callable.

If anything, this should be:

'callback' => ['\Drupal\common_functions\Controller\CommonFunctionsController', 'ajax_load_boiler_size'],

That's only if it's going to work though. No guarantees.


How can I filter out specific words in a node body? For example, suppose a user creates a node with body value "Hi everyone. GARBAGE VALUE This is my node." Upon submission, I want to be able to filter out "GARBAGE VALUE" and replace it with nothing (or have a replacement value) so that when the node is displayed, it only displays "Hi everyone. This is my node."

Is there any way to do this? Rules? (Rules is the only module that I have yet to figure out despite trying.)

Apart from the Rules module,

the Wordfilter module allows site
administrators to filter certain words on all pages.
the Phonetic module goes a step further by including the phonetic characteristics in the comparison as well as a list of profane words.


How do I use PHP code in a block? I am new to Drupal 8. I am building a website with Drupal 8, and it has many blocks contain images. They have an absolute path for the src attribute right now. I would like to make them dynamic base on the base URL, but there is no text format support PHP code anymore for security reason. Is there a safe way to achieve this?

PHP filter is a core module in Drupal 7 but in Drupal 8 it is removed because of some security reason but still you can use this module PHP.

Note: Enabling this module can cause security and performance issues as it allows users to execute PHP code on your site.


Best approach to inject variable data into JavaScript files? I'm looking for a good approach to manipulate some JS code from within a module call. (Using Drupal 6.)

I have a set of JavaScript functions I need to add to a page. (Regular JavaScript, no jQuery.) Unfortunately they rely on some variables from the page they are shown on. So my current approach is to generate all the JavaScript from within PHP code which results in a whole lot of escaped strings like $output .= '  var url = "'. $url . '";' . "\n";, which is not so nice after 20-30 lines of code.

So I would like to move all the JavaScript code into it's own .js file, and find a way to inject my variables. So far, the only solution I could come up with is putting it in a temporary file, read that, modify and save it to the /files directory. But is there another, more preferred way?

Drupal have a javascript array for save settings and variables, take a look here:

http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_js/6

Check the "settings" option in that page.

A example could be:

$my_module_variables = array(
  "url"  => "http://google.com",
  "name" => "this is a variable"
);

drupal_add_js(array("my_module_vars" => $my_module_variables),'settings');

And for use it in your javascript files you can do:

console.log(drupal.settings.my_module_vars.url);
//will print http://google.com
console.log(drupal.settings.my_module_vars.name);
//will print "this is a variable"

In this way you can set javascript vars without need print javascript code, only using a php array.


Add custom fields to image field I have a case where I need to add three custom fields to each image in an image field to hold data.  The content of these fields will not be displayed, but will only be indexed into Solr so they can be used in a custom image search. The logical place for these fields is in the same place that the Alt and Title fields are displayed (when enabled in the field settings), so that they can be entered in when the image is attached. Considering all the field API goodness in D7, it seemed like this would be pretty straightforward. However, it's not turning out that way.

One suggestion was to use the File Entity module, so I can add custom fields.  This seems to work great, in that it allows me to add fields through the UI to the file entity.  However, the problem is that these fields are not available when actually attaching the image to a node - they are only available when you add an image at /file/add.

After looking at the code in image.module, I noticed that the Alt and Title fields are added in the #process callback, which in turn is added in the hook_field_widget_form() imeplentation (image_field_widget_form()).  Since there is an alter hook (hook_field_widget_form_alter()), I implemented it and added my own #process callback:

function nb_alters_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($element['#field_name'] == 'field_images') {
    // Add a custom #process function to add the fields.
    $element['#process'][] = 'nb_alters_image_process';
  }
}

and then added my callback (using code suggestion found here:

function nb_alters_image_process($element, &$form_state, $form) {
  if (isset($element['#type']) && ($info = element_info($element['#type'])) && isset($info['#process'])) {
    foreach ($info['#process'] as $process) {
      $process($element, $form_state);
    }
  }

  // Add the additional Person, and Organization fields.
  $element['person'] = array(
    '#title' => t('Person'),
    '#type' => 'textfield',
    //'#default_value' => isset($item['person']) ? $item['person'] : '',
    '#default_value' => t('Default Person text'),
    '#description' => t('The person'),
    // @see http://www.gawds.org/show.php?contentid=28
    '#maxlength' => 255,
    '#weight' => -2,
    //'#access' => (bool) $item['fid'] && $settings['alt_field'],
    '#access' => TRUE,
  );
  $element['organization'] = array(
    '#type' => 'textfield',
    '#title' => t('Organization'),
    //'#default_value' => isset($item['title']) ? $item['title'] : '',
    '#default_value' => t('Default Organization text'),
    '#description' => t('The organization the person in the image belongs to.'),
    '#maxlength' => 255,
    '#weight' => -1,
    //'#access' => (bool) $item['fid'] && $settings['title_field'],
    '#access' => TRUE,
  );

  return $element;
}

However, this doesn't work as expected. Instead of the fields being added to each image, they are added separately below the last uploaded image.

What do I need to do differently to get my fields to show up for each image? Am I on the right track?

Thanks.

This question got me scratching my head also for a couple of hours, until I found File Entity Inline module.

Basically this module provides the functionality the OP wanted. You just create the field in the file entity you need to and then when creating the file/image field you have an additional box in the editing window where you can select the fields you want to be displayed next to each file.


Unit price showing in purchased entity (Item) field Commerce2.x admin/structure/views/view/commerce_cart_form

Field:
(order_items: Order Item) Order item: Unit price (price)
admin/structure/views/nojs/handler/commerce_cart_form/default/field/unit_price__number

Showing in

Field: (order_items: Order Item) Order item: Purchased entity (item)
admin/structure/views/nojs/handler/commerce_cart_form/default/field/purchased_entity

Is this a bug or configuration problem?

d8.4 Commerce2 updated

Workaround fix: In structure/views/view/commerce_cart_form Change to hidden field: (order_items: Order Item) Order item: Purchased entity (Item) [hidden]

Add field (order_items: Order Item) Order item: Title (Item) for line item display.

Still researching Purchased entity problem.