Using Drupal 7 & Omega 3.x - Page Titles + Edit Tabs are not showing up on node content types! It seems that my page titles and the edit tabs have disappeared. I'm currently using omega 3.x and drupal 7. However the weird thing is that its showing up one content type, but not on others. I even created a new content type and it still doesnt show up. I also disabled the theme and enabled the default seven theme as the main one and it does show up. So it is in fact omega's subtheme that is causing the issue when i enable it.

it seems that it is a bug in omega. https://www.drupal.org/node/1906744 -- this took quite awhile to figure it out! The culprit was actually the "main content" block not being enabled on the blocks page. This was because I was primarily using context in positioning my blocks and left the default blocks page empty by not assigning anything. It seems that the theme has to detect the "main content" block in order to show the tabs. So the fix is just assigning the "main content" block back into the content region.


How to build a url to an (AJAX driven) exposed filter? There are quite some threads about it, but none seems to do the job for me.

I'm using a better exposed filter on a view, and I'm trying to build a link that would expose the results by a query in the url.

Eg: domain.com/myview?filter=term-id

Why am I looking for this? When I use the regular approach (using Taxonomy display) it would use an url like this domain.com/myview?filter=some-stuff, and the exposed filter wouldn't work anymore but for the terms specified in the url. All the possible results are limited to what's in the url, while it should be able to filter on all the results, regardless of what's in the url.

In my console I found something like this when I'm using the exposed filters: domain.com/en/views/ajax?field_sector_tid=6

I wish I could translate that behaviour to an url. Anyone ha an idea how I can achieve this please?

If I understood well, once I face the same situation than you, the module Views Filter Harmonizer help me to solve my issue.

From the module's page:

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering.

  Normally, when a Views field has been assigned both an exposed filter
  and a contextual filter, then both filters get applied to the View's
  results set -- always. This is not configurable behaviour. It's
  hard-coded.


My administration menu dissapears when installing a module I have created a module that implements hook_menu() using the following code:

function mypbm_menu() {
  $items['pbg'] = array(
    'title' => 'Theming example',
    'description' => 'Examples of implementing theme functions.',
    'page callback' => 'pbg',
    'access callback' => TRUE
  );
  return $items;
}

function pbg($id) {
  $stringit = $id;

  return $stringit;
}

The module works the way it is supposed to work; when it is turned on, the Administration menu module disappears.

Does anyone know why?

The reason in my case was the character encoding of the "mymodule.module" file.
Changing it back from "UTF-8" to "ANSI" solved the problem.


how to add UTM Source to RSS Links? I have pressflow 6.22 website (drupal 6.22). I need to add UTM Source to RSS links so i can track the page views that come from RSS in google analytics.
how can i do so?
Thanks for your help

You can create an RSS feed of your own using the Views module. It may seem a bit overkill to redefine the entire feed for just an extra parameter, but you may need more customization in the future, and having your feed served using Views allows all kinds of customizations in the future.


How to display parent Taxonomy ID in REST export I want to configure REST export View in which I display taxonomy term name, id and parent ID. How to insert parent taxonomy term id, why it's not available in FIELDS?

Here is current REST export settings, I only missing parent term ID.

Unfortunately, this is currently not yet supported. We're working to add that capability in https://www.drupal.org/node/2543726.

Long story short: the $term->parent field is a special snowflake: it's not an entity reference field as you would expect!


How to create menu when dynamic routes This link https://www.drupal.org/node/2122201 suggest us to make use of route_callbacks when we are using dynamic routes.Can someone tell me how to make use of this route name in *.links.menu.yml file to make menu? The problem is when we are returning $route_collection in the routes() function then it must be containing multiple routes then how to generate menu for any particular dynamic route.
 I did a search inside menu_tree table in the database and find out that no menu has been created with help of dynamic routes so I am beginning to think whether this is possible or not. If it is not possible that what is the possible solution?

You need a derivative plugin, see views module for an example, it dynamically generates menu links for views configured to have a menu entry


How to Pass argument from URL to field in Views I need some help about the follow case:

I have a json file from webservice that i extract all informacion and shows into a view. (I have a module that do it)
The json file is specify in a field into a views:
    Json_file: "http://[path]/event/4.json"

However, only show all informacion about the EVENT 4 ("event/4").
My question is: Is there any solution to pass an argument and change the url that is defined in the field of the route? (Only change the number after "event/")

For example:
Json_file: "http://[path]/event/4.json"
Json_file: "http://[path]/event/5.json"
Json_file: "http://[path]/event/3.json"

Note: The structure of the URL is static, always have the same structure.

This is done using contextual filters. The easiest way to do it is to set up a "page" display by clicking Add+ on the views page. Give the page the URL of http://[path]/event/% (you may also have to try %.json depending on the exact call you are trying to make, the json files are known to drupal right?). The % gives you the argument you are looking for. Then you need to set up a Contextual Filter found under the advanced section of the view. Here you pick the field you are passing the number 4 or 4.json to and choose the correct settings. You may find that you need to pick Provide Default Value for this exact case and then use raw value from url or even php code and do some magic on the $argument (depending on exactly what it is you are doing).


How to filter content by a specific taxonomy term when vocabulary allows multiple values? I have defined a vocabulary that allows multiple terms to be checked for a Content Type and I would like to create a View that could gather all the data from that Content Type but grouping the results by a specific term.
When I'm not applying any contextual filter, the result list should contain a group of data for every term in my vocabulary. Naturally, some of the items will appear in multiple groups because of the multiple terms scenario.
I would like to create a contextual filter for a specific term and get as a result only one of those groups. The problem is that I'm getting not only the group I expect but other groups in which some of the results have more than one term selected for the same vocabulary.
For example:

Content type is "Dogs".
Vocabulary is "Places".
Taxonomy terms for "Places" are: "Kitchen", "Living room", "Garage", "Outside".

"Dogs" has a field called "Places to play with my owner" which is related to "Places" and the user can select one or more options.
I created a view that has:

A relationship with "Places" vocabulary.
A contextual filter that retrieves all the "Dogs" that play on each of those places when there is no specific term to filter.
A field group using the "Places" term names.

And retrieves the following results on a URL like: /dogs/places-to-play/:

Kitchen: Dog A, Dog B.
Living Room: Dog A.
Garage: Dog C.
etc.

The contextual filter should receive a "Places" term name via URL like: /dogs/places-to-play/kitchen and the expected result would be:

Kitchen: Dog A, Dog B.

But in my case, the results are:

Kitchen: Dog A, Dog B.
Living Room: Dog A.

Because "Dog A" has options "Kitchen" and "Living Room" selected in its "Places to play" field.
The question is: Is there a way to avoid getting the extra groups?
Thanks in advance.

To solve the problem:

Removed the relationship with "Places" vocabulary and used the field "Places to play" to create the field groups, checking the "Use rendered output for a group of rows" option.
Unchecked the "Display all values in the same row" option for "Places to play" field.
Created a contextual filter for "Places to play" field to receive the value via URL.

As a result I now get what I was expecting.


How can I temporarily prevent any logins? I've a high visitor website in Drupal 6. For performance reasons I've removed Captcha on all pages.
I don't want anybody to log in and  we don't logout.
Can I rename any Drupal file related to login-functionality? I have SSH access and also use drush. When I want to enable login functionality I've move the file back.

The correct way to avoid users can access the login form is changing the access callback of the route used for the login form and removing the login block from any page.
Altering the form with hook_form_alter() or hook_form_FORM_ID_alter() and setting $form['#access'] to FALSE would just hide the form to the users, who would just see a blank page.
Altering the access callback, users would see an access denied error page if they try to access the login page entering directly the login path in the address bar of the browser (http://example.com/user/login, if clear URLs are enabled, or http://example.com/?q=user/login, in the case clear URLs aren't enabled) which would make clear the login page is not accessible to them. Plus, Drupal wouldn't show any link pointing to the login page, if users don't have access to that route. This means that, if you have a module that adds a link to the login page, that link would not be shown to the users who cannot access the login page.
Since the User module is already using an access callback for user/login, it's sufficient to change it, for example with the following code.
function mymodule_menu_alter(&$items) {
  if (isset($items['user/login']) {
    $items['user/login']['access callback'] = FALSE;
  }
}

Setting the access callback to FALSE makes user/login not accessible from any user.
I would not use that code, if I am not totally sure users aren't automatically logged off, for example because the session cookie has expired, or because there is a module that logs them off when their session lasted too long.


Wrap a field in html from template I have an Article content type that has related_news field. It displays inside the article text as a box.

In node--article.tpl.php I have the following code:

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

I found that I can hide the related_news field using hide as:

hide($content['field_related_news']);

Is there any function like hide that could able to wrap the that field in custom HTML like
...
?

I tried the following:

//$content['field_related_news'] = "***". $content['field_related_news']."***";

But it causes to hide the field from the node.

You can achieve this by creating field tpl file.

Refer field.tpl.php

Create tpl file named as field--field_related_news.tpl.php


How to translate custom fields in taxonomy terms? I would like to have custom fields with translatable content in taxonomy terms. Is this possible with existing modules?

I know that this is possible if I use nodes instead of taxonomy terms: I can make fields translatable using the entity translation module and edit the different versions of the field by switching the language on the node edit page.

I am also aware that the taxonomy translation module allows to "localize" a vocabulary in the sense that its terms can have a different name and description for each language. I want not only name and description to be localizable but also custom fields that I have attached to the vocabulary, in particular text and image fields. Is this possible with existing modules?

If you use 'Localize' option for taxonomy translation mode, it is possible to add taxonomy custom fields to string translation:

/**
 * Implements hook_i18n_string_list_TEXTGROUP_alter().
 */
function YOUR_MODULE_i18n_string_list_taxonomy_alter(&$strings, $type, $object) {
  if ($type == 'taxonomy_term' && $object) {
    if (isset($object->FIELD_NAME)) {
      $term_FIELD_NAME = field_get_items('taxonomy_term', $object, 'FIELD_NAME');
      $strings['taxonomy']['term'][$object->tid]['FIELD_NAME']['string'] = $term_FIELD_NAME[0]['value'];
    }
  }
}

After clearing cache the field will be available in translation form.


how to connect android app to drupal database? I have a Drupal Site with content. I now want to make an Android App. Obviously, I would like Android App to access my Drupal site database - has anyone tried this?

From what I have read (from Google), it seems that I could use something like the phonegap module, or the Services module.

Am I on the right path? Are there other modules/tools/features I should be researching?

Here is a module that will help in this venture, for Drupal 6.x and 7.x sites:

DrupalGap

It leverages PhoneGap (Cordova), Drupal + Services + Views Datasource (Views JSON). It provides a starting point for creating multi platform (Android, iOS, etc) mobile applications for Drupal websites.


Options form with FieldPluginBase? I tried some variations on the code below, but I have not been able to pass my custom form options to render().

class CustomField extends FieldPluginBase {

  public function query() {
    // This is a custom field.
    // Leave empty to avoid a query on this field.
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['my_options'] = [
      '1' => 1,
      '2' => 2,
      '3' => 3,
    ];
    return $options;
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {

    //Form select element.
    $form['my_options'] = [
      '#type' => 'select',
      '#required' => TRUE,
      '#title' => $this->t('My Options'),
      '#options' => $this->options['my_options'],
      '#description' => $this->t('Description.'),
      '#default_value' => 1,
    ];
    parent::buildOptionsForm($form, $form_state);
  }

  public function render(ResultRow $values) {
    return kpr($this->options['my_options']);
  }

}

As is the ['my_options'] key is empty. If I create the $options['my_options'] in buildOptionsForm() it does populate the select list in the views field form. Both, however, break the output of the render(ResultRow $values) function. No errors, just no output.

How do you create and pass options from defineOptions() to buildOptionsForm(), and inevitably access them in render(ResultRow $values)?

Trying to reference:
FieldPluginBase::defineOptions and Field::buildOptionsForm without success. As well as referencing: https://www.webomelette.com/creating-custom-views-field-drupal-8

$this->options and #options of the select element are two different things.

See the separator field of NumericField::buildOptionsForm:

$form['separator'] = [
  '#type' => 'select',
  '#title' => $this->t('Thousands marker'),
  '#options' => [
    '' => $this->t('- None -'),
    ',' => $this->t('Comma'),
    ' ' => $this->t('Space'),
    '.' => $this->t('Decimal'),
    '\'' => $this->t('Apostrophe'),
  ],
  '#default_value' => $this->options['separator'],
  '#description' => $this->t('What single character to use as the thousands separator.'),
  '#size' => 2,
];


Switching out the autocomplete items in a user based entity reference I'm working with an entity reference field in Drupal 8.3. It resides on a node and references users using the autocomplete widget. I have it setup to use an entity reference view for both what it is doing the lookup on and what it is showing. However no matter what modifications I seem to make to the view the auto complete always returns the referenced email address the new search criteria from the view is working ( it looks up the email by first or last name). Instead of the email however, I'm trying to instead show the users first name and last name as listed on the user entity.

I'm not sure if this is a bug in 8 as I remember this working in 7. Please let me know if there is anything I'm missing. If you need more info please just let me know. Thanks in advance for any help you can provide.

In case anyone else stumbles on this... Its currently broken in 8.0x+ https://www.drupal.org/node/2174633


TB mega menu does not work anymore I'm working with the TB mega menu module. Two days ago it worked perfectly; now I have this error:

  Fatal error: Call to undefined function libraries_get_path() in
  C:\wamp\www\drupal\sites\all\modules\tb_megamenu\tb_megamenu.admin.inc
  on line 45

How can I fix it?

libraries_get_path() is provided by the Libraries module. That error indicates that the Libraries module is either missing or not enabled.


Why do D7 form builders have a $form parameter? In Drupal 7, the first parameter of a form builder function is $form.

When implementing a form builder function, one has the option of either adding stuff to this existing array and returning it, or creating a new $form array, discarding what was passed into the function. In my experience, both of these options usually work fine.

What's the point? Is there ever a case when this parameter is needed?

I think to vaguely remember that this is somehow relevant when a form is rebuilt, so this would be the old form.. but I would not really know what to do with it.

Note: The same question already exists for Drupal 8, but it seems to be a policy here that we need distinct questions for D7 and D8. I was going to answer it for D7, and I realize it would be off-topic in the D8 question.

At least for D7 there is one scenario where the passed-in $form parameter does make a difference.

With hook_forms(), it is possible to define a 'wrapper_callback' for a form definition for a specific form id.

From the hook documentation https://git.drupalcode.org/project/drupal/-/blob/7.69/modules/system/system.api.php#L1821:

/**
 [..]
 *   - wrapper_callback: (optional) Any callable to invoke before the form
 *     builder defined in 'callback' is invoked. This wrapper callback may
 *     prepopulate the $form array with form elements, which will then be
 *     already contained in the $form that is passed on to the form builder
 *     defined in 'callback'. For example, a wrapper callback could setup
 *     wizard-like form buttons that are the same for a variety of forms that
 *     belong to the wizard, which all share the same wrapper callback.
 */

So if a wrapper callback was defined, then the $form array passed as a parameter may already be prepopulated.

I found some contrib modules where this is being used (simply grep for 'wrapper_callback'):

ctools does not set the wrapper callback in hook_forms(), instead it sets $form_state['wrapper_callback'] directly.
entity uses hook_forms() to set a wrapper callback to a form definition, but also sets it in $form_state['wrapper_callback'] directly.
media_bulk_upload does use hook_forms() to specify a wrapper callback.


Can't update radio button fields after ajax callback I'm having troubles with a FORM in Drupal 8, the idea is:

Chose a radio value from radio-estaciones to recharge radio-contaminantes, but, after the callback, the result I see is empty, but in replace command I use, I see it correcly

This is the code of buildForm

public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state){

    $arrRadioContaminantes = array();
    $arrRadioContaminantes["0"] = t("ALL");

    //My function to access DB
    $result = \Drupal\map_data\Controller\Contaminante::list();
    foreach ($result as $it){
        $arrRadioContaminantes[$it["id_contaminante"]] = t($it["description"]);
    }

    $form['radio_contaminantes'] = array(
        '#type' => 'radios',
        '#options' => $arrRadioContaminantes,
        '#ajax' => [
            'callback' => '::seleccionContaminantes',
            'disable-refocus' => true,
            'event' => 'change',
            'wrapper' => 'radios-estaciones',
            'method' => 'replace'
        ]
    );

    $form['radio_estaciones'] = array(
        '#type' => 'radios',
        '#id' => 'radios-estaciones',
        '#options' => ['-1'=>t("SELECT CONTAMINANTE FIRST")]
    );

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
        '#button_type' => 'primary',
    );

    $form_state->setCached(false);
    $form_state->setRebuild(true);

    return $form;
}

This is callback function:

public function seleccionContaminantes(array &$form, FormStateInterface $form_state){
    if($form_state->getValue("radio_contaminantes") != 0){
        $form['radio_estaciones']["0"] = t("All");
    }

    //My Database function
    $resultado = \Drupal\montar_mapa\Controller\Estacion::list($form_state->getValue("radio_contaminantes"));
    foreach ($resultado as $it){
        $form['radio_estaciones'][$it["id"]] = t($it["name"]);
    }

    $ajaxResp = new AjaxResponse();
    $ajaxResp->addCommand(new \Drupal\Core\Ajax\ReplaceCommand('radios-estaciones', \Drupal::service('renderer')->render($form['radio_estaciones'])));

    return $ajaxResp;
}

I try returning $form['radio_estaciones'] with same results, and try DataCommand pasing new values, same result... I need help

After change type to 'select' works fine.

Drupal have this bug active

https://www.drupal.org/project/drupal/issues/2758631

Same situation with checkboxes


Admin toolbar unstyled list I successfully migrated a Drupal site I'd been working on to my local machine. The site itself and its content are all fine, but when I login as administrator, the admin toolbar is an unstyled list, as seen here.

I seem to have the same problem as described in this other thread; however, I have tried the solution suggested with no success.

All the permissions are correct, either 755 (folders) 644(files), and I did a recursive chown on the entire directory. I flushed the caches before I migrated the site and then again when I got it live locally. I am using the admin toolbar module, so I tried uninstalling, no change, and reinstalling, no change.

If I observer the console output from web browser, when I log in as admin, I get the following:

  The stylesheet http://localhost/drupal/?og6o9k was not loaded because its MIME type, “text/html”, is not “text/css”.

  SyntaxError: expected expression, got '<'

I don't know if these are related, but they are the only noticeable difference when I log in as admin, so I'm acting as if they are related.

Have you tried turning off CSS aggregation and seeing what happens?

The fact that it's trying to load a stylesheet at "http://localhost/drupal/?og6o9k" makes me think it's an issue with how your public file system is setup. Like it tried to create a CSS file but failed. I would check which folder it's set to and make sure the permissions are correct.

It could also be an issue with the theme. Trying switching to another theme temporarily and see if that fixes things.

Lastly, you can try uninstalling and reinstalling a fresh version of Admin Menu.


Migrating input formats for taxonomies with empty description I am trying to write custom migrations to migrate my Drupal 7 website to Drupal 8. I am currently using Drupal 8.7.10 and Drupal 7.61 for a copy of the production website.

I have tried to migrate description from drupal 7 source and set format as "full_html" for drupal 8.

I have read a lot of sources, for example
Migrating input formats causes errors

I have used this code for migration

description/value: description
description/format: format2

and for process plugin

public function prepareRow(Row $row) {
  $row->setSourceProperty('format2', 'full_html');
}

but format didn`t saved for empty description.

How to save the format if the description is not filled?

The field is empty so it'll get a format set from the configured default when someone enters a description. If there's no value it doesn't need a format, because the format is purely there to say how the value should be displayed.

In theory a value of an empty string with a format attached might give a different result to a null value (the empty string might be wrapped in <p> tags for example) but this will not usually matter in practice.

So the migration is doing what is expected, by not creating an entry for an empty field value.


Displayng menu description under main-menu links in Drupal 7 I am trying to display the menu description under menu links for the main-menu in my custom theme. I have tried overriding the function as given in this post http://fusiondrupalthemes.com/forum/using-fusion/descriptions-under-main-menu #10 comment. But its not working. Can anyone help me on this?

It worked when I used the Main Menu block in header region.

It wasn't working before because the Main Menu was directly being output in the page.tpl.php file by a call to theme('links_system_main_menu'). I followed the instructions on "Descriptions under main menu" at the Fusion Themes forum, and enabled the Main Menu block to get the desired effect.


How to make a popup appear on the side/bottom of the page instead of the center? I'm still very new to Drupal and I've been trying to get a popup to appear on my page in a specific location. Popup on load (https://www.drupal.org/project/popup_onload) does pretty much everything I want, except that it appears in the middle of the screen. Anyone know what I can do so that it'll appear on the side or bottom of the screen? Or know another module out there that has this kind of configuration?

The Popup on Load module leverages the Colorbox module, and its jQuery plugin dependency, to style the pop up. The module allows for your own custom style which will let you adjust the popup position to where you want it. This is covered in its documentation.

  Add a custom Colorbox style to your theme

  The easiest way is to start with either the default style or one of
  the example styles included in the Colorbox JS library download.
  Simply copy the entire style folder to your theme and rename it to
  something logical like "mycolorbox". Inside that folder are both a
  .css and .js file, rename both of those as well to match your folder
  name: i.e. "colorbox_mycolorbox.css" and "colorbox_mycolorbox.js"

  Add entries in your theme's .info file for the Colorbox CSS/JS files:

stylesheets[all][] = mycolorbox/colorbox_mycolorbox.css
scripts[] = mycolorbox/colorbox_mycolorbox.js

  Go to "Configuration" » "Media" »
  "Colorbox" and select "None" under "Styles and Options". This will
  leave the styling of Colorbox up to your theme. Make any CSS
  adjustments to your "colorbox_mycolorbox.css" file.


Add fields to entityform, when it's created Is that possible that I set default fields for entityform types when it's created? There will be site admin users. They will create registration forms for events, but there are 2 mandatory fields that they forget about sometimes, but they have to add it, because it breaks a few modules. Like voucher code and the email fields. Also, they sometimes recreate a field with different names. Like they add a new email field, with the name "field_email" address, but the field I'm checking is the "field_email_address". I want to add these fields to the form programmatically, right after the site admin clicks the "Save entityform type" button, but only when he creates it first. Is it possible to add a field programmatically to an entityform? And if it is, then how? Thanks in advance!

Yes it's possible  here's the steps on how to achieve that functionality.

1. First you need to alter the entityform and add your custom submit handler

Example:

/**
 * Implement hook_form_alter().
 */
function example_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'entityform_type_form') {
    $form['#submit'][] = 'add_new_fields';
  }
}

2. Create your custom submit handler, you need field_create_field(), field_create_instance() in creating your field, define all the details of your field inside the $field and $instance array

/**
 * Submit callback adding custom field when saved entityform type.
 */
function add_new_fields($form, &$form_state) {
  // Create email address field.
  if(!field_info_field('field_email_address')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_email_address',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_email_address',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Email address',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
   // Create voucher code field.
  if(!field_info_field('field_voucher_code')) {
    // Create your new field.
    $field = array(
      'field_name' => 'field_voucher_code',
      'type' => 'text',
    );

    field_create_field($field);

    // Create field instance.
    $instance = array(
      'field_name' => 'field_voucher_code',
      'entity_type' => 'entityform',
      'bundle' => $form_state['values']['type'],
      'label' => 'Voucher code',
      'settings' => array(
        'entityform_type_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
}

Here's the link of working custom module that i created https://github.com/umandalroald/entityform-custom-callback


How to hijack the route response? I have a configuration form that if it wasn't previousely configured should be the only thing that the user is able to see.

I would like to hijack the response for the current page and display the form, no matter what url the user is currently on. I could do a redirect but I would rather learn how to do it this way.

I presume this is done via EventSubscriber, I'm just not exactly sure how. Do I have to render the form and set is as response? Or can I just alter the controller for active route? Which would seem more DX friendly to me.

*I am not looking for contrib module to do this.

--

I was looking at the kernel events but the only viable events were

request - which already had the route "loaded"
controller - which is fine but in most cases it requires DI stuff so I cannot swap it so easily, and
response - too late, creating a new repsonse is not good for performance

It could be done with Rules:

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

set up a field for the user, boolean and use Field Permissions to hide it from users:

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Rules, Event - Drupal is Initialising
Condition - Data field is empty, user field previously set up
Action - redirect to form

Then you can set up an override for the form submit to set the user data field (or use Rules to do it), so that the condition is no longer met.


Is It Safe to Delete Content Types "Article" and "Basic Page"? It is highly unlikely we will ever use these in our CMS that we're implementing.  They're just cluttering things up.  Any reason why I shouldn't delete them?

If you're not going to use them feel free to delete them.  There will be no impact if you remove them.


Change the filter widget type in a views When adding a reference field as a filter in a views the default widget of the filter is drop down.
Is there a way to change it to a auto complete widget?

I think you might be looking for something like Views Autocomplete Filters.  The D7 version is in development but it sounds like it might be worth a try.


Mention/Reply to users in comments using @ (@name) I am looking for a feature that makes it possible to reply to comments, or mention users in a comment using the @ symbol.

So, if I was to write the following in a comment on a node:

  @Michael Jackson Cool stuff dude.

"@Michael Jackson" would turn in to a link that leads to his user page.

Also, if it is possible without to much hassle, it would be great if it only turned in to a link if the user exists, to prevent a 404 error.

Thanks.

I think you might be looking for this module but the 7 version is still in dev.

Mentions

  The Mentions module offers Twitter like functionality, recording all
  references to a user's username - using the [@username] or [@#uid]
  filter format - from various locations, providing a centralized page
  to track all mentions.


Summary or trimmed body field formatter does not display anything when the trim length is anything below 888 I am creating a view for blog items to be displayed on the home page.

Obviously I would not want the whole blog to show on the home page and I want a summary of this to be displayed.

Whenever I set the summary to anything less than 888 it seems to delete the markup completely from the page.

Does anyone perhaps have a solution for me? Thank you in advance.

Well I still don't know exactly what the solution to the issue with Drupal's own summary or trim option. I did however get the trim right using the Smart Trim Module. Thank you to the developers of the Smart Trim module.


How do i add a background image to a imput submit button in my module? So i have a input submit button that needs an image.

I've been looking at the module styling documentation where it says i can attach the styling to a render array of a block plugin. What does this mean and how do i do this? I'll include the trimmed down code where i want to include this styling.

LoginBlock.php:

class LoginBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('plugin.manager.pixelpin_openid_connect_client.processor'),
      $container->get('form_builder')
    );
  }

  public function build() {
    return $this->formBuilder->getForm('Drupal\pixelpin_openid_connect\Form\LoginForm');
  }

}

LoginForm.php:

class LoginForm extends FormBase implements ContainerInjectionInterface {

  public function buildForm(array $form, FormStateInterface $form_state) {

        //submit button that i want to add styling too

          $value = 'Log in Using PixelPin';
          $label = 'Log in Using PixelPin';

          $form['pixelpin_openid_connect_client_pixelpin_login'] = array(
            '#type' => 'submit',
            '#value' => t($value, array(
              '@client_title' => $client['label'],
            )),
            '#name' => $client_id,
            '#prefix' => '<div>',
            '#suffix' => '</div>',
          );
    }
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    //code
  }

}

pixelpin_openid_connect.libraries.yml:

pixelpin_logo:
  version: 1.x
  css:
    theme:
      css/style.css: {}

style.css:

#edit-pixelpin-openid-connect-client-enable-login {
  background: #f0f0f0 url(/ppicon.png) no-repeat center;
  cursor: pointer;
  height: 26px;
  margin-left: 0;
  margin-right: 0;
  overflow: hidden;
  padding: 0;
  text-indent: -9999px;
  direction: ltr;
  width: 34px;
}

You can attach it to any render array; the submit button itself seems as good as any:

$form['pixelpin_openid_connect_client_pixelpin_login'] = [
  ...
  '#attached' => [
    'library' => [
      'pixelpin_openid_connect/pixelpin_logo',
    ],
  ],
  ...
];


Printing thumbnail images in DomPDF My print-friendly version replaces the thumbnail images with the hi-res versions which is fine, but the PDF version replaces the images with the alt tag.

Anyone have any ideas on how I can get the PDF varsion (DomPDF) to behave when dealing with the thumbnails?

The problem was a setting in the admin/content/node-type/[your node type]/display (Display Fields settings). The "Print" tab was set to show the images, but PDF uses the "Basic" settings. Changing the "Teaser" setting to "thumbnail" fixed the problem.


Email users on node creation based on taxonomy reference I have 2 taxonomy vocabularies (town and topic) which are referenced on both a user and a node. When a node is created, I need to email all users who are referencing any of the terms referenced on the node EXCEPT when the node has been directly assigned to a user (using a User Reference field).

The Subscriptions module works great for notifying users of all new nodes with a particular term, but I cannot find a way to exclude nodes based on other fields (in my case, the User Reference).

I can use Rules to send an email when a new node is created without the User Reference, but I don't know how to define the recipients as "all users with a referenced term which is also referenced on the new  node". VBO may be the answer, but I'm lost on how to generate the View from Rules.

Any suggestions? Thanks.

Actually, you can pull up all users (or any entity) based on a field value by using the 'Fetch entity by property' action.

Since users (and nodes, and comments, etc) are all entities, you can use this action to pull up a list of users with a certain value in a field.

In your rule, that gets fired upon the update of a node, simply

add the 'Fetch entity by property' action,
select 'User' as the entity type, and
in the final screen choose the field (in your case a term reference) you want to check and the specific value you're checking for.
Feel free to change the name of the entities it will fetch for you.  By default they will be called fetched_entity.

THEN, add a loop to your action set after this fetch, to go through each of the found entities.  In this loop, we'll check for your second field and exclude the necessary ones.  From what I understand, you'll want to exclude the ones whose uid matches the user reference field on the edited node.

So here's how:

By now your rule's action set should look like this: You're fetching users by your taxonomy property, then you'll looping through all the found entries (make sure it's pulling as many as you want, because it limits to 10 by default, by the way).

Now, add a component in your rules.  Components are used when you need an entirely new rule to execute in your action area.  Now that we're looping through users, we need an entirely new rule to call (IF the user doesn't have field x, THEN do y).  However, when we're in the action area, we can't call conditions.  So that's why we'll create a component that's a rule within itself, and call it from here.

Go to admin/config/workflow/rules/components or Configuration --> Workflow --> Rules --> Components
Click to "Add new component"
Select "Rule" for the component plug in.  We don't want it to be just a condition test or an action, we want it to contain both a condition and action!
Call it something like "Email non-referenced users" or something like that
We will pass it two parameters. We need to pass it the user we're currently looping through and the node that has just been changed (that triggered the rule) because we'll compare the user's uid with the node's user reference field.

Add a condition to your component that is a 'Data comparison' condition and compare the looped_user:uid (or whatever you called that incoming parameter) to the user reference field of your updated_node (or whatever you called that incoming parameter)
Careful here, make sure to check the 'Negate' checkbox at the bottom of that condition.  We want to let through only those users for whom the two fields DON'T match, i.e. the ones that aren't referenced.

 - As an action in the component, have the system send out the email you want

Voila!  Almost done.  This component now narrows down our looped users (with the correct terms) to those who aren't referenced and emails them.  The one thing we have left to do is to CALL this component in our user loop.

Go back to your original rule, and click 'Add action' to your loop (not below it, but on it)

In your list of actions, at the very, very bottom, you will see the names of components you have created.  Your new component should be there.  Just select it, and pass it the updated node and the 'fetched_entity' (which is your currently looped users) as the two parameters.

Test!

Hope this helps.


How do I remove text format information from the bottom of my text areas I have a content type which all of my users can create instances of.  The last text area has a section listing the particulars of the text format.  I would like to disable this area so that the test format does not explain itself, and all the user sees is a text area.

You can use the Simplify module for this.

It describes itself as follows:

Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Update site from core dev to stable Using advice from Drush: Update core from stable to dev I ran drush up drupal-7.x in order to switch from 7.7 to 7.x-dev.

However I'm now in the position whereby I want to move the project back to 7.8, however I don't seem to be able to figure out how to do this. I've tried:

drush up drupal-7.8

Which produces:

 Name         Installed version  Proposed version  Status
 Drupal core  7.x-dev            7.x-dev           Specified version available

So it appears to understand I'm asking for a new version, but following this through just updates the site to the latest 7.x-dev.

You could hack the includes/bootstrap.inc file
The very first line of code will be something like:

define('VERSION', '7.11-dev');

Set it to 7.7, and drush should accept that 7.8 is a never release.
I know that hacking core is strongly discouraged, but since the upgrade itself will remove the hack, I think it's more than ok.


Create several form in a same module or function in Drupal 7 I want to create several forms from the same page. And these form I am generating from a custom module. I have already generated the function my_module_form (), but I can only create a single form. How can I generate more forms?

There's nothing limiting you to a single form, your page callback just needs to return a render array containing all of the ones you need:

return [
  'form_1' => drupal_get_form('MYMODULE_form_1'),
  'form_2' => drupal_get_form('MYMODULE_form_2')
  'form_3' => drupal_get_form('MYMODULE_form_3'),
];


Manipulate Database from Drupal I'm new to Drupal 7. Right now I'm trying to use D7 to build an interface that allows me to directly manipulate the tables in the database.
I have installed a couple modules such as Data, Migrate, Feeds, and etc. I managed to create a view to display the table that I created using Data Module, but I need to add and update the rows from the interface.
Furthermore, is it possible to set up relational tables so that I can update or delete related rows at the same time using Drupal?

Thanks in advance

Yea, I just started learning Drupal, even new to the whole CMS thing. I decided to take the chance to learn Drupal for my project. But thanks all for the help I really appreciate the helps. I will come back and vote up the answers when I have enough rep.

Drupal isn't an MVC framework.

Content types and entities give you a way to insert records into a database, and edit them as well.

Making a "view" of one kind of record is possible with the Views module, and also the VBO module.

Deleting "related things" is trickier and requires the use of built-in hooks to remove related items from the database typically. Or if using Entities you could wire removing relationships into the Entity Controller.

Simply put, Drupal isn't a Ruby on Rails-like framework where you get CRUD capability for free; it currently acts more like the Linux kernel (in my opinion) where you register or "hook-into" the lifecycle of a thing and alter it to your needs.

You may find these 2 modules useful:

Model Entities uses Entities to kind of create a CRUD like interfaces for custom objects built with D7 Entity(s).
SBDO an ORM for custom object tables in drupal


How to use variables in a PHP evaluation in a rule? I created a rule with the actions "Provide a variable: mynumber" and "Grant points to a user". I'd like to evaluate the points with PHP, using "mynumber". For some reason, I can't use $mynumber, although that is possible in the PHP evalution of the sections 'Operation' and 'Description'. As the replacement pattern [mynumber] is available, I tried to use it in my code with and without the square brackets, but in both cases, I get the error:

  Notice: Use of undefined constant mynumber - assumed 'mynumber' in
  eval() (line 1 of
  C:\wamp\www\mysite\sites\all\modules\rules\modules\php.eval.inc(146) :
  eval()'d code).

Is this a missing feature, a bug in the Rules module or did I do something wrong?

You can achieve this,  use variable module and define variable which you want use in rule.

To define a variable you need to write custom module , which will contain following function

function My_module_variable_info() {
  $variables['rainbow_count'] = array(
  // 'name' isn't really necessary, as it will get populated from the key of this array above.
 'name' => 'rainbow_count',
 'title' => t('Number of Rainbows'),
 'type' => 'number',
 'group' => 'UserPoints Config',
 'token' => TRUE,
'default' => 0,
'description' => t('Specify the number of rainbows.')
);

}

Set value for variable which you want use in rule through :

configuration>>variables>>modules>>My_module_...

Now go to rules >action> grant points to a user > Points:

Set data type =current-user:uid  and put return variable_get('rainbow_count'); code in PHP evaluation.

This solution worked for me,hope will help you also.


Field template for display mode I have a template for my field: field--field-category.html.twig. Is there a way to override this for a specific Display Mode? A have a mode called teaser block. I tried field--teaser-block--field-category.html.twig as well as a couple of other formats.

I know I can modify how the field is output in node--teaser-block.html.twig but I'd like to do it at the field template level.

For the field template there is by default no suggestion with the specific display mode.

You can add this suggestion in a hook:

function MYTHEME_theme_suggestions_field_alter(&$suggestions, $variables) {
  $suggestions[] = 'field__' .
    $variables['element']['#field_name'] . '__' .
    $variables['element']['#view_mode'];
}

Put this into MYTHEME.theme in the theme directory.


How to hide some fields from user in add content page? I have a content type with some fields created using cck module in Drupal 6 . I want user just fill in some of them in create content page and doesn't see others which will fill later by admin.

How can I do it in drupal 6 ? Is it possible ?

If they are fields that the user is not permitted to use then there is a module included with CCK called content_permissions.

If you install that then you can set role based permissions for each field on the permissions page.

If it is not an issue of access control, but you just want to hide some fields that once, you can implement hook_form_alter() in a custom module to do it.

It would go along the lines of this:

/**
 * Implementation of hook_form_alter(),
 */
function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] . '_node_form' == $form_id) {
    $node = $form['#node'];
    // Only for page content and only when adding a new node.
    if ($node->type == 'page' && empty($node->nid)) {
      // Hide the name field by restricting access.
      $form['field_name']['#access'] = FALSE;
    }
  }
}


Webform live calculations in table/matrix I am trying to create a work time allocation webform. My goal is to create a table (6 columns and addable rows) and get a live sum of all columns at the bottom. (edit: pardon my lacking terminology.  With live I meant client side ajax or js that updates instantly when the user fills in the form, before submitting it)

I tried using a webform and webform matrix module, they allow for a table with addable rows. But I can't get the live sums to work. Is there another method or module I could use that would suite my case better?

TLDR; I need a webform with a table supporting x amount of rows and a live sum at the bottom. Any suggestions what modules to use?

The colored cells are buttons.

Refer to Filter form submission data by a field value with Views, Webform for a tutorial to display the data collected by Webform in a filterable, tabular format, using the Webform module (of course), and the Views module.

After you created an appropriate view, you could consider either of these approaches:

Add the "Views Calc" module to add the "live sums" that you're looking for. Here is an excerpt from its project page:

  This module adds simple calculations to a views table. Requires the Views module.

  You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

And this is a typical screenprint using the Views Calc module:

Refer to my answer to "Total count of two different content types in one View?" for more details about how to use the Views Calc module.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.
Use the Views Summarize module. Here is an excerpt from its project page:

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

There isn't a lot (any?) documentation available about actually using this module, but the "clue" is like so: Click on the "settings" icon for the display style, then enable a summarizer on one of the columns.

Refer to the project's home page for a screenprint of a view using this module.
Addd the calculation via custom logic in views templates, as explained in one of the answers to the question about "How can I add a summary row to a Drupal View?". Here is a quote from that answer:

  ... Create a views-view.tpl.php for your view, and then edit it calculate and print out the summary.

  Another option is to create another display for the same view, and then create a views-view-unformatted.tpl.php and calculate and print out the summary w/o doing a print $row; to avoid calling the fields template. Then add use view display where needed.

Note: the extra clarification (requirement?) about "live" only got added after I wrote most of my answer. I.e. via a comment like "... something client side that updates as the user fills in the form without submitting it first". So far I'm not aware of any module that ALSO supports that. Not sure if there is a way to do that using the "Views templates" approach described above (if there is such way, please add another answer related to that also).


Can I make a Drupal Book page parent with no content? Is it possible to Organize Drupal Book pages under parent pages that are just headings, are not links and have no content?

I want to separate pages under headings but I don't want to create pages for these headings, just to add text to the navigation and use as a parent for pages.

Yes, create a new content type, call it headings, remove the body from it and let it have children.

see http://yoursite.com/#overlay=admin/structure/types/add

Create the heading content type and remove the body, add or remove anything you want or don't want while your there.

Then see:
http://yoursite.com/#overlay=admin/content/book/settings

Add the new content type to the books modules allowed content types and your done.


Find/Replace in File Field I'm working with a site that has many files that have been uploaded to it. Data has been pulled from these files to populate fields such as title, description, etc. Some of these fields contained ampersands which now appear as &.

Is there a way I can batch correct these—such as a find/replace? I tried the Find/Replace Scanner module but it doesn't seem to be able to work with file nodes.

If you can find the file field in question in your database.

Export it as csv.
Use find and replace with excel, save.
Import it back in.
Clear the cache.


All special characters get outputted as question marks I have a Drupal 8 (8.2.5) setup on a Debian Jessie Server PHP 7.0.15-1~dotdeb+8.1 and MySQL 5.5.54. All of a sudden Drupal converted all special characters like ü,ä,ö,ß,–... into question marks like Das mu?? doch nicht sein.

At first I thought, this must be a problem with a false encoding in the HTML header, but the encoding of the page is: UTF-8. Then I realized, that in the database all those characters are really 'converted' to question marks. As I have on the same server many Drupal instances (v. 6, 7 and 8) running, the which never had shown such behavior, I don't think, it is an issue with the server setup. The MySQL logs did not show anything referring to this issue neither.

After restoring the Data base, the same issue occurred again after some days.

I have absolutely no clue, what is going on. Has anybody an idea what could be the cause of this problem?

UPDATE: This problem is getting more wired: It turned out, as soon as I clear the cache, all special characters are gone. A look into the database (with PHPMyAdmin) shows, they really are. When I then restore a former database version, all special characters are shown on the site correctly again, but in the database they are still shown as  questions marks. My first guess was: They are already »converted« in the database dumb I was using, but only correct in the cache table. But, when restore the database and directly edit an affected node, all special characters are correctly shown in the form field. After saving it, they are correct even in the database. So I could restore all special characters by bulk republish them from the /admin/content interface. Also it turns out that not only special character in node fields are gone, but also in path alias and taxonomy terms. For example: Where »ä« should be converted to »ae« within a path alias, it was turned to a »?«.

Let me demonstrate this with some screen shots. The special character in this case was an en dash (–):
This is how it looks like on the site, when the issue occurs, a question mark is shown where originally an en dash was:

PHPMyAdmin shows us in the next picture, that this en dash was really converted to an question mark:

Looking into the backups of my data base with a text editor show, that in there the special characters are not corrupted.

Uploading the database file with Mackup and Migrate or with drush sql-cli < path/to/my/file/database.sql a look into the database shows, it gets corrupted immediately:

But on the site as long as I don't clear the cache all looks good. That means the cache table aren't corrupted. But surprisingly even if I edit an node, it is shown as if it weren't corrupted:

For a commoner like my that leads to the conclusion:

Some how, if I edit a node, it's content is loaded from cache tables!

So my questions are:

Which Drupal module or function could be responsible for touching
all most every database entry, but not the cache tables?
If I re-save a node or entity (without making any change), how is it
possible, that the database entry of the affected fields change?

It turned out that the described problem was caused by the Backup and Migrate module. In fact it is a known bug. So, don't use this module for Drupal 8. It will destroy your entire site.


Show Node fields on Drupal Form I'm working on a form where I have added Company field as entity reference and which is type of auto complete. Is there any way, which can show other attribute of company content type like phone number and email in the form post selecting the company name.

If your question pertains to Drupal 7 then you may want to take a look at the Entity Reference Autofill

  The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


Is there a way to hide the Apply button on an Exposed Contextual Filter? I'm using an Exposed Contextual Filter in a view. It's working nicely; however for aesthetics, we'd like to remove the Apply button and have the view change when the pull down does. How might I accomplish this?

Follow up:

Thanks to both of you Lance and agargy below. Yes, hide the Apply button by checking 'Hide submit button'.

This is a standard feature. Go to the "Exposed Form" settings on your view and click "Settings" next to "Exposed form styles". I don't remember the correct name of the option but i think you get it when you're there.


Drupal Feature pushed to staging site I am just getting into drupal features and wanted to make sure I understood something.

I updated my drupal features. Used Git Flow to finish the branches and create a release.
I pulled the new release branch to the staging server.

My question is after I checkout the release branch and run drush fl - I see the features I worked on and committed as overwritten.

I  know on my local if I want the changes I run drush fu to update them. However I thought I remembered that it is the opposite on the staging server. I did run drush fd to get the diff but still learning to read that better.

Thanks!

When you have an existing feature and you are changing some configurations which are stored in the feature, you have to update your features

drush fua

does an update on all enabled features. After that you deploy your features (propably using git) an then you have to accept the changes done to your feature on the production side.

drush fra

(feature revert all) does the trick.

A better explanation is here: https://drupal.org/node/582680


Internal server error when programmatically updating about 100 nodes I'm writing a function that unpublishes a bunch of event-type nodes within a date range. My query pulls about 100 nodes, but I'm apparently maxing out the available memory. Here is the code in question:

$sql = "SELECT node.nid AS nid FROM node node  LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

$nids = mysql_query($sql);
$report = "";

while ($nid = mysql_fetch_array($nids)) {
    $node_id = $nid['nid'];

    $node = node_load($node_id);

    $node->status = 0;

    node_save($node);
    $report = $node->title . " unpublished.";
}
drupal_set_message($report);

Any suggestions greatly appreciated.

Give your server more memory ;)

Better to use EntityFieldQuery (but this will not speed up your script ..)
You could replace the while loop with foreach (array_keys($result['node']) as $node_id)
In the worst case you'll need to limit the $result or $nids array to 10 or something .. and run the script several times, maybe in cron ?

Or run an update query (also possible without php)

$sql = "UPDATE node node LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid SET node.status = 0 FROM WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

mysql_query($sql);


How do I use twig templates with views? I'm trying to figure out how to use twig templates with views. at the moment I'm just using twig in the view itself but I'm sure I can use twig files to overwrite the styling of the view.

e.g.

        {{ field_category }}
        {{ title }}

I'm using this in the rewrite field of the block view with one field hidden.

How can I translate this to a twig file?

Edit1; I'll try to explain my issue in more detail. I've been working with the page.html.twig file which overwrites the default homepage used by Drupal. I'm wondering if I can do the same with blockviews. Can I overwrite the default layout, meaning html layout, divs, classes, ID's using a Html.twig file for the view?

You can overwrite views-view-fields.html.twig or create your personal views-view-fields--YourViewName.html.twig and apply the div or any wrapper you want.
I advise you to activate the twig debug to follow the suggestions


configuration error directories not present I am brand new to trying to create a web blog so I am hoping you can help me get started. I haven't been able to find answer online.

My status report has this error.

Configuration directories   Not present
Your sites/recoverypractices.dd/settings.php file must define the $config_directories variable as an array containing the names of directories in which configuration files can be found. It must contain a sync key.

I don't know what thes sync key is but I did find a sync folder here D:\Sites\devdesktop\drupal-8.2.5\core\modules\field\tests\modules\field_test_config
I found the following code in my settings.php file but I don't know exactly how to fill in the array or define the sync key.

@code
$config_directories = array(
CONFIG_SYNC_DIRECTORY => '/directory/outside/webroot',
);
@endcode
*/

Can you assist me in figuring out how to fix this error?

Thanks,
David

You can define it in settings.php like so:

$config_directories[CONFIG_SYNC_DIRECTORY] = '/../config/sync';

This sets the default sync directory outside my webroot.

CONFIG_SYNC_DIRECTORY is a constant defined for 'sync'.


How to change a node field when the output of a View changes? I have a View Top 3 that displays the 3 nodes with the highest average voting scores (I use Fivestar via comments on the nodes for voting). Every node has a field Highest ranking, that - as the name suggests - should store the highest ranking ever obtained in Top 3.

Now, the View Top 3 also filters nodes that were created less than 5 days ago. I'm wondering how I can change the Highest ranking fields of the nodes in the top 3 when the top 3 changes. The above explanation should make clear that this can happen when

a new comment with a vote has been created;
an existing comment with a vote has been changed;
a node is older than 5 days and is therefore banned from the top 3.

Which hooks can I use for this?

Implement something like hook_views_pre_render() or hook_views_post_execute() and, every time your "Top 3" view is executed have your code iterate over the results and update the "Highest Ranking" field for each of the nodes in the top 3 as needed.

The only downside of this is that if your "Top 3" view is rarely ever executed then it's possible that a node could move into then back out of the Top 3 without the view ever being executed and thus without your code ever recording the node's presence in the top 3.  If you want to try to avoid this you might implement hook_cron and programmatically call your view every time cron is run.


Testing Email locally? Could i reroute email to watchdog? I'm trying to debug how an email invoice looks in ubercart locally. Mail is not configured on my local machine (ubuntu 11.10).

I really would prefer to debug this locally without sending nagging emails to the stakeholders.

Is there anyway to reroute email output to the watchdog log?

Yes, you can use the Maillog / Mail Developer module.

  Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails to being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the Drupal core. Additionally you can immediately display the mail through the devel dpm() facility.


User-Access return value issue I'm executing the following code in hook_init:

function my_module_init(){
    global $user;

    $apprenticeship = user_access('prevent publishing apprenticeship job', $user);
    drupal_set_message("CHECKING permission[prevent publishing apprenticeship job]: " . $apprenticeship);
    $content = user_access('access content', $user);
    drupal_set_message("CHECKING permission[access content]: " . $content);
}

I am logged in as USER#1 and the prevent publishing apprenticeship job permission is NOT set for user#1.

However, each time my code executes user_access('prevent publishing apprenticeship job', $user) returns 1 i:e true.

As I said, that permission is not set for for the administrator role.

Can anyone help and point out what I'm missing or doing wrong?

PS:

The access content also returns 1 but that is set for the administrator role.

The user #1 is special, in Drupal. It will always have all permissions, even the ones not explicitly set for the administrator role.

See user_access() source code.

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }


How to use Facebook Connect's user picture in Views? I'm using the Facebook Connect Module on my Drupal 7 site. If a user logs onto my site via Facebook, his Facebook user picture gets imported to his account on my site. But now I am wondering whether or not there is any way to show this Facebook user picture in Views. This picture is only shown on the user profile page, not in any view that references the user picture field.

Does anybody know how to do this or is there any way to automatically import the Facebook picture to be the standard user picture?

I found a solution: You can use the following hook to copy facebook's user image and save it as drupal user image. Make sure to ask your users to allow this!

/* Copy facebook image if no user image is present.
   See: http://drupal.org/node/1764176 */
function custom_api_user_login (&$edit, $account) {
  $fbuid = fbconnect_get_fbuid();
  if(is_null($account->picture) && $fbuid && isset($account->data['fb_avatar']) && $account->data['fb_avatar']){
    #$test = fbconnect_user_picture_override(array('fbuid' => $fbuid, 'account' => $account, 'size' => '25'));
    #drupal_set_message(print_r($test, true), 'status', true);

    if(copy("http://graph.facebook.com/".$fbuid."/picture?type=normal", '/tmp/'.$fbuid.'.jpg')) {
      $path = '/tmp/'.$fbuid.'.jpg';
      $file = new StdClass();
      $file->uid = $account->uid;
      $file->uri = $path;
      $file->filename = $fbuid;
      $file->filemime = file_get_mimetype($file->uri);
      $file->filesize = filesize($path);
      $file->status = FILE_STATUS_PERMANENT;
      $dest = "public://" . $fbuid.'.jpg';
      $file = file_copy($file, $dest);
      file_save($file);
      $edit['picture'] = $file;
      user_save($account, $edit);
      #drupal_set_message(print_r('<img typeof="foaf:Image" src="'.$path.'" alt="Naomi Yoshida">', true), 'status', true);
    } else {
      drupal_set_message(print_r('Kopieren schlug fehl', true), 'status', true);
    }
   }
}


Control Views Bulk Operation messages? For my purposes I don't need these types of messages:

2 rows processed in about 261 ms:
Performed Email Reviewers on user joren1.
Performed Email Reviewers on user joren5.

I don't want to hide messages in general. Is there a way to specifically target messages from this module, or specific messages at all?

You can uncheck "Display processing result" in the VBO settings (in the edit view UI).

VBO for D7 stopped generating that many messages in latest -devs (after beta1). It now only shows one message: "Performed $operation on $count items."

That is something that should be backported to D6, there's an open issue for it.
In general, you can't affect those, the module is just calling drupal_set_message (usually in _views_bulk_operations_execute_finished()).


Hide a region with empty view in it I have a region page_intro where I display a view, with some CSS on it. When the view is empty (return no result), the region is still displayed (All html code before and after {{ page.page_intro }}). Is there a way to compltetly remove it when the view is empty ?

template :

{% if page.page_intro %}
    {# #page-intro #}

                {# #page-intro-inside #}

                    {{ page.page_intro }}

                {# EOF: #page-intro-inside #}

    {# EOF: #page-intro #}
{% endif %}

I'm on Drupal 8.2.0 version.

I would suggest you use the views template for your view (views-view--page-intro.html.twig, and put the wrapping markup in there, rather than in the page template.

{% if rows %}

                    {{ rows }}

  {% endif %}

turn on twig debugging to see the template suggestions in your page markup.  this will be the default.services.yml file in your config directory where you have settings.php

 twig.config:
    debug: true


Views Grouped filter returns empty set I am using Drupal 7 and Views 7.x-3.7.

In a view I have an exposed filter "gender".

If I select the filter type as 'single', it works fine. But I want radio buttons rather than dropdown so I select 'grouped filter' option.

Then the filter renders as I like.

But it always returns an empty result set.

There must be a setting that I am missing. Can you please point me to it?

Thank you.

Well, I could not find a way to make the grouped filter work for me. The solution I found was to use the Better Exposed Filters module. It is quite easy to configure. It worked smoothly for me.


Why node/*/track appears as Referrer to node/*? I have the Statistics core module turned on in my Drupal 7 site.

When I visit the 'Track' tab of a node (node/X/track), the table shows that same page – node/X/track – listed several times as the 'Referrer' to the page itself – node/X. These visits are made by 'Anonymous (not verified)' users.

How can that happen if only the admin (myself) has the permission to view the 'Track' tab??

However, if I click on 'Details' for one of these anonymous visits (/admin/reports/access/*), the "Referrer' information is blank.

Is there some misconfiguration in my site or I did not understand how the Statistics module works?

The issue is with the _statistics_link() function and no referral data; this function relies on drupal_get_path_alias() and when an empty path (i.e. the referrer) is passed to it, it returns the current path which is node/%node/track.

So in other words, those are not anonymous users viewing the tracking page, rather it's anonymous users browsing directly to the page (or not sending referrer data).


Collapsible fields with Views This is a follow-up to this question about automatic node title generation.

I'm using the "Question of the Week" content type. Its fields are "Date," and "Answer;" "Question" is its title.

What I want is a view with a collapsible field for "Answer." The view is used in a block shown in the front page ("This week's questions"), and on a page ("Past questions").

How can I get a view that has a collapsable field?

Automatic Node Title doesn't work the way I want it (can't hide hours, Doesn't update title when content is changed, etc)
View Accordion won't let me hide last of three fields (so I can't show two fields, "Date," and "Question," while hiding answers with VA).
Collapsable Text plugin screams about depreciated functions and breaks other stuff.
I don't see how to combine two fields into one in Views.

I either need to be able to collapse/hide a single field within a view, or combine two fields into one for the view. I'm looking "Computed field" now; I am not sure how to create a field via PHP, though.

I'm trying to make this into a computed field that adds the two fields together, "Date" and  "Question," but all the examples I can find are Drupal 6.

To merge fields you should override a template in your view. ( Views 3 and HTML5 - how to override output for markup? )

I'm new to theming in drupal and wanted to merge fields myself to make collapsible fields few days ago as well, but with no luck. Then I used a css-only workaround  without merging fields or modifying any markup. I used it recently in a comision work:

http://aelasoca.cat/web/

The frontpage is an unformatted view using fields. Each 'new' has the standard separate fields in separate divs (Title, image, date, intro-text, category). I used relative/absolute css positioning and opacity to show/hide text and put it over the image. Then with :hover behaviors and changing opacities and positions again I can make appear or dissapear fields. I've used this as reference:

http://www.sohtanaka.com/web-design/css-on-hover-image-captions/


How to set default values for "modify entity values" form I have a view with nodes and a views bulk operations field. With this vbo field I like to "modify entitity values" of the selected node.

Is it possible:

to automatically check the checkbox for a selected field, so that the field to modify the value is shown by default?
to automatically set a default value in the textfield (which should be shown by default of course)?

You have to hook the form, which is shown after clicking "Modify entity values".

Here is my code to handle this:

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

  global $user;
  $account = user_load($user->uid);

  //to get the form id, you have to print it out first
  dpm($form_id);

  switch ($form_id) {
    case 'views_form_your_view_display_name':

      $nid_page = menu_get_object();

      // the next line activates the checkbox to show the input field
      $form['bundle_item']['show_value']['field_name']['#default_value'] = TRUE;

      // the next line sets the default value for the field shown
      // notice: the 'value' array field depends on the field type and may also
      // be 'target_id' (for entity references) or 'tid' for taxonomy references
      $form['bundle_item']['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = $your_desired_value;
  }
}


How to have a dialog box displayed automatically when a page is reached without having to click the link? Using Dialog API and advice from @leymannx, I added this link to a node (node99):

Last minute information

and it works fine: when clicked, the dialog box shows up!

Now, I'd like to have the dialog box displayed automatically when the node is reached without having to click the link.
@No Sssweat suggested to make jQuery to click the link for you on page load $(".use-ajax").click();

After some errors ($ is not a function), I finally used this:

(function ($) {
  $('.use-ajax').trigger("click");
})(jQuery);

It works but not as expected: the node 27 (the link has href="/node/27") is displayed instead of node99, not in a modal over node99.
What am I missing?

Your JS needs to be formatted like this:

(function ($, Drupal) {
  Drupal.behaviors.myThemeBehavior = {
    attach: function (context, settings) {
      $('.use-ajax', context).once('auto-open').each(function () {
        $(this).click();
      });
    }
  };
})(jQuery, Drupal);

Your library needs to be defined like this:

example:
  js:
    js/example.js: {}
  dependencies:
    - core/jquery #Just ot be save
    - core/drupal.dialog.ajax #Required for dialogs


Can't acces my site and without login and drush clear cache I moved my local site to shared host.

all code has been deployed to the staging server
I changed settings.php
import the database from local to the staging server database

When I try to reach the site I get an HTTP ERROR 500. In phpMyAdmin I TRUNCATE the cache tables:

TRUNCATE cache_config;
TRUNCATE cache_container;
TRUNCATE cache_data;
TRUNCATE cache_default;
TRUNCATE cache_discovery;
TRUNCATE cache_dynamic_page_cache;
TRUNCATE cache_entity;
TRUNCATE cache_menu;
TRUNCATE cache_render;
TRUNCATE cache_toolbar;

If I look in the error logs I see:

AH01071: Got error 'PHP message: PHP Fatal error:  Class 'Drupal\\Core\\Cache\\DatabaseBackend' not found in /home/mysite.nl/public_html/staging/index.php on line 16\n'

What do I have to do?

Make sure your database connection to the DB server is correct. I was using an older local password for DB which caused a similar issue when moving to live hosting.


Adding markup to fields in block plugins I'm attempting to create a block plugin that renders nodes retrieved from a query. I'm able to successfully get the node id's and field values from the query but I'd like to wrap each item in divs and classes but I'm not sure where to start.

public function build() {
    $query = \Drupal::entityQuery('node')
        ->condition('type', 'blog_post')
        ->sort('created', 'DESC')
        ->range(0,3);

    $nids = $query->execute();
    $build = [];

    foreach ($nids as $nid) {
        $node = Node::load($nid);
        $build[] = $node->field_image->view();
    }

    return $build;
}

This is able to render a list of images. But I'd like to be able to have control so I can output something like

Body Text

Body Text 2

Body Text 3

Instead of what Drupal wants to output automatically from the view() function.

You can configure a custom view mode with the two fields image and body and then use a twig file:

node--blog-post--my-view-mode.html.twig

And build the node:

$build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'my_view_mode');

Alternatively your task could be easily solved in Views, but maybe this is only an simplified example and you need to do more things in code.


How can I embed a View inside a content of a node? How can I embed a view inside a content of a node in Drupal 8?

I found something similar, for example in the question about "How do I embed a view inside a node?" or the Viewfield module, but it is all for Drupal 7.

I tried with an Entity reference field pointing to a View but it display only a label and from the Manage Display tab I can choose only from Label and Entity ID. I need something like the "Rendered entity" option that is present on Entity reference fields pointing to other nodes.

Option 1
You can create a View Block. Then the view block will be available in the blocks section. Assign the view block to a region and show it on specific pages if you need to.

Option 2
Create a twig template file for your node and use
Twig Tweak

Twig Tweak module provides a Twig extension with some useful functions
and filters that can improve developer experience.
Ex:    <dd>{{ drupal_view('view_name', 'page_1') }}</dd>

Option 3
If you use Panels or Display Suite, you can embed the view as a field.


How do I give access permission for specific node to anonymous User I have removed "Access Content " Permission from Anonymous user. Now want to display specific node to the anonymous user.

As this is for only 1 or 2 nodes, It's not a good idea to use a contributed module like https://www.drupal.org/project/access_by_entity. I am looking for a solution as a custom code only

I have tried mymodule_node_access also but it's not working.

Give back the "Node access" permission (View published content) to Anonymous user and control the accesss with your custom module

use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;

function MODULENAME_node_access(NodeInterface $node, $op, $account) {
  $allowed = [1,2];
  if ($op == "view" && in_array($node->id(),$allowed)) {
    return AccessResult::allowed();
  }
  return AccessResult::forbidden();
}


Alternative, more secure user registration process wanted I don't like that Drupal 7 exposes at the registration page whether the provided e-mail is known by displaying a "The e-mail address xx@xx.xx is already registered. Have you forgotten your password?" message.

I would prefer if it only lets the user know that the process has been initialized, and depending on the status of the e-mail it either sends out a normal registration e-mail or a password reset.

What would be the best way (the closest to Drupal's philosophy) to implement such a feature?

Is this a module?

Could it be accomplished by reconfiguring the fields of the user account?

If you want to change the way a user can register on a Drupal site, I would rather implement hook_menu_alter() to alter the menu callback called when a user access user/register.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
}

If you are going to allow users to enter an email that is already used from another account, then you should alter also the menu callback associated with user/register, as Drupal allows users to reset a password by entering their username or their email address.

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_register_form');
  }
  if (isset($items['user/password'])) {
    $items['user/password']['page arguments'] = array('mymodule_user_pass');
  }
}

The functions Drupal uses as form builders for those menus are user_register_form(), and user_pass(). You can use them as guideline for the code you implement.

Keep in mind the following points, though:

The unique email is necessary because Drupal allows users to request a new password by entering the email associated with their account. This is also helpful for who simply forgot their username, as the email sent from Drupal contains a link that redirects them to their account, where they will eventually change their password (or just enter their previous password to keep it).
There isn't any security involved, as that doesn't allow a user to know all the emails used in a Drupal site, nor any email matching a partial email address. The users need to enter a complete email, and at that point there is few they can do; even in the case they try resetting a password, Drupal would sent an email to that email address, to which that user needs to have access. If that user can change the password of that email address, or can obtain it, that is not a Drupal security issue, but eventually with how that email address is handled, or who knows the password used for an email address.
If there is a security issue with allowing to use an email address to reset a password, then there would be a security issue even in the case the user is able to enter a username to request a new password, because somebody could find out a username already in use on a Drupal site.
Allowing to have not unique emails can create problems with modules such as the LoginToboggan module that allows users to log in entering their email address when logging in. There are probably other modules that assume there aren't two user accounts using the same email.
Enforce unique email addresses for users is a Drupal issue report related to what you are trying to achieve. If this patch is going to be applied, it will be possible to allow users not to have unique emails by setting the user_mail_unique Drupal variable.


Create a page with database data in a module I am new to drupal and in a process of developing a custom module. My module will do a couple of things:

(ADMIN) User will be able to select a zip file and upload it
(ADMIN) The module will than take that file, extract it to files folder
(ADMIN) Upload the content from a certain file to the database table
(ADMIN/front end) Create a link/page/node on the front page in navigation where the data will be displayed with some additional js required

I got first 3 things going but I am struggeling with the last one.

Any pointers in the right direction will be much appreciated.

if all the uploaded Zips contain similar data you could expose the custom table to Views using hook_views_data and then make a View path with a contextual filter to show the content of a given table.

If you really need a link look at the hook_menu function and make a menu entry that loads a custom page ... which can then load a custom View to show your data on a page.


how to put "add friend" link with flag friend with views Flag Friend Add Friend Link with views. Flag friends shows a link to add friend in my account page but i want to display this link on in a field for a view.

In views you have to go to advanced setting and in relationship you can add your flag.

After that you will be able to add your field.


Using db_insert with a reserved keyword as the column name It appears that db_insert() (Drupal 7) fails when I try to specify a column name which is one of the reserved keywords (in this case, insert).  I tried finding a way to use the back tick syntax which works with a direct SQL command, insert, but it still does not seem
to work.

Googling so far has only confirmed this problem and returned suggestions to change the column name.

Is this the only solution, or is some other way to get db_insert to work (there's a good
reason why the column is called insert in our application)

thanks!

You can try to pass column name in `parenthesis` to db_insert. Just be sure you escaped them if needed, as they have their own meaning in php itself.
If this does not work, well, you can:

fill a bug against core, or post in existing one.
use good old db_query
Or use thesaurus to get rid of reserved words from your app. There is always a "good reason" to use them, of course there is for any common word, but word-oriented languages simply have to reserve some words.


How to have exposed filters not displayed on search results This is hard to explain so I'm attaching an image.

When someone clicks on a filter to search for something, I would like the resulting page to show results but not the filter. Maybe simply a link like "back to search".

Or possibly a small search box, like basic search but not every filter.

This is pretty simple to do with a little coding:

First create a "Display output" template inside your theme folder that will only target the relevant view (check options using "Theme: Information" bottom right under "Advanced" when you are on your view administration page). Copy the contents of "views-view.tpl.php" inside the file and clear the caches.

After that modify the original filter output:

<?php if ($exposed): ?>

    <?php print $exposed; ?>

<?php endif; ?>

to what you need:

<?php if ($exposed): ?>

    <?php if (!isset($_GET['something'])): ?>
    <?php print $exposed; ?>
    <?php else: ?>
    <?php print l(t('Back to search'), $_GET['q']); ?>
    <?php endif; ?>

<?php endif; ?>

You will just have to replace "something" inside that $_GET to a value that is actually used in your filters (check the URL when you have a search performed - it will look like example.com?something=value1&somethingelse=value2). Since views adds all the filter keys to the URL when a search if performed you can pick any of them.


Is it safe to send the unencoded JSON output? The mobile app developers wants an api to get a list of articles from our Drupal site.
It should have these fields in the output:

nid
title
field_teaser_body

The api resonse has to be in JSON format.

The field type of field_teaser_body field is Long text and text processing is Plain text.

I created a custom code to get this working. Here's a simplified version of it.

$query = db_select('node', 'n');

$query
  ->fields('n', array('nid', 'title'))
  ->condition('n.status', 1)
  ->orderBy('n.created', 'DESC')

$result = $query->execute();

$nodes = array();
foreach ($result as $value) {
  $node = node_load($value->nid);

  $data = array(
    'nid' => $node->nid,
    'title' => $node->title,
    'field_teaser_body' => !empty($node->field_teaser_body['und'][0]['value']) ? check_plain($node->field_teaser_body['und'][0]['value']) : '',
  );

  $data = (object) $data;
  array_push($nodes, $data);
}

$content = new stdClass();
$content->nodes = $nodes;

print json_encode($content);

Just for the security purpose, I'm using check_plain() function to sanitize the teaser body text. But, when using this function, it encodes all special characters.

For e.g.,
Bob's height is > than Alice.
converts to
Bob&#039;s height is &gt; than Alice.

The mobile app developers said that they don't want any encoded text in the JSON output.

Is it a safe practice to send the unencoded (unsanitized) text in the JSON output ?

There is no need to encode or escape anything yourself. json_encode() will take care of properly escaping any special purpose characters.


How to add new fields in Drupal I'm just starting out with Drupal, and I have no idea what I'm doing.

I already have the postal code which I can convert to latitude and longitude using the Google Geocoding API.

My problem is how to create the fields that will store the latitude and longitude and how to insert those values in the database so that I can use them in a search view which uses the Search API Solr search module.

All I need is for someone to point me out to what I need to do, maybe some tutorials or resources that will enlighten me so that I know what I'm doing. Please help, thanks!

Assuming you use Drupal 7, it is trivial to add fields to any entity using the build-in Fields module.  (If you see references to "CCK", note that this is not for Drupal 7, but to an older version of this feature.)  With fields, you can enhance Drupal 7 with new data types and entity types from the front end admin interface.

The term "field" refers to a given piece of content within an entity. A field is characterised by having a field name, field type and widget. A widget in this context can be a HTML form element or jQuery widget that is to be used for data entry.

To have latitude and longitude fields in your entity, you should install the Geofield module.  This will give you access to geofields as native datatypes, and also a widget for entering map coordinates if you need that.

To add fields to an entity, start by navigating to Structure → Content types, and click on manage fields for the content type you want to add new fields to.  This can be one of the build-in content types, or a custom content type you've defined.

Clicking on  manage fields brings up a form that shows what fields are already present in the entity. Here you can delete or add new fields to the entity. Add your geofields and click Save.

However, if you want to insert values into those fields programatically (instead of interactively using a widget), you need to create a small custom module that uses the Drupal database API to insert the values into the fields in the database.

Here are links to some fields tutorials that tells you more about how to use fields:

http://heim.ifi.uio.no/gisle/staging2/drupalprimer/drupal/drupal_field.html
https://drupal.org/documentation/modules/field
https://drupal.org/node/707832


Webform Multistep - conditional wizard skipping Is there a way to create a multistep form in Webform and add conditional logic somehow that, based on submission values, certain steps are skipped?
Example, I have a 10 step wizard Webform. Based on certain answers in the first 3 steps, steps 4-6 may be skipped, or in some cases, sent from step 3 to the final step. In other cases, the user would go through every single step (normal).
I tried looking around for examples but didn't come across anything concrete. I did find this, but I am not sure if that is still current?
Webform version: 6.x

Wizard pages support conditional logic which can be used to skip steps as needed.


How can I use regex in a migration query condition? I have data in a table that looks like this:

|-------------------------------------------------------|
|ID|              Data                                  |
|--|----------------------------------------------------|
| 1|{"key":"value",...,"image":"1234567",..."key:value"}|
| 2|{"key":"value",...,"image":"",..."key:value"}       |
| 3|{"key":"value",...,"image":"9876543",..."key:value"}|

In my migration I only want to import items that have an image ID in the Data column.

Previously I was doing this in my migration class query() method:

class myMigration extends SqlBase {

  public function query() {
    return $this->select('data_table', 'd')
      ->distinct()
      ->fields('d', ['ID', 'Data'])
      ->condition('Data', '%' . db_like('"image":') . '%', 'LIKE');
  }

  public function fields() {

    $fields = [
      'ID' => t('ID'),
    ];

    return $fields;
  }

  public function getIds() {
    return [
      'ID' => [
        'type' => 'string',
      ],
    ];
  }

This was also selecting rows where the image value was empty in the Data column.

This query in SQL works for selecting the correct data, but I cannot get it to work with the query() method in my migration:

SELECT ID, Data
FROM data_table
WHERE Data REGEXP '"image":"\d*[^>"]';

I was able to use REGEXP operator in a normal condition() method, although it is not stated in the documentation.

The answer was found on this example.

Solution:

  public function query() {
    return $this->select('data_table', 'd')
      ->distinct()
      ->fields('d', ['ID', 'Data'])
      ->condition('Data', '"image":"\d*[^>"]', 'REGEXP');
  }


Updating entities/posting data via ajax? I've got a handful of entities that need to updated on user interaction, such as:

Tracking user progress through a video, such that a listener checks playhead position every x seconds and posts information to an entity containing data on that user's progress on that video.
A collection of checkboxes that, when clicked, automatically update the state of a corresponding value on a related entity. For the sake of argument, I don't yet know if this will be the actual entity form or a generic form/set of forms.

In the past I attempted #1 by having a hidden, ajax-enabled form whose field values were updated every x seconds and the submit button automatically clicked, but this caused assorted ajax errors for some iOS users that were difficult/impossible to debug. Ideally I think I'd like to bypass having a form there at all. I know how to setup the js to track the data, but I'm not sure how to then pass it along to Drupal from the front-end. I'd assume I want to do something like this (via http://hayageek.com/jquery-ajax-post/), but not sure exactly how to determine the AJAX_POST_URL or how the data should be formatted.

$.ajax({
    url : "AJAX_POST_URL",
    type: "POST",
    data : formData,
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
    },
    error: function (jqXHR, textStatus, errorThrown)
    {

    }
});

For #2, I suppose it might be enough to just have a form that autosubmits via ajax when the checkbox is clicked, but given the misc errors I hit above I'm curious whether or not there might be a better way to handle it.

Happy to update this issue as needed if it's deemed too generic.

The AJAX callback URL will be a route you define in a module. The route will call a controller, which can optionally return an AjaxResponse. First define the route.

example.routing.yml:

example.ajax_callback:
  path: '/example/ajax'
  defaults:
    _controller: '\Drupal\example\Controller\AjaxController::ajaxCallback'
  requirements:
    _permission: 'some permission'

The path to set in your $.ajax() call is set above.

Then create the controller:

example/src/Controller/AjaxController.php:

namespace Drupal\example\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Controller\ControllerBase;

class AjaxController extends ControllerBase {

  public function ajaxCallback($nid, $key, $value) {
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
    $node->set($key, $value);

    return new AjaxResponse(['success' => TRUE]);
  }
}


How to get term by path or alias? I've seen this question posted many places, but no answers - or relevant answer. i.e. how to get term object or ID from path or alias e.g. /cat/subcat or /taxonomy/term/6??

I usually do something like this:

<?php

use Drupal\taxonomy\Entity\Term;

function hook_preprocess_page(&$vars) {
  $route = \Drupal::routeMatch();
  if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = $route->getRawParameter('taxonomy_term');
    $term = Term::load($term_id);
  }
}


Drupal behaviors not attached after Ajax load I'm facing a weird problem on my clean Drupal Installation
I attached a js library to page with this

function fs_gal_preprocess_page(&$variables) {
    $variables['#attached']['library'][] = 'fs_gal/fs_gal';
}

This js file I have:

(function ($, Drupal, drupalSettings) {
  'use strict';
   Drupal.behaviors.GalJs = {
    attach: function (context, settings) {
        alert("Gal");
    }
  };
}) (jQuery, Drupal, drupalSettings);

In my custom theme I created a Ajax call:

$('.button a').on('click', function (e) {
    e.preventDefault()
    $.ajax({
        type: "POST",
        url: "path-to-controller",
        cache: false,
        success: function(htmlText) {
            $('.text-container').html(htmlText);
        }
    });
});

After clicking the button, the text is correctly replaced in the .test-container but the library is not re-attached to the newly changed DOM.
Do someone know a technique to re-attach all behaviors to the content injected after an Ajax call ?

Many thanks for your help

Behaviours are fired after a Drupal AJAX call - a call to jQuery.ajax isn’t the same thing.

Fortunately it’s easy to attach them yourself, just add this in the success callback when you’ve finished manipulating the DOM:

Drupal.attachBehaviors();


Can't get rid(find) of this margin. Please help! I isntalled the Professional theme and Content Glider - all very simple. I got rid of titles and all in the glider, but I can't find the code where the blank line or margin is created. Drupal is new for me. Look and you'll see right away: http://www.aironfix.eu
The slider content-type has no body just title and image. Please help.

Inside professional_theme/style.css line no 727 there is css rule,

.node {
margin: 20px 0;
}

thats create the margin of 20px white margin.