webform select options validation unique I need to prevent two different users from choosing the same option from a webform select options component. In the validation only validation required available, no unique validation.

For example: my select contains the following: 1|1, 2|2, 3|3. AnnonUser1 chooses option 2. AnnonUser2 should be presented with 1|1 and 3|3.

How can I validate unique for this select options component. I tried webform validation, but it does not provide unique validation for select options component as well.

You can use a select list with a pre-loaded option list. In that "preload" callback you can alter available options.

Define a custom option list:

function mymodule_webform_select_options_info() {
  $items = array();

  $items['exclusive'] = array(
    'title' => t('Exclusive options'),
    'options callback' => 'mymodule_webform_options_exclusive',
  );

  return $items;
}

This callback is called every time the form is displayed, we can alter options here based on previous submissions:

function mymodule_webform_options_exclusive() {
  $default_options = array("One" => 1, "Two" => 2, "Three" => 3);
  $available_values = mymodule_webform_available_values(5); // nid of the webform

  return array_diff($default_options, $available_values);
}

function mymodule_webform_available_values($nid) {
  $submissions = webform_get_submissions(array("nid" => $nid));

  // get all the options values that were already submitted
  $values = array_values(array_map(function($submission) {
    return $submission->data[1][0]; // 1 == index of the field in the form
  }, $submissions));

  return $values;
}

Two things are hard-coded here: nid of the webform (5 here) and the index of the select widget (1 here). It might be possible to avoid hard-coding stuff, good luck!


Update pagination after hook_apachesolr_process_results() Apache Solr Search
Version: 6.x-2.x-dev

I am using hook_apachesolr_process_results() to modify results of search. This returns fewer results than are indicated by displayed filters. Pagination is also configured for original search results, not those modified by hook.

My question is: Is there a way to modify the pagination due to modified results totals without deleting the excluded nodes from the index?

For example, if I execute search A, my pagination is set for a total of 100 results on 10 pages listing 10 results per page.

When the results of this search are modified by hook_apachesolr_process_results(), I now actually have only 15 results. But, my pagination is still set for 100 results.

I want to know how to reset the pagination for a total 15 results.

Thanks for any assistance anyone can provide.

Instead of using hook_apachesolr_process_results() I figured it was better to use hook_apachesolr_update_index instead.

Following the guidance here: http://www.phase2technology.com/blog/filtering-apache-solr-search-results-based-on-dynamic-fields/

I am now able to create a filter using hook_apachesolr_modify_query that will return the correct results and pagination.


Required database permissions I have to make a new install for Drupal 7 and i need to request the database space on Oracle DB to the DB guy, who wants to know exactly which permissions should have the drupal account that will handle the database.

I have read a lot do documentation, and everywhere is just said that the account for the database should have full privileges. I have told this to the DB guy and he refused that statement, arguing for example that Drupal will not need the "drop database" privilege, as an example.

So my question is: where can I find the exact minimum list of database privileges that Drupal needs to work properly?

There's no official documentation for Oracle (I don't think), but INSTALL.mysql.txt states you need the following permissions for MySQL in Drupal 7:

SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER

I came across an INSTALL.oracle.txt on http://drupalcode.org, but I can't vouch for it's accuracy. It says to run the following with regards to permissions:

grant dba, create any trigger, drop any table, select any table, select any sequence, create user to drupal identified by drupal;
grant connect, resource to drupal with admin option;
alter user drupal default tablespace users temporary tablespace temp;

Show both of those files to your DBA, it should be enough for him to go on.


How to alter Services Views result How can I alter services views result. Using services view I can easily produce Json data.
I have tried function hook_views_post_execute. This hook is working for simple views but not with services Views(Json data).

You can use hook_services_request_preprocess_alter() and hook_services_request_postprocess_alter() hooks of Services module.


Drush cim: error "Table xyz already exists" I'm trying to deploy a dev website to a dev server. When running drush cim on the dev server, drush ends with an error message:

  Table honeypot_user already exists

When running drush cim again right after that, the same error comes up again for a while with different table-names. The database does definitely not have these tables before running the config import.

What's the underlying problem and how can I solve that?

Using drush 8.1.17 on a Drupal 8.3.7 (both running offline and soon to be updated for security patches)

Like event said, and In my case, this was solved when the drush cr command is entered before drush cim


Logging out user by modifying database directly? Is there a way to log out a user by just modifying the drupal database?

You can delete the user's session in the sessions table.


set min - max values drupal date_popup timepicker Is it possible to set the minimum and maximum values of the timepicker in a date_popup field? I use this code for the field, but something like 'minTime' is not working.

  $form['fetch_date'] = array(
    '#type' => 'date_popup',
    '#description' => t('Datum waarop u uw bestelling wil ophalen.'),
    '#required' => TRUE,
    '#title' => 'Afhaal Datum',
    '#datepicker_options' => array(
      'minDate' => 0,
    ),
  );

You may find this one helpful.

Datepicker: minDate and maxDate


Modify data structure of a view REST export I need to build a sitemap.xml with a REST export with a view.
By default I get this data structure with a REST export.

<?xml version="1.0"?>
  <response>
    <item key="0">
      <field1>...

How can I modify the tags of this structure? I need to get this tags.

<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>...

These tags must be changed.

<response> > <urlset...
<item> > <url>

Do I write a custom serializer for the REST export or a specific encoder? How do I proceed?

In D8 you need to create custom serializer and encoder to alter the XML tags.

Create custom serializer
Ref :  https://gist.github.com/BERRAMOU/dd21e009eec0e3d98733e78360122892
Write custom encoder

-

namespace Drupal\custom_serializer;
use Drupal\serialization\Encoder\XmlEncoder as SerializationXMLEncoder;
use SimpleXMLElement;
 /**
 * Encodes xml API data.
 *
 * @internal
 */
class myXMLEncoder extends SerializationXMLEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['myxml'];

  /**
   * {@inheritdoc}
   */
  public function getBaseEncoder() {
    $base_encoder = parent::getBaseEncoder();
    $base_encoder->setRootNodeName('jobs');
    return $base_encoder;
  }
}

Then in View under 'FORMAT' you will see both options.
After save, you should get XML with required tag.


Can't submit entityform after ajax callback on select element I followed the advice from this link and migrated the code populating my ajax into buildForm(), and all is well. Select list is populated by ajax and elements are preserved even after form submit. Problem is that I get the following error when I try to submit the form -
The value you selected is not a valid choice

I've tried adding the popular '#validated'=TRUE option to my ajax select, but this causes 2 things to happen

My ajax callback only successfully replaces the content of the
select once, subsequent calls have no effect whatsoever, the old
content of the select remains
I get a really bad error when I try to
submit the form "Website encountered an error". Checking the logs
shows the following:

[client ::1:40776] TypeError: Argument 1 passed to Drupal\Core\Field\WidgetBase::massageFormValues() must be of the type array, string given, called in /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 390 in /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 537 #0 /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Field/WidgetBase.php(390): Drupal\Core\Field\WidgetBase->massageFormValues()\n#1 /home/chibuzo/Software/Dev/Src/Web/tpl_website/web/core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php(232): Drupal\Core\Field\WidgetBase->extractFormValues()```

So if I use '#validated' = TRUE, my ajax callback runs only once and shows the error above on form submit,
And if I remove '#validated'=TRUE, my form fails to submit and shows "You have selected an invalid choice" error".
I even tried to update the $form_state variable to contain the same #options values populated by  my ajax callback and nothing changes, also $form_state->setRebuild(TRUE) does nothing.
I'm almost giving up the idea of using ajax at all, since I've spent more than a week debugging just an ajax select element. First, the ajax callback wasnt being reached at all, now ajax populate happens, but cant submit form. It's just that I have this feeling that I've done 90% of the work involved, its just remaining 1 thing which I dont know. That remaining 10% is what I decided to throw this to the community. I'm sure someone else must know! Thanks for your help, guys...

It would be useful to have the actual code you wrote to check if there are some errors.
If you check my relative question you can crossreference your code to check if there's something wrong (mine is currently working).
I'd suggest to:

apply the patch of this issue
if still not working do the same workaround I've used: check the $triggering_element to populate the select options only in the opportune moments of the form build.


How to tell what is being loaded on a Rules Content is viewed event Is there a way I can see what exactly is being executed on a Rules Event of 'Content is viewed', followed by an action of page redirect to an external URL? Specifically if the content is actually being viewed, and then redirected.

I tried Devel viewing the query log and I didn't find anything. I also tried Devel's Display redirection page, but upon visiting the node, it just timed out.

Using rules event 'Content is viewed', then redirecting, I am still able to get a log message that says I visited that node, so I believe it is loading the node, then redirecting.

This concerns me because when I test other methods of node redirects to external URLs, I don't get a log message saying that I visited that node.

I struggled with a similar question ... The "clue" about what "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

Be aware: this applies to D7 ... and D6 is another story.


Layouts using the grid system How can I lay out blocks or paragraphs using Bootstrap's grid system? I found this seven-year-old answer and am hoping things have evolved since then, and if so would like to know how.

My best stab at cobbling together something at this point is to use Paragraphs for the content and use the Block Class module to assign the desired Bootstrap class to each paragraph type. Is there a more obvious and cleaner solution to the problem in Drupal 8?

The Paragraphs Grid module provides this functionality.

  With Paragraphs Grid, you can display multiple paragraph entities in a
  grid. Supports Out-Of-The-Box Bootstrap 3.0 and 4.0 and CSS grid
  from MDC (Material Design).


How to GET REST resources for Views Getting a node via Drupal 8's RESTful web service can be done by doing a GET with this url:

/entity/node/1

How then, do you access a View?   I've tried the following, with no luck:

entity/view/myviewid

Where 'myviewid' is id specified in views.view.myview.yml

My rest settings for views are exacty the same for nodes, which return JSON successfully.  The view GET attempt however, returns a 500 Internal Server Error.

If you have the rest module enabled you have a new display type called "REST export". There you can configure to either return just the normal REST output for all entities, or you can even configure which fields you want to include.

Much like you enable REST support for entity types you also don't want to deal with unwanted REST access by default.


WYSIWYG on panel panes Is it possible to use a wysiwyg editor like TinyMCE for editing content in panels.  I want to be able to use TinyMCE for editing 'custom content'.

Another note: is it better to create nodes and just add them to the panel or to use the 'custom content' feature?  Thanks!

The last time I added Panels to a site, I used this code to preload the required libraries on panels edit pages.

  // Panels support.
  if (module_exists('panels') && $form_id == 'panels_edit_display') {
    // Load potential editor.
    foreach (filter_formats() as $format => $object) {
      if ($profile = wysiwyg_get_profile($format)) {
        wysiwyg_load_editor($profile);
        wysiwyg_add_plugin_settings($profile);
        wysiwyg_add_editor_settings($profile, 'advanced');
      }
    }
  }

From http://drupal.org/node/356480#comment-1190907 and the patch located in http://drupal.org/node/356480#comment-4256204.

This setup worked with:

Drupal 7.0
Latest WYSIWYG 7.x-2.x-dev from git
CKEditor 3.6
Panels 7.x-3.0-alpha3
CTools 7.x-1.0-alpha4


How do I modify the content of a select list field? I have a content type with a Node Reference field, so the user can select from a list of node titles. I need to filter out some nodes from the list (those that have a date field older than the current date).

I know that hook_form_alter() can be used to modify the display and validation of form fields, but probably not change the query that the field uses. So I think I need to write some kind of preprocess function for this field, that does a second filter on the contents?

Any pointers on how to do this would be great - thanks.

Have a look at Restricting node reference values to owner

As described there, you can select a view as the source for the node reference selection. In that view, you can apply whatever conditions you want to that list.


Can we make 2nd field required only if 1st field is filled in a custom composite field? I am using custom composite field in one of my webform form . It has 4 fields and i want to make 2nd field as required only if 1st field is filled .How can i do this?

I had added field2 as required in webform and I had tried to do remove the required attribute from field2  if field1 is not filld by  using some jQuery code but that is not working.

Below is the jQuery  code i had used

var field1=$('#field1').val();

if (field1 == "") {
 $('#field1').removeAttr('required aria-required aria-invalid');
 $('#field2').removeClass('required error');
}

You can do it with two ways

With Webform Custom Handlers.
With custom js.

I prefer you to go with the 1st approach I mentioned above. How to create and work with webform custom handlers is documented well on drupal.org's webform document. Attaching here for quick reference.

namespace Drupal\mys_module\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\Component\Utility\Html;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Webform validate handler.
 *
 * @WebformHandler(
 *   id = "my_module_custom_validator",
 *   label = @Translation("Alter form to validate it"),
 *   category = @Translation("Settings"),
 *   description = @Translation("Form alter to validate it."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class CustomValidatorWebformHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  //We will overwrite the method validateForm, inherit from WebformHandlerBase.
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->validatePhone($form_state);
  }

  //We will define a new method to validate for example the phone.
  /**
   * Validate phone.
   */
  private function validatePhone(FormStateInterface $formState) {
    $value = !empty($formState->getValue('phone')) ? Html::escape($formState->getValue('phone')) : NULL;

    // Skip empty unique fields or arrays (aka #multiple).
    if (empty($value) || is_array($value)) {
      return;
    }
    if ($value > 9) {
      $formState->setErrorByName('phone', $this->t('Phone not valid.'));
    }
    else {
      $formState->setValue('phone', $value);
    }
  }
}

Enable it for your webform: The route to administer the handlers of a Webform is  /admin/structure/webform/manage/[your_webform_name]/handlers

The second way is to add javascript in assets section of the webform:
Route is: /admin/structure/webform/manage/[webform]/settings/assets

In the case of jQuery, I suggest instead of removing the required try adding it. As the property is configured in the webform element setting.


Drupal 7: pull out just the Twitter job as its own Cron job so that we could run it every minute Drupal 7: We are using the twitter module and it adds a job to Cron so that every time Cron is run it checks Twitter for the configured tweeter account and downloads to the Drupal Twitter table any new tweets since that last time Cron was run.  Our customer wants to have close to real-time display of these tweets and we did not want to have Cron run every minute since we are concerned about the performance hit so instead we run it every 5 minutes.

Is their any way to pull out just the Twitter job as its own Cron job so that we could run it every minute which might not impact performance?

There are a couple of different cron managers available, personally I use Elysia Cron

  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

But there's also Ultimate Cron which I understand is very good too

  Runs cron jobs individually in parallel using configurable rules, pool management and load balancing.

Either of those will let you isolate the Twitter cron job to be run more frequently than the normal one.


How to copy data from one node reference to another node reference in same content type I have already saved a lot of data in a content type 'Events' in the node reference field field_organization. However, I need the data to be moved to the field field_affiliation also within the same content type.

Is there a way to do this with VBO and PHP command or another simpler way without code?

As far as I know VBO is rather not for this kind of job, I also don't know any other module to help you with this except the migrate module but I also think that it won't be of any help for you. What you are describing is called "migration", transferring and storing data from one place to an other, even if it is just one field or an entire website. Most migration tasks require at some point, if not at all points, code writing, code to  manage the data during the migration. Fortunately, to your case is just a field, so you'll need to write a small script by taking advantage of the Drupal's node API, to transfer the data from one field to another, and that's it.

Rough idea on how to do it:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

foreach ($nodes as $node) {
  $value = $node->field_organization[LANGUAGE_NONE][0]['value'];
  $node->field_affiliation[LANGUAGE_NONE][0]['value'] = $value;
  field_attach_update('node' ,$node);
}

Use drush to run your script by using this command :

drush php-script site/all/scripts/script_name
I know, this is too much for someone who has not much experience with Drupal yet but if you are really serious in getting involved with it you should start learning and use those things as much as possible.

Lastly, if you still insist to do it without writing a single line of code, do it manually, but you will soon discover that that way has a major disadvantage if your nodes are more than one or two hundred.


Multi-site: how to handle some module differences? I have a Drupal 7 multi-site installation with some shared modules. Some of these modules declares some forms. And here comes the problem: How to make these forms look different in two different sites? For example: In one site the whole form needs to be on a single page but in another site it needs to be divided in two steps, how can I solve this without change the module code?

I tought in some solutions:

Create a custom module for the site that needs the form to be in two steps.
Break in two steps using javascript and handle the navigation on the client site.
Create a configuration on the shared module (the problem here is that I'd have to create a specific configuration for every possible customization on the form).
Create a template for the form and handle this steps in specific site theme.
Change the module to, instead of creating a form using FAPI, creates a webform node that could be changed for the specific site when the module is installed.

What would be perfect for me is that is someway I could implement a form alter hook in the theme but it isn't possible, right?

What do you think? How you solve this problem?

Create three modules named site1.module, site2.module and site1site2.module respectively. Store changes (hook_form_alters) for site1's forms (including those of your custom module) in site1.module, sites2's forms in site2.module, and forms of both sites in site1site2.module.

The module names will of course need to be swapped for more meaningful alternatives.


How do I run Drupal SimpleTest example from Examples for Developers from the CLI? I've been running tests from a helper_module_preprocess_html function that I trigger on reload. I think I need to level up with testing. I have a vanilla installation of Drupal, downloaded and enabled Examples and SimpleTest modules, and for the life of me I can't figure out how to get the simple test example tests to run from the command line on Ubuntu 14.14. How do I use Drupal's testing system? I'm lost and the documentation on the internet isn't helping.

It seems that SimpleTest requires a version number in the .info file. I added testing_api = 2.x in the .info file and now it works.


How do I load a JavaScript file? I used the following code.

libraries.yml

    my_module.admin:
  version: VERSION
  js:
    js/my-module.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

my_module.module

 /**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {

$attachments['#attached']['library'][] = 'js/my_module';
  // $attachments['#attached']['library'][] = array('my_module', 'admin');
}

my_module/js/my_module.js

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.my_module = {
      attach: function(context, settings) {
        $(document).ready(function() {
            alert("hello");
            console.log('Loaded');
          }
        };
      })(jQuery, Drupal, drupalSettings);

I have tried many other changes, but the JavaScript file is not used.

I have ported Drupal 7 code that implements hook_boot() and includes that JavaScript file, to Drupal 8.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme. In your case, the library name is wrong. The right format for the name is module_name/libraries_name.

/**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_module.admin';
}


Add javascript to form by module i am writing a module in drupal 8. I wish to add a javascript when loading that form.

function ajax_example_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#attached']['library'][] = array('ajax_example', 'ajax_example.sync_script');
}

and i have defined the following at the module library yml file

sync_script:
  version: 1.x
  js:
    js/test.js: {}

but seems the js is not embedded. And i have put the js in a folder called js at the root directory of the module.

What is the way for drupal 8 to embed a javascript at the form?

I don't know what you're aiming to build.

Because I think it's not good to use your javascript in hook_form_alter() , that way, any form you try to see will invoke that javascript code.

However... Back to your issue,

I think the hook_form_alter() function should be used in the module_name.module file under the root of your module folder: modules/custom/module_name/module_name.module along side the routing, info, etc.

After building the .module file, you need to build the module_name.libraries.yml file (if it's not already built), and there, you write your routing requirements, example:

<route_name>:
  version: 1.x
  js:
    js/<your_javascript_file>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Backto the .module file, you implement the hook_form_alter, so your code goes like this:

/**
 * Implements hook_form_alter().
 */

function <module_name>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    $form['#attached']['library'][] = '<module_name>/<route_name>';
    $form['#attached']['drupalSettings']['<module_name>']['<route_name>'] ['variable'] = 'value';

    return $form;

}

To make sure, console.log your PHP variable in your_javascript_file to see it, example:

(function($){
    console.log(drupalSettings.<module_name>.<route_name>.variable); // value
})(jQuery);

Hope this help!


Export content type: 'An illegal choice has been detected. Please contact the site administrator.' I have a content type which uses a lot of conditional fields, along with an email field, field permissions. When I try to export the type, it produced the error 'An illegal choice has been detected. Please contact the site administrator.' and the export script seems to be truncated so the fields do not import correctly.
Any ideas what might be causing this?

This was caused by a corrupted field. I deleted and re-added the field.


Is there any way in drupal to get all primary links through views? My objective is to get the primary links or any kind of menus items, to be shown as JSON, so that an app could consume it and show it.

I tried it using views and I have services module and views_datasource as well, but no success.

If there is no easy way then I am open to build a custom module as well.
Any suggestions?

Can you create a hook_menu() and then in the callback do a https://api.drupal.org/api/drupal/includes!menu.inc/function/menu_tree_all_data/7 to get the menu tree and then expose that to services or return  json.


How do I pass multiple values to the command line? My module will be run from the command line.  The Drush command would be something like this:

drush create-denver-type --name="some title" --title="some title" --options="apple" --userid="myid"

--options can have one option or five. I'm using a switch statement and only passing one value through --options. What do I need to do to pass two or three values to --options, for example --options="apple, pear, orange"?

Basing on the values passed in --options, different functions will be called.

When gathering multiple values, how do I pass them to my function, and call the correct functions based on the value passed in --options?

$options = drush_get_option_list('options');

This will return something like array('apple') or array('apple','pear','orange').

Yeah, Drush does everything.


Theme suggestion or theme overridden I have two template override - user-profile.tpl.php and views-view-fields--myviewname.tpl.php.
To take effect those templates, I had to place them into the default enabled theme.

The main problem is that I use the default theme "bartik" and I got to place them into "themes/bartik/templates/" to let the drupal theme system know them.
I know it is not a good idea because it is just like hacking. I should use a custom theme or sub-theme from bartik, but I don't want to write any theme.

The only clue is that I have a custom module and I shall put them into that module ( sites/all/modules/mymodule/templates ). Then, I shall make a theme suggestion to let the theme system use them.

How can I do this or any better idea?

when you create a sub-theme you do not need to create any "new" template, but you can change something from the "main-theme". So try to create a new sub-theme and put that files into sub-theme.

M.


Product migration with group and execute-dependencies options I'm migrating from an SQL source in a D8 commerce site. Presently, I'm working on product and inventory data. I have one migration for product variations, one for products, and then 6 additional migrations for inventory tables all in a single migration group. (Inventory data migrations are dependent on the product/variation migrations.) Everything works properly when I run the migrations individually. However, I have a strange problem if I use this command:

drush migrate-import --group=my_inventory_group --execute-dependencies

The migration runs fully and reports that everything is ok--no error messages. I get all the inventory data, products, and variations, but the table commerce_product__variations (relationship data from products to their relations) gets only a single record added (instead of the 1510 records it should have.) That record references the first product item in my source data and one of its variations.

I've found that what does work for me is to execute the product and variation migrations individually and then the rest of the group, like this:

drush migrate-import my_variation_migration
drush migrate-import my_product_migration
drush migrate-import --group=my_inventory_group --execute-dependencies

Since I have this workaround, it's not a huge issue. But I'm curious as to why I can't execute the migration for the entire migration group with the single command. I'm wondering whether I'm missing something related to the structure of the product/variation entities -- the rest of the migration is all for custom entities.

Perhaps https://www.drupal.org/node/2830357 comes into play here? Apart from that, the usual use of --execute-dependencies is to migrate a single migration making sure any migrations it depends on have been executed, the group scenario hasn't been tested so there may be some broken assumption in the code.


D6 - Rule to simply redirect path to login Currently I'm trying to add create a rule that simply redirects anyone from /node/add to /user/login. It's intended to be part of a larger rule, but I'm having No luck with this

Steps of the rule are

Trigger - User is going to view a page
If path has alias(es) - /node/add
Do page redirect to - /user/login

Instead, it just goes to the /node/add page as usual. Why is this simple rule is not working?

Here is the rule exported.

array (
  'rules' =>
  array (
    'rules_30' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_init',
      '#label' => 'Redirect to login if accessing /node/add',
      '#active' => 1,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        1 =>
        array (
          '#weight' => -1,
          0 =>
          array (
            '#weight' => 0,
            '#info' =>
            array (
              'label' => 'Path has alias(es)',
              'module' => 'Path',
              'eval input' =>
              array (
                0 => 'src',
              ),
            ),
            '#name' => 'rules_condition_url_has_alias',
            '#settings' =>
            array (
              'src' => 'node/add',
            ),
            '#type' => 'condition',
          ),
          '#type' => 'OR',
        ),
      ),
      '#actions' =>
      array (
        1 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Page redirect /user/login',
            'label callback' => false,
            'module' => 'System',
            'eval input' =>
            array (
              0 => 'path',
              1 => 'query',
              2 => 'fragment',
            ),
          ),
          '#name' => 'rules_action_drupal_goto',
          '#settings' =>
          array (
            'path' => '/user/login',
            'query' => '',
            'fragment' => '',
            'force' => 0,
            'immediate' => 0,
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

One easy option is to set the 403 Access Denied page at:

admin/config/system/site-information

to:

user

That way, if the user is not authenticated, they can login and view the node/add page.

I think the reason your Rule isn't working is because /node/add isn't an "alias" per se, but a system path.

Another option is something like

/**
 * Implements hook_init
 */
function MODULENAME_init(){
  if($_GET['q'] == 'node/add' && !user_is_logged_in()){
    drupal_goto('user/login');
  }
}


Is it possible to integrate Zoho CRM with Drupal Webforms? How would one integrate Zoho CRM with the Drupal Webform module? Salesforce has a webform module that woks well. As I understand the webform module API is different to the Drupal forms API, making it more challenging. I have found an sandbox ZOHO API drupal module that seems to have lost some steam. Any pointers would be appreciated.

Please checkout http://www.drupal.org/project/zohocrm. There isn't a submodule in there to specifically syncronize webforms, however, when you have zohocrm set up properly, it's pretty easy to use it with some custom code to send webform data to zoho. In the code below, we are inserting a Case into Zoho. You could easily modify to insert a Lead or Contact:

/**
 * Implements hook_webform_submission_insert().
 */
function my_module_webform_submission_insert($node, $submission) {
  $components = $node->webform['components'];

  // Get all submission values.
  $form_values = array();
  foreach ($components as $key => $component) {
    $form_values[$component['form_key']] = $component['type'] == 'textfield' ? check_plain(trim($submission->data[$key]['value'][0])) : $submission->data[$key]['value'][0];
  }

  switch($node->nid) {
    case '234':
      $notes = 'Phone: ' . $form_values['phone_number'] . "\n";
      $notes .= 'Message: ' . $form_values['message'];

      // Build Zoho data for Case.
          $data['records'][] = array(
            'Request Type' => $form_values['topic'],
            'Subject' => $form_values['subject'],
            'Description' => $notes,
          );

          // Send case data to Zoho.
          my_module_send_record($data, 'Cases', NULL, TRUE);
    break;
  }
}

/**
 * Send record to Zoho to insert or update.
 */
function my_module_send_record($data, $module, $record_id = NULL, $workflow = NULL) {
  $zoho = zohocrm_get_client();
  if ($zoho === FALSE) {
    return;
  }

  zohocrm_log($data, 'ZOHO DATA');

  $zoho->setModule($module);

  // Trigger Zoho workflow rules
  if ($workflow) {
    $params = array('wfTrigger' => 'true');
  }

  try {
    if (!empty($record_id)) {
      zohocrm_log('UPDATE RECORD');
      $response = $zoho->updateRecords($record_id, $data, $params);
    }
    else {
      zohocrm_log('INSERT RECORD');
      $params['duplicate'] = 2;
      $response = $zoho->insertRecords($data, $params);
    }

    watchdog('zohocrm', t("Successfully sent data to Zoho CRM. Zoho module: @module"), array('@module' => $module), WATCHDOG_INFO);
    zohocrm_log($result = $response->getResponse(), 'ZOHO CRM RESPONSE');

    // Let other modules process their tasks.
    module_invoke_all('zoho_record_sent', $data, $module, $result['recordId']);
  }
  catch (Exception $e) {
    drupal_set_message(t('Sending data to Zoho CRM failed. Error message: @message', array('@message' => $e->getMessage())), 'error');
    watchdog('zohocrm', t("Sending data to Zoho CRM failed. Zoho module: @module. Error message: @message"), array('@module' => $module, '@message' => $e->getMessage()), WATCHDOG_ERROR);
  }
}


reCaptcha does not display I've installed Captcha and reCaptcha in Drupal 8 because I want to use it on the site contact form. I believe I have all the configuration options set correctly but they are limited. For example, there is no place to tell it what form I want it to appear on.

All modules and core are up to date.

I am logging out to test the form. I know that by default administrators are not presented the reCaptcha.

I'm working with image based reCaptcha v2.

I've looked for a field widget to add to the form but there is nothing. Nor is there anything in the form display settings.

In the old days there was a form list to select from (see screenshots on this question: How do I go about telling Captcha that my form exists? ) but that no longer appears.

The instructions even reference the missing list:

While reCaptha has a stable release for 8, Captcha has only a beta from Feb 2017. So I'm wondering if anyone has this working in 8 at all.

Any suggestions? Further troubleshooting steps I can take?

Go to CAPTCHA Points and enable reCaptcha for your form.


How do I get the node URL in a Twig template? I am trying to get the node URL in a Twig template. {{ content.node_link }} returns the full link, but I only need the URL.

How do I retrieve the node URL?

According to Functions - In Twig Templates you can use is simple by

 {{ path('entity.node.canonical', {'node': node.id}) }}


Entity Reference auto complete term creation on the fly? There is a reason why I'm using an (autocomplete) Entity Reference field on my Content Type, instead of the Drupal's default term reference. It is linked to a taxonomy vocabulary and it's working just fine for my purposes.

What I can't achieve is for a term to be created on-the-fly (auto-creation), if it doesn't already exists in the tax vocabulary, while authoring a new node of that Content Type. Just like drupal's default term reference can do.

Thanks alot for your time.

Instead you can give a try to this Autocomplete Deluxe module to achieve your goal. It have the option to create new term in auto-complete field.

  Features

Combo/Select box like selecting.
Select without entering something.
Widget for taxaonomy
Chosen like multiple selecting.

  If you want to deny adding new terms, then checkout Chosen. It
  converts select boxes to autocomplete fields.


Remove directory name from path I am using WYSIWYG editor with IMCE for article description, the issue is that once i upload an image file with imce, its showing image path like

  /DirectoryName/sites/default/files/image.jpg

Once we hosted website from local to online server, image is not showing because now DirectoryName is changed to some other name.

Any suggestions?

I think the Pathologic contributed module will do it. I have used it in the past and it's awesome. Configuration is a bit tricky, but once it's done you can forget about most file path problems. It's an input filter for text, so it can be used anywhere you can set an input format.

Configuration of Pathologic is covered here. I think it may have issues with internationalization in some cases though.


Should a splash page linking to other multisite instances also be a multisite instance or a bare HTML page? This is the situation:

Global domain: www.domain.com (exists of one page, with links to other 3 subdomains)
Sub domain 1: sub1.domain.com (full website)
Sub domain 2: sub2.domain.com (full website)
Sub domain 3: sub3.domain.com (full website)

My question:

Is it overkill to also create a site for the global domain? It will only have one page (frontpage). Or what is the best practice to accomplish this? The global domain is just a landingpage where you can make a choice between the 3 subsites.

If you need more flexibility on the long run, you better create a separate website for the global domain. Keep in mind that it will require extra resources on your server.

If your global landing page is simple you can consider the option to only use a HTML page. Keep in mind that this will give you less options on the long run.


How to get the value of a variable in CCK from Devel? I am using a custom .tpl file to theme teasers, and I am having trouble with the value of a variable returning true even when apparently there is no value inside ($picture). I would like to see what exactly this variable contains.

How do I leverage Devel to view this variable without having to var_dump()? Currently, the teasers are inside a view which is inside a block on the home page.

As you mentioned after enabling the Dev module, you can use dpm($variable); to get a detailed graphical listing of the array values.


How can I extract a specific field from a set of nodes? I am using Drupal 7.

I have a custom content type with multiple fields. For example, one field contains a thumbnail image. Another is a text field.

There are 36 nodes that use this custom content type. In database terms, I have 36 records.

How do I have Drupal extract a specific field from each of the 36 'records' and display them on a single page?

For example, in PHP I could write an SQL query such as "select fieldname from table" and display using while() { print $row['fieldname']; }.

How do I achieve this using Drupal 7?

Use views, add fields - only the image - display for that content type only if published. done.

If you want to fine tune it, do some theming.


Custom Template Help I am making a custom module on Drupal 7 and I am into to use templates for showing the info. How can I pass values from the module to the template?

Well, You need to use theme() function, which will allow to define the template name to be called, and the variables (values) to be send over to the template file defined.
Please refer documentation here - https://api.drupal.org/api/drupal/includes!theme.inc/function/theme/7

$read_more = theme('more_link', array('url' => 'aggregator/sources/' . $feed->fid, 'title' => t("View this feed's recent news.")));

In the above code "more_link" is template name and associative array of values to be passed. In Template, you will get value of $title as "View this feed's recent news."
Hope you got the point.


Drupal 7 Jumplist using Views Module I am trying to set up a jumplist on my site that has a list of taxonomy terms from a list I've called Categories. I have the jumplist displaying correctly but when I select a term from the list and navigate to it I get this message:

Page Not Found
The requested page "/cms/ca2/Video%20Editing" could not be found.

I would like that it would bring up a list of all the nodes that I have assigned to the category I've selected from the list but can't seem to figure out how to do it.

Could anyone help me with this issue.

Many thanks.

My site I am trying to implement this on. You can see the jumplist on the right sidebar with the title Categories List

http://jciadt.com/cms/ca2/

try to use rewrite field option on your Views to rewrite content link as absolute URL or try using node/[nid] format on the href


What services must I leave switched on in Elysia cron I have installed Elysia Cron to import some Feeds data periodically.
However, I have switched off all the other cron tabs that I have in order not to interfere. However, my database size grows to ten times the size as when the cron was switched on without Elysia cron.

Must I switched them on and with what periodicity?

Elysia cron is just an improved durpal cron service. You must have enabled the services you have enabled by deafualt in the standard Drupal cron. Some of them, for example, remove temporal data from the database (probably the reason your database is growing).

So, yes, you must have the services enabled, and those are the services enabled byu default by Drupal. Obviously the exact services that must be turned on depends on each installation.


Set language for a panel page How do I create multiple translations of a panel page?  My homepage is designed with panels and I have both english and spanish content.  For nodes everything is fine but I can't figure out how to do the multiple language thing with panels.

I haven't attempted this myself, but I would assume you can pass the current selected language in as a context and then trigger different variants of the panel based on that.

You could then also trigger individual pane visibility based on the current language (i.e don't show this untranslated pane to German visitors).


Commerce product with customer defined attributes Is it possible to create a product, for which before adding to the cart, customer must define some attributes. For example, I need a number field where the customer defines the size of the product (105x200mm, or 1000x600mm). There are no predefined sizes, I only need an empty text field for width and height where the customer can type their specific size.

After that I want to add it to the cart but without price. I only want to collect customer orders where the products have sizes. Information about final prices will be sent later by email. We don't want to display prices and no payment.

Thanks a lot

Absolutely.  What you need is the Commerce Customizable Products module.

That allows you to set up Line Item Types that are entirely fieldable!  You can add text fields, select boxes, radio buttons and any field you want to be displayed as the user is adding the product to their cart.

Once the module is enabled, do the following

Add a new Line Item Type at /admin/commerce/config/line-items
Add any fields you need to it (in your case, just a text field)

Make sure to check the box that asks whether this is a field you want added to the 'Add to Cart' form

Finally, go to the 'Manage display' tab of the content type you have that displays your product, and go into the settings of the 'Product' field.  You will see a new option which allows you to choose a 'Line item type' to display.  Select the one you just created, Update, and Save!

Final result:

Let us know if this works for you...


Check if field is empty in Views field Template I have about 4 fields displayed in a view.

What I am looking to achieve is when one of the fields have a check box ticked, to hide a different field in the view display. e.g

Price on application [Ticked and displayed]

Price GBP [Hidden]

Price USD [Hidden]

OR

Price on application [Un-Ticked]

Price GBP [Dispalyed]

Price USD [Dispalyed]

I am editing the views-view-field.tpl for 'Price USD' and 'Price GBP' field.
(views-view-field--clone-of-gallery--gallery--field-listing-price-usd.tpl.php)

The basics I am trying to achieve are:

if 'price_on_application' = '1'
"Empty"
else
Print $output

The if statements i have tried so far are:

<?php if ($row->field_listing_price_on_request == "POA"): ?>
<?php if ($field->field_listing_price_on_request == '1'): ?>

and several other variations of the above.

Any ideas?

You can use the Views Conditional module. With it, you can add a conditional field that would evaluate the value of your 'Price on application' field. You can then add the other two fields in a personalize text excluded from display and use you conditional field to display it or not depending on the condition you want.


Apply grouping to custom views list template I have a custom views-view-list.tpl.php template that uses

foreach ($view->style_plugin->rendered_fields as $delta => $item)

to manipulate the fields at this template level rather than using

foreach ($rows as $id => $row)

and relying on views-view-fields.tpl.php to render the HTML.

However, when using grouping in a view, the views-view-list.tpl.php is called once for each grouping, but the first method renders all items, rather than just the ones in the current grouping.

How can I tell from views-view-list.tpl.php which items belong to the current grouping?

Turns out the $rows object has indices that don't go from 0, counting up by 1.  It keeps only indices of the items in the current group.  That makes this code work:

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
    <?php if(isset($rows[$delta])) : ?>
         ... print out whatever necessary ...
    <?php endif; ?>
<?php endforeach; ?>


How to display an image when hovering over its title in a View? In my style sheet (which does seem to be loaded), I have

.snhover_img a { position:relative; }
.snhover_img a span { position:absolute; display:none; z-index:99; }
.snhover_img a:hover span {
    display: block;
    width: 350px;
}

And in the Title field of my View, I have Rewrite results as

      {{ title }}

But I always see both the title and the image. Nothing happens on hover.
The debugger shows. What am I doing wrong?

Note: I am thinking that the style sheet is not really loading. If not, how do I fix that?

I post as answer because I have not reach 50 reputation to post as comment.
When you debug .snhover_img a span is the style { position:absolute; display:none; z-index:99; } applied?


Passing values from text field to a javascript function in Drupal 8 i am new to Drupal and i am building a form (Drupal 8)that needs to calculate an amount based on the input in two text fields.
What i want to achieve is for the "calculate" button to be hidden until the two text fields have been filled but i'm not sure how to achieve this with behaviors.
Code example:

    $form['weight'] = array(
        '#type'  => 'number',
        '#title' => t('Weight:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'weight',
            ),
    );
    $form['number'] = array(
        '#type'  => 'number',
        '#title' => t('Number:'),
        '#required' => TRUE,
        '#attributes' => array(
            'id' => 'number',
            ),

    );
   // Here if weight and number are not empty, show button

Thanks

You do not need to use Drupal Behaviours for this, this can be done with States API which ultimately uses javascript.

e.g.

$form['calculate'] = array(
  '#type' => 'submit',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="weight"]' => array(
        'filled' => TRUE,
      ':input[name="number"]' => array(
        'filled' => TRUE,
      ),
    ),
  ),
);

You can change the fields name as per your requirement. Hope this will help.

Thanks


How can I truncate uploaded file name Can anyone suggest a way, or a module to truncate very long filenames which are uploaded to a Drupal 7 website? I have a client who keeps uploading files that are actually sentences and I want to limit the filename to a reasonable and certain amount of characters (say 20).

Thanks for any help on this.

You could use a presave hook and rename the file before it gets saved: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_file_presave/7


Safe to add a class attribute to the HTML element via the theme? In Drupal 8 is it safe to manually add a class attribute to the HTML element in the theme's html.html.twig file?

<html{{ html_attributes }} class="no-js">

Its working fine for me but I don't know if there are some instances where Drupal would want to add a class as part of html_attributes? If so then presumably my output would be this:

<html class="drupals-class" class="no-js">

You should use .addclass():

<html{{ html_attributes.addClass('no-js') }}>

That would prevent the output in the example from your question and the result will be:

<html class="drupals-class no-js">


Multiple Drupal Commerce line items in the database but one in the order page I am doing a report module to show various information about drupal commerce orders and line items.

I am now facing a problem with the line items:

For some orders, in the commerce_line_item table, there are multiple line items for the same product and quantity.

However, in the order page of these orders, I only see one line item.
I suppose only one of these line items is the good one, but how can I know which one is good in the table?

They looks the same except the line_item_id field which is different.
So how can I get the line items of an order without any of these dupplicate line items?

Why are there dupplicate line items in the table?

For instance, this query:

SELECT SUM(quantity)
FROM {commerce_line_item}
WHERE order_id = 388

gives me 5 intead of 1.

Note:

I am using Drupal Commerce 7.x-1.3.

Dump for the order 388:

-- commerce_product
product_id  revision_id sku     title   type    language    uid status  created changed data
1   52  sku     Product Name    product_type    und     1   1   1342634788  1352819763  [BLOB - 4o]
-- commerce_order
order_id    order_number    revision_id type    uid mail    status  created changed hostname    data
388     388     1865    commerce_order  123     mail@example.com    completed   1359728586  1359755276  1.2.3.4     [BLOB - 208o]
-- commerce_order_revision
order_id    order_number    revision_id revision_uid    mail    status  log revision_timestamp  revision_hostname   data
388     388     1838    984     mail@example.com    cart    Log message     1359754659  1.2.3.4     [BLOB - 6o]
388     388     1859    984     mail@example.com    checkout_checkout   Log message     1359754827  1.2.3.4     [BLOB - 6o]
388     388     1860    984     mail@example.com    checkout_review     Log message     1359754829  1.2.3.4     [BLOB - 6o]
388     388     1861    984     mail@example.com    cart    Log message     1359755005  1.2.3.4     [BLOB - 6o]
388     388     1862    984     mail@example.com    checkout_checkout   Log message 1359755034  1.2.3.4     [BLOB - 6o]
388     388     1863    984     mail@example.com    checkout_review     Log message     1359755074  1.2.3.4     [BLOB - 74o]
388     388     1864    984     mail@example.com    checkout_payment    Log message 1359755075  1.2.3.4     [BLOB - 153o]
388     388     1865    0   mail@example.com    completed   Log message     1359755276  1.2.3.4     [BLOB - 208o]
-- commerce_line_item
line_item_id    order_id    type    line_item_label quantity    created changed data
773     388     product     sku     1.00    1359754516  1359754829  [BLOB - 232o]
763     388     product     sku     1.00    1359728686  1359728686  [BLOB - 232o]
762     388     product     sku     1.00    1359728699  1359728699  [BLOB - 232o]
761     388     product     sku     1.00    1359728689  1359728689  [BLOB - 232o]
758     388     product     sku     1.00    1359728642  1359728642  [BLOB - 232o]

Thanks for your help.

I finally found out how to do what I want.
The last commerce line items are in the field_data_commerce_line_items table. The commerce_line_item table seems to contain all the commerce line item revisions.

SELECT SUM(quantity)
FROM {commerce_line_item}
INNER JOIN {field_data_commerce_line_items}
    ON {field_data_commerce_line_items}.commerce_line_items_line_item_id = {commerce_line_item}.line_item_id
WHERE order_id = 388

I don't know if it is documented somewhere.
However, it is what I found by reading the source code and the SQL queries.


I have Created a form to upload images, where i should display error message if i upload more than 3 images and should disable submit button I have Created a form to upload images, where i should display error message if i upload more than 3 images and should disable submit button to delete already uploaded image if i want to upload more images

Follow the steps

Go to image field settings of you content type.

Then Go to Image Field Settings and select '3' for number of values for the image

That's it. When user reaches their upload limit (3) the submit button will be disappeared automatically. and display like follows.


Multiple submit/save buttons in form I wanted to add another submit/save button above a node form (for only one content type) and added the code below. The thing is that it messes up the submission, so I had to remove it.

Whats wrong with it and is ther a better way of doing this?

if ( $form_id == 'news_node_form' ) {
        $form['submit'] = array(
                '#type' => 'submit',
                '#value' => 'Save'
                );
        }

Thank you JimJamma, that worked!

Here's how my code looks now:

    $form['submit'] = array(
        '#type' => 'submit',
        '#access' => variable_get('node_preview_branschguiden', DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
        '#value' => t('Save'),
        '#weight' => 5,
        '#submit' => array('node_form_submit'),
    );


How do I theme a blog listing page for a specific taxonomy term? I have a site, where a blog listing of a particular category, say Resources, has to have the "Read More" button say "Download Resource" instead.

I saw that this is controlled by a template file called 'node--blog-tpl.php' in the theme, with the following code:

    <?php if($extended == '1'): ?>
        <a class="btn readmore" href="<?php print $node_url; ?>"><?php print t('Read More');?>
    <?php endif; ?>

Since I wanted to change this just for the 'Resources' category, which was Taxonomy Term 23 for me, I copied this file and renamed it all manner of combinations/permutations of filenames with 'taxonomy--term-23' in it, but nothing seems to work.

Can someone please help me with this? I would be very grateful.

Thanks in advance,
Jasper

Blog list pages render node teasers. I think that the automatic template suggestion patterns would only operate on node attributes and taxonomy is not one.

You can add this to your theme's template.php file

function THEME_preprocess_node(&$variables) {
  // check for blog and teaser
  if ($variables['type'] == 'blog' && $variables['view_mode'] == "teaser") {
     // check for taxonomy term on node
     dpm($variables);
     if ($variables['field_TAXONOMYFIELD'][LANGUAGE_NONE][0]['tid'] == TAXONOMYID) {
       // change the readmore link here or add code for template file
       $variables['content']['links']['node']['#links']['node-readmore']['title'] = "Custom Read Me";
     }
  }
}

If you don't want to override the readmore link inside the preprocess function but absolutely want a template file, then you can instead do this:

array_unshift($variables['theme_hook_suggestions'], "node__blog__blahblah");


Avoid duplicate files on migrate update I am creating file entities with migrate using drush. Image files are being copied down from a remote server.
I tried

$this->addFieldMapping('file_replace')->defaultValue('FILE_EXISTS_REPLACE');
$this->addFieldMapping('preserve_files')->defaultValue(TRUE);

If I run the migration with --update it duplicates the files, not replacing existing ones.

drush mi DAProductImages --limit="10 items" --update

When I run this first time it creates the files. Second time it adds _0 to the filenames and duplicates the files. If I rollback after first migration the files are being removed. When rolling back after the second migration only files of last batch get removed. I also tried with:

$this->addFieldMapping('preserve_files')->defaultValue(FALSE);

How can I make it so that I will not end up with duplicates? I have about 30000 images so I cannot afford that.

This solved it for me.

The documentation at this link was missing a mention that you need to use the class prefix - I just submitted an update to the Drupal Docs to make it more clear:

$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);


Display mode for search API users index I have Search API users index. I am trying to show them in views with my display mode (for example 'teaser') created by Display Suite.

But I only can show fields. For default user view I can show all modes: fields, display suite, rendered entity and so on.

How I can show them via rendered entity?

This worked for me:

Clear the site's cache (drush cc all)
Re-index the search api index that powers the view
Refresh the view edit page

After that you should see the "Rendered entity" option appear with your view modes as options.


printing file entity fields in a node.tpl I have some fields in a file entity type. Now I need to print some of these fields directly in a node.tpl.

How can I do this?

You could do this in a variety of ways. One way: in template.php, invoke YOURTHEME_preproces_node(&$vars){}. Inside it, do:

if($vars['type' == 'YOUR_CONTENT_TYPE'){
   $wrapper = entity_metadata_wrapper("node", $vars["node"]);
   $file = $wrapper->YOUR_FILE_FIELD->value();
   ...
 }

The $file variable should now contain your file object (or an array of file objects). Debug that with print_r($file) (or, preferably, with xdebug or another debugger) and you can add variables the $vars array there with:

$vars['YOURVARIABLE'] = $file->YOURFIELD...

which will then be available in your template as $YOURVARIABLE.


Commerce Rules OR Condition I am trying to set up a simple OR condition.

If these "blocks" (red) are TRUE or these "blocks" (green) are TRUE execute the rule.

So I've tried added a OR block in various ways, but it does not succeed.

Basically what I want to achieve is that, if red block is NOT EMPTY or green block has value YES, the rule should execute.

This thread helped me understand the logic.

https://www.drupal.org/node/1784196

Basically what tobiasb said:

  OR (All conditions below this or between the lines are OR-Conditions)
  - condition1 (OR)
  - AND  (All conditions below this or between the lines are AND-Conditions, default condition)
  -- condition2 (AND)
  -- condition3

  This means:

  condition1 OR (condition2 AND condition3)


Workbench Moderation - Admin Preview - Show Current Revision in Front-End Can someone please help me on the following use case related to workbench module showing current revision but in the front-end.

What I need:

When we hit the preview button on edit content type (editorial) form, I need a LIVE PREVIEW, to show the current version edited, using my front-end theme I've, to show the article details. I don't want the default preview of Drupal.

It sounds like you want Page Preview.

  Page Preview is a low-impact alternative to Drupal's core node preview
  functionality.

  Why would I need this?

  Drupal's regular node add/edit form provides a "Preview" button that
  allows you to see what your node content will look like after all of
  the input filters are applied, without having to first save the node.
  However, it doesn't allow you to see what the entire node will look
  like within the context of a fully rendered page


Check if a field group's subfields have values Is it possible to check if a fieldset's subfields have values?
If none of the fieldset's fields have values it would return null.

$field = field_get_items('node', $node, 'group_name');
if ($field) {
   // At least 1 of it's sub-fields has a value!
}
else{
   // None of it's subfields have values!
}

You might want to try use the field_group_field_group_is_empty() function.

From the field_group module itself:

  // Example from field_group itself to unset empty elements.
  if ($display) {
    foreach (element_children($element) as $name) {
      if (in_array($name, $groups)) {
        if (field_group_field_group_is_empty($element[$name], $groups)) {
          unset($element[$name]);
        }
      }
    }
  }


db_update without table prefix on custom table I installed Drupal with table prefixes in the database. I have my own tables in the same database which I am trying to update. I am getting an error because Drupal is automatically adding the prefix "drupal_" to the table I specified.

$key_cached_update = db_update('my_table')
  ->fields(array('key_cached' => $apikeyinfo->result->key['expires'],))
  ->condition('keyid', $row->keyid, '>=')
  ->execute();

  Base table or view not found: 1146 Table 'drupal_my_table' doesn't exist

I don't have problems with db_query to read the database.

In your settings.php file where you have prefix set in the $databases array. Change this

'prefix' => 'drupal_',

to this

'prefix' => array(
  'default' => 'drupal_',
  'my_table' => '',
),

If you want a more wildcard like way to do this you can set the target. So lets say this is what your $databases array looks like inside settings.php

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
  ),
);

Change it to this, where everything is the same except the prefix is empty.

$databases = array (
  'default' => array (
    'default' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => 'drupal_',
    ),
    'noprefix' => array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => NULL,
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Then in your function call do this

$key_cached_update = db_update('my_table', array('target' => 'noprefix'))
  ->fields(array('key_cached' => $apikeyinfo->result->key['expires'],))
  ->condition('keyid', $row->keyid, '>=')
  ->execute();


What meaning do the primary / secondary menu links have when it comes to SEO? Is there some meaningful difference between the primary / secondary links when it comes to SEO? Do they carry a different weight from a search engines perspective?

Thank you!

Usually there is no meaning other than that you apply. For most sites, Primary links (or Main menu) are used to navigate the content of the site, and Secondary links are more for the infrastructure links (Contact, Site policy etc). You can use them any way you wish in the context of your own site. There should be no SEO impact.


Drupal 8 migrating image from local folder per XML file I'm trying on this for two days now and I don't get it. I need some more experienced people to look over my code. This is my first Drupal 8 project, meaning, Drupal 8, Twig, Migration API, Yaml... it's a lot of new stuff for me and I'm still learning.

I need to import data from a XML file. I wrote a custom module and was able to migrate all the XML nodes into D8 nodes, but only text fields and taxonomy terms.

There are also image references in some XML nodes and I know, I have to migrate them first into file entities before referencing them in the nodes. So I wrote a second migrate configuration, but it doesn't work and I'm stranded. I don't find a mistake in my yml file, it's close to this example on GitHub: drupal-migration-example

My source data folder, containing some jpgs and a XML file, is stored inside the public file folder.

Maybe important for my issue: Not every XML node has an image reference. But I think I catch that with plugin: skip_row_if_not_set. I don't know how to debug that.

What I have so far:

id: clio_cover_import
label: Clio-Cover-Import
migration_group: werk_import
# Source
source:
  # XML data parser
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: xml
  urls: public://import/werk-import.xml
  item_selector: /Werke/Werk
  fields:
    -
      name: clio_cover
      label: 'Werk-Cover'
      selector: Coverpath
  ids:
    clio_cover:
      type: string
  constants:
    file_source_uri: public://import
    file_dest_uri: 'public://cover_uploads'
# Destination
destination:
  plugin: 'entity:file'
#Mappings
process:
  settings:
     # Check if the "clio_cover" key exists in the "data" array.
     plugin: skip_row_if_not_set
     index: clio_cover
     source: data
     message: "Missed the 'data' key"
  file_source:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_source_uri
        - clio_cover
    -
      plugin: urlencode
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - clio_cover
    -
      plugin: urlencode
  uid:
    plugin: default_value
    default_value: '1'
  filemime:
    plugin: default_value
    default_value: 'image/jpeg'
  status:
    plugin: default_value
    default_value: '1'
  filename: clio_cover
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
# Dependencies
dependencies:
  enforced:
    module:
      - clio_import_modul
migration_dependencies:
  required: {}
  optional: {}

Every help is very appreciated!

Thanks to quietone, I figured it out. The settings for skipping row didn't work as expected. Instead of repairing, it's much easier for me to modify the XML-file and remove all rows without image node.

So I don't need the skipping plugin anymore and can change the process part to this (and it's working):

process:
  file_source:
  -
    plugin: concat
    delimiter: /
    source:
      - constants/file_source_uri
      - clio_cover
  file_dest:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/file_dest_uri
        - clio_cover
  uid:
    plugin: default_value
    default_value: '1'
  uri:
    plugin: file_copy
    source:
      - '@file_source'
      - '@file_dest'
  filename: clio_cover_name


Why to use hook_drush_help() when we have 'description' in hook_drush_command()? When you go to create new drush commands you can define the 'description' element inside the hook_drush_command(), and if you use drush help your_command you will see this description as output.

function onlyone_drush_command() {
  $items['onlyone-list'] = array(
    'description' => dt("List the configured content types to have Only One node."),
    'aliases' => array('ol'),
    'examples' => array(
      'drush onlyone-list' => dt("List the configured content types to have Only One node."),
    ),
  );
  return $items;
}

Command:

drush help ol

Output:

List the configured content types to have Only One node.

Examples:
 drush onlyone-list  List the configured content types to have Only One node.

Aliases: ol

But once you implement the hook_drush_help() and you use drush help your_command you will see the description defined inside this hook and you'll never see again the description defined inside hook_drush_command().

function onlyone_drush_help($section) {
  switch ($section) {
    case 'drush:onlyone-list':
      return dt('This is from help');
  }
}

Command:

drush help ol

Output:

This is from help

Examples:
drush onlyone-list  List the configured content types to have Only One node.

Aliases: ol

So, why to use hook_drush_help() when we have 'description' in hook_drush_command()?

The answer is context.

The command data pulled from hook_drush_command() is used when listing of all available drush commands with the command:

drush

So if a user is curious, "What drush commands do I have, and what do they do?" hook_drush_command() would provide that snippet. This could be useful for a short description in a directory of commands.

If a user is curious about a specific command:

drush help my_command

That's where hook_drush_help() would be more applicable as it can provide a detailed description that is only about that command queried.


Is there a number field with + and - feature? I am working with Form API to create a customized form shown in a block. Most of the fields are textfields.

I need a +/- feature for a numeric textfield, i.e.:

Is there an existing field like the above I can use?

Try the Stepper Field module

  The Stepper Field module is based in a plugin for jQuery UI called jQuery.ui.Spinner and provides a new steps widget that can be added to any Integer field.

Here is the image


Using hook_form_alter to change exposed filter from a textfield to a checkbox While Views in now in Core in Drupal 8, Better Exposed Filters, a popular module for Drupal 7, is not yet ported to Drupal 8.  So I need some way to do some of the same things.

I have an underlying Numerical field, and have configured an exposed filter that matches a value of 1 when the field has a value of > 0, and 0 otherwise. This works, but Views renders the field as a text field.  This is very ugly, and you'd think it would be simple enough to change the form field in the exposed filter form to a checkbox.  You'd think that changing the '#type' via hook_form_alter would do the job.

Except, this does not work. I've tracked the problem down to code in ViewExecutable::_build($key), around line 1269:

$rc = $handlers[$id]->acceptExposedInput($this->exposed_data);

If I change the '#type' of the form field to 'checkbox', $rc is always TRUE, even if when the type was still a textfield, $rc would be FALSE. This pretty much guarantees that the view will never return any matching rows.

The problem appears to be that the array ViewExecutable::$exposed_data have values of 1 (rather than the correct value of '') once type is changed to 'checkbox'.  Since ViewExecutable::$exposed_data has access "public", I still haven't figured out where in the code the wrong values get assigned.

I'm not sure why it's so hard to do something that is normally very simple using form_alter.  Any ideas as to how to get around this problem will make me (and my client) very happy.

Just entered this as a bug: https://www.drupal.org/node/2651102. The underlying issue is that Views checks for an empty array (among other things) to see if a filter has a value set. Unchecked checkboxes results in an array of zeros.


View fields from the same database column So, I have serialized data within the uc_orders table. This data has several parameters of interest each of which I want to create a unique field from.

Each one of these $data values work on their own. Obviously I am rewriting the value on the second declaration. How can I reference the same data location twice so that both of the fields can be used and I can explode all of my serialized data into separate fields?

  function uc_order_views_data() {
    $data['uc_orders']['data'] = array(
      'group' => t('Order') . ':data',
      'title' => t('Arrival Date'),
      'help' => t('Arrival date choosen by customer during checkout.'),
      'field' => array(
      'handler' =>'uc_order_handler_field_arrive_date',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
    );

    $data['uc_orders']['data'] = array(
      'group' => t('Order') . ':data',
      'title' => t('Ship Date'),
      'help' => t('The date to ship the order by.'),
      'field' => array(
      'handler' =>'uc_order_handler_field_ship_date',
        'click sortable' => TRUE,
      ),
      'sort' => array(
        'handler' => 'views_handler_sort',
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      ),
    );
  }

I finally found the answer.

  $data['uc_orders']['data2'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Arrival Date'),
    'real field' => 'data',
    'help' => t('Arrival date choosen by customer during checkout.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_arrive_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

  $data['uc_orders']['data'] = array(
    'group' => t('Order') . ':data',
    'title' => t('Ship Date'),
    'help' => t('The date to ship the order.'),
    'field' => array(
    'handler' =>'uc_order_handler_field_ship_date',
      'click sortable' => TRUE,
     ),
     'sort' => array(
       'handler' => 'views_handler_sort',
     ),
     'filter' => array(
       'handler' => 'views_handler_filter_string',
     ),
  );

The solution is to add 'real field' => 'field name', and change the $data id.


Set translated field I'm having some trouble finding how to handle field translations in the documentation.

I have a requirement to keep certain fields in English and Japanese. I periodically have to update nodes and taxonomy terms programmatically. I'm doing this with a combination of EntityQuery and the Entity class.

Is there a set function that takes a language code? For example;

$term->set('field_my_field', 'my value', 'ja');

You update another translation by getting an object for that language, and then you set the values of those fields.

$translation->set('field_my_field', 'my en value');
$translation = $term->getTranslation('ja');
$translation->set('field_my_field', 'my ja value');
$term->save();

Those translation objects are actually shallow clones that have a different internal active language code, so you can update multiple translations and then save, for example.


Updating Drush with Composer I've been using Drupal for several years, but only just dipping a toe in with Drush - I've bought an ebook tutorial and working my way through. I've installed Composer, and used it to install Drush. The tutorial book specified a particular build of Drush to install (7.0.0-alpha5). I've navigated to a drupal folder and run

drush st

to get installation info which works fine.
The tutorial explains that you don't have to navigate into the drupal folder to do this, instead using

drush --root=PATH-TO-DRUPAL-SITE st

however this brings an error:

Fatal error: Call to undefined function conf_path()

Googling this error suggests this a problem with the version of Drush and to upgrade.

SO I've navigated into the .composer/vendor/drush/drush folder and run
    composer global update
but composer says nothing to update, confirming the version as 7.0.0-alpha5 - I assume this is not the latest 7.x version, so do I need something changing in the composer.json file?

If you want to update your global installations of any package under composer, you can just do this:

composer global update

You don't need to navigate to .composer/vendor/drush/drush

However: There are a couple of things:

1) Your global composer.json file might have a version constraint.

Check out drush's packagist page: https://packagist.org/packages/drush/drush

That will show you the available release versions of drush.

Edit ~/.composer/composer.json so that the version constraint for drush/drush is higher than the one you have. Probably something like "~8".

Do composer global update.

2) It's best practice to install drush per project.

The reasons why are a little complex and might not answer the question here, so I'll just link to an article: https://pantheon.io/blog/composer-vs-drush-make-which-should-you-use


What's wrong with a new installation of Drupal 8.6.10? A fresh install of Drupal results in a WSOD including a very helpful error message which says "The website encountered an unexpected error. Please try again later."

I normally install Drupal with the drupal-project template from github and at first, I thought this was a problem with my local DDEV environment. I then tried with MAMP Pro to find exactly the same.

Finally I tried on simplytest.me to realise that it isn't me.

A look at my local error logs reports the following;

"NOTICE: PHP message: Uncaught PHP Exception Twig\Error\SyntaxError:
An exception has been thrown during the compilation of a template
("Attribute "name" does not exist for Node
Twig\Node\CheckToStringNode) in
core/themes/bartik/templates/block--system-menu-block.html.twig"." at
/var/www/html/public_html/vendor/twig/twig/src/Environment.php line
797"

I found that is was possible to access the site via the admin path, and changing the theme to Stark allowed me to view the site.

I then attempted to view recent system messages at admin/reports/dblog - only to once again to get the "Please try again later" message.

Twig version 1.38.1 is broken (or not D8 compatible)

Revert to 1.37.1


How can I stop JavaScript from being cached during development? I have a Drupal 8.00-beta11 site and am trying to dynamically add JS to a page, so that I don't have to clear the cache every time I edit the JS file. I have a custom module (lets call it my_module) in drupal_root/modules. My javascript file is in drupal_root/modules/my_module/js/my_js.js.

I have a my_module.libraries.yml file as follows:

my_module:
  version: 1.x
  js:
    js/my_js.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui

In my my_module.info.yml I have:

name: My Module
type: module
description: ...
core: 8.x
libraries:
  - my_module/my_module
package: Custom
version: 0.1

This loads the JS succesfully, but I need to clear the cache everytime after I edit it to see the changes.

In order to avoid doing this, I added the following to my buildForm function:

$form['#attached']['js'] = array(
  drupal_get_path('module', 'my_module') . 'js/my_js.js',
);

$form['#attached']['library'][] = 'my_module/my_module';

I also placed the following in drupal_root/modules/my_module/my_module.module:

<?php

  function grid_tools_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
  }

  function grid_tools_page_build(array &$attachments) {
    $attachments['#attached']['library'][] = 'my_module/my_module';
    $path = drupal_get_path('module', 'my_module');
  // Add JavaScript/CSS assets to all pages.
  // @see drupal_process_attached()
    $attachments['#attached']['js'][$path . '/js/my_js.js'];
  }

?>

However, none of this has worked and I still need to clear the cache to see my changes. How do I avoid having to clear the cache every time?

I'm assuming you have to clear caches because your JS file is being aggregated? Can't think of a different reason.

That has absolutely nothing to do with how you add your JS file (Most of what you tried shouldn't even work, use #attached][library).

Instead, it depends on the separate settings to aggregate JS or not. You can find them on the Performance settings page. Aggregation is also automatically disabled if you use the provided sites/example.settings.local.php as your settings.local.php, which I strongly recommend when doing development, also for the other things it does like enable verbose error logging and disabling render caching (but keep in mind to always test your code with render caching too).


Limit image file size; if bigger, then decrease file size with lossy compression/resizing/etc. for saving disk space When the user uploads an image with a large file size, I would like to allow him/her doing this (not restricting the file size generally, because many users don't know how to resize an image by themselves), BUT after this, I would like to decrease the file size of this image (the original file!) somehow to save disk space (lossy compression/resizing/etc.).
My site is on a shared hosting, so unfortunately ImageMagick is not available.

This question is very closely related, but does not contain any detailed information about the specific solution: How can I reduce the file sizes of the original versions of uploaded image files?

I also found the ImageAPI Optimize module, which can solve the optimization of the image via the online Yahoo! Smush.It service, but optimization is not a restriction for the file size.
There are some related topics about limiting the file size of an image on Stack Overflow and Super User too:

https://stackoverflow.com/questions/1258634/how-to-resize-an-image-in-c-sharp-to-a-certain-hard-disk-size
https://stackoverflow.com/questions/2094064/how-to-resize-a-picture-to-a-specific-file-size
https://superuser.com/questions/201440/batch-resize-jpeg-images-to-a-fixed-file-size/297029#297029

Is there a Drupal-based solution for this task?

If it's unaccomplishable or too complex, maybe I should use an integrated solution with http://www.jpegmini.com/, but I don't know any modules which solves this.

The built-in functions will not do this.

You will have to write a hook for the form,  upload the image at the original large size and then use Imagemagick (or similar) to process the image.

I only suggest Imagemagick because it's got more tools than GD and you should be able to re-size the image in a loop, testing for filesize and resizing/re-compressing as necessary.


How can I have multiple caches of the same page with different query arguments? Using Drupal 8, I have a page (a node) that has two different renderings depending on a passed in query parameter. This is to support a regular page view in a browser and also an embedded version of the page without the header, footer, etc. Example:

https://www.domain.com/my-page
https://www.domain.com/my-page?version=embedded_view

I've implemented this by using THEME_theme_suggestions_page_alter() in my .theme file to suggest a different page template to use depending on the query parameter. (Perhaps there's a better way.)

When viewed on a site with caching enabled, both of the URLs return the same rendering of the page. How do I get different cached versions for the two URLs?

You have to add a cache context for the query parameter version to the page:

function THEME_preprocess_page(&$variables) {

  $variables['#cache']['contexts'][] = 'url.query_args:version';

}

The context will then be used to vary the cached pages by this query argument.


Drupal 7 Views Organic Groups Complex Relationship I have an Organic Groups setup with many relationships. My groups are separated into 3 primary group types..let's call them:

Trucks
Cars
Vans

All of these groups have group content:

Tires
Rims

I've created a view that is a list of Tires and I need to be able to sort by group type...so I need a list of tires for Trucks (for instance). How do I relate the bundle type?

This worked for me....

Create two relationship:

OG membership from node
Group node from OG membership (Relate to
Above)

Filter by Content Type and use relationship Group node from OG membership.


Customer render $scripts and $styles Short of replacing html.tpl.php and calling drupal_get_js/drupal_get_css functions and tweaking the output as required...

How else can I drop some of the JS or CSS that drupal (D7) seems to include in the resulting markup??

The ajaxPageState object is quite confusing I would rather start from minimal markup and stuff and build from what I know.

Any ideas/???

You can do this with some alter hooks in your themes template file.

/**
 * Implements hook_css_alter().
 */
function YOURTHEME_css_alter(&$css) {
  // Remove stylesheets not required
  unset($css['sites/default/themes/YOURTHEME/css/STYLESHEET.css']);
}

/**
 * Implements hook_js_alter().
 */
function YOURTHEME_js_alter(&$js) {
  // Remove scripts not required
  unset($js['sites/default/themes/YOURTHEME/js/SCRIPT.js']);
}


Difference between Relation and term reference field Can anyone explain, what is the difference from practice point of view between relation (by Relation module) and term reference?

I mean if I will use as product attribute taxonomy term, what type of attribute connection I should use?

In your case you should use https://www.drupal.org/project/entityreference

This one is lighter and does the job without overcomplicating. It simply stores 1 to n relations, which may be used later to display in Views.

Relation - this module is much more advanced and allows you to make:

directional references, example

user A is "boss" of user B

different types of references between same entities, example:

reference type 1:  user C is "friend" of user D

AND
reference type 2:  user C "follows" user D

these references are entities itself, so they are fieldable, could be displayed in Views separately etc.


Can't acces field collection with $content I try to render a field collection in my node--1.tpl.php template with print render($content['field_image_teaser']) with no succes. I followed the example at http://drupal.org/node/1155752

The strange thing is, when I do a print of $content width var_dump () my field is listed:

var_dump ($content);
//...
["field_image_teaser"]=>
      array(1) {
        ["und"]=>
        array(2) {
          [0]=>
          array(1) {
            ["value"]=>
            string(1) "1"
          }
          [1]=>
          array(1) {
            ["value"]=>
            string(1) "2"
          }
        }
      }
//...

but when I do a print of $content ['field_image_teaser'] the var_dump print out a NULL.

Edite:
I'm using the current recommended version 7.x-1.0-beta4.

With the answer of Neograph734 I spot that the the dump of the field "field_image_teaser" cames not direct form "field_image_teaser". It cames from the $node Object (which is referred in every field), but I can't render that value. There is no output with: print render($node->field_image_teaser);

So is there a way to get the field collection in a renderable form to use the regular template system, or is something else wrong?

field_view_field() would probably do the trick:

$rendered = drupal_render(field_view_field('node', $node, 'field_image_teaser'));

There are other options you can pass to the function (display mode for example), so it might be worth checking out the docs to see exactly how you want to use it.


How to restyle GeoField's proximity filter controls? Background
I am using the modules: geocoder geofield addressfield geophp ip_geoloc libraries to create a store locator view. The user can search the available stores using an exposed GeoField proximity filter.

Question
How can I restyle the GeoField's proximity filter controls? I would like to change the edit box for distance to a select with fixed values, and hide the distance units select defaulting it to miles.

I had a similar issue with editing the exposed form. Form alter is not the right way to go though. You'll need to use element info alter. Take a look at this custom module I threw together for editing the geofield proximity search. You can see what I did, and add/modify functionalities for your needs (although I think i did exactly what you wanted).


Views not saving after upgrading I am upgrading my website from Drupal 6 to Drupal 7.  In the Views module, when I attempt to save a view I now get the following error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'human_name' in 'field list': UPDATE {views_view} SET
name=:db_update_placeholder_0, description=:db_update_placeholder_1,
tag=:db_update_placeholder_2, base_table=:db_update_placeholder_3,
human_name=:db_update_placeholder_4, core=:db_update_placeholder_5
WHERE (vid = :db_condition_placeholder_0) ; Array (
[:db_update_placeholder_0] => Last_update [:db_update_placeholder_1]
=> last update [:db_update_placeholder_2] => [:db_update_placeholder_3] => node [:db_update_placeholder_4] =>
[:db_update_placeholder_5] => 0 [:db_condition_placeholder_0] => 11 )
in views_db_object->save_row() (line 2092 of
/home/yektafil/domains/dl.yektafile.info/public_html/sites/all/modules/views/includes/view.inc).

Does anyone know what's causing this?

The message states that views is missing a database column (human_name) it is expecting to exist. New fields in core or contributed modules are often added by an update process.

It looks as if you need to run update.php, because it was not run after upgrading core or the views module itself. Alternatively, if you have drush enabled, you can run 'drush updb' from a shell.


Drupal error after creating new theme ,Undefined variable: hide_site_name and other similar error I am new to drupal theme . I have created a direcory mytheme and added mytheme.info to it and copied other files from drupal's default theme directory . Now after editing the page.tpl.php, drupal is showing the errors below .

Notice: Undefined variable: hide_site_name in include() (line 99 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined variable: hide_site_name in include() (line 109 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: featured in include() (line 168 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: highlighted in include() (line 187 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: sidebar_second in include() (line 212 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: triptych_first in include() (line 220 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: triptych_middle in include() (line 220 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: triptych_last in include() (line 220 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: footer_firstcolumn in include() (line 230 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: footer_secondcolumn in include() (line 230 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: footer_thirdcolumn in include() (line 230 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).
Notice: Undefined index: footer_fourthcolumn in include() (line 230 of C:\wamp\www\dtest\sites\all\themes\mytheme\bartik\templates\page.tpl.php).

After searching on google, I have found that clearing cache will solve the problem . But even after clearing my cache,it remains the same !

It looks like you copied the Bartik theme and put inside your "mytheme".
Do you create new theme or just create theme base on the Bartik theme?
If you want to create the subtheme base on Bartik theme. Please add the default regions in your new mytheme.info like from link : Problems creating Bartik sub-theme

You may also check the tutorial from How to Customize Bartik. It's the nice tutorial for creating subtheme base on Bartik theme.


How do you find out which module is causing a redirect? I have a Drupal 7 site and have a bunch of custom modules installed. Currently when I hit a specific node/9283 it gets redirected to another page. I'm not sure which module is causing this redirect. I also check URL Alias and nothing is there for redirection. Its definitely something custom. How would you go about debugging this and figuring out which module/code/function is being loaded on this redirect to another page on the same site?

If we're talking Drupal redirects (i.e. drupal_goto calls), the Devel module could help out here. In its settings it has a Display redirection page option that halts redirection for inspection.

You can use this in conjunction with a hook_drupal_goto_alter() invocation to dump a stack trace on the redirection halt page to find the origin of the drupal_goto call.

function MYMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  ddebug_backtrace();
}


How to prevent caching of a page? I've set a custom homepage url at example.com/welcome.
The user comes to the example.com/ and logs in on that page. Drupal redirects to
example.com/welcome

Now the user clicks on the home page which loads example.com/ from browser cache (which has the login form on it).

I guess if Drupal would reload the homepage at example.com/ instead of example.com/welcome I wouldn't have that problem. How would I do that?

What else could I be doing?

Btw, anonymous pages are getting cached by varnish.

drupal_page_is_cacheable can also be used.

Calling:

drupal_page_is_cacheable(FALSE);

Should do the trick.

And for Drupal 8:

Drupal::service('page_cache_kill_switch')->trigger();


Message (from message stack) not translated into the preferred language of the recipient Here is a code which can be pasted into devel/php (run php code) if the message template new_user_register exists with a user reference field called field_user_reference

This message should be sent when a new user register himself (But this has no link with my problem as the code can be run outside... I provide this information just to give some context)

$id=127;
$account=\Drupal\user\Entity\User::load($id);
$message=\Drupal\message\Entity\Message::create([
    'template' => 'new_user_register',
    'uid' => $id
]);
$message->set('field_user_reference', $account);
$message->save();

$subscribers = \Drupal::service('message_subscribe.subscribers');
$notify_options = [];
$subscribe_options = [
    'notify message owner' => TRUE,
    'notify blocked users'=>TRUE, //new user is blocked
    'entity access'=>FALSE, //new user don't have access (blocked)
    'uids' => [new \Drupal\message_subscribe\Subscribers\DeliveryCandidate(['subscribe_user'], ['email'], $id)],
];

$subscribers->sendMessage($account, $message,$notify_options,$subscribe_options);

Even if the template is translated, the user 127 will not receive the message in his preferred language but in the site default language.

Is it a bug or am I missing something?

I have made a path here: https://www.drupal.org/project/message_notify/issues/2965975#comment-13559090

Feel free to test it and report any problem


Apply style to administration interface I would like to do a minor change to the form in which articles are added, it's just a few lines of CSS. However drupal doesn't seem to load the stylesheets of my theme if the admin interface is used in non-overlay mode.

So is there a way to add CSS to the administration interface without touching the system stylesheets?

Without having to do too much you can use CSS Injector: https://www.drupal.org/project/css_injector

Just install the module and then make your CSS rule to only work on the assigned admin theme.

There are of course other ways to do this, you can write a custom module and add CSS that way as well.