Create a vocabulary with terms that are linked to a content type I need to create a vocabulary with this "twist": the taxonomy terms of the vocabulary are the titles of the article based on a specific content type.

This means that if I create, modify, or delete an article based on the content-type "vocabulary," the relative term in the vocabulary should be added, modified, or deleted.

Imagine I have the content type "Cars." I create different articles, one of which is "Ferrari 456", and another one is "Volkswagen Golf." I want a vocabulary called "cars" with a term for each article (e.g., one for "Ferrari 456", one for "Volkswagen Golf").

When you are creating a new node, you call taxonomy_term_save(), passing as argument the taxonomy term object $term, and using the node title for set $term->name, and the vocabulary ID to set $term->vid.
When you update a node, you first you load the taxonomy term with taxonomy_term_load_multiple(), as in taxonomy_term_load_multiple(array(), array('name' => trim($name), 'vid' => $vid)), change $term->name, and save the taxonomy term with taxonomy_term_save().
When you delete a node, you first load the taxonomy term with taxonomy_term_load_multiple(array(), array('name' => trim($name), 'vid' => $vid)), and then delete it passing $term->tid to taxonomy_term_delete().

The functions I reported needs to use the vocabulary ID; this means that the module you are writing needs to save in a Drupal variable the ID of the vocabulary it created, or to ask to the user the vocabulary name for the vocabulary that needs to be used. In the second case, and in the case the module stores the vocabulary name, code similar to the following one should be used to get the vocabulary ID:

$vocabulary = taxonomy_vocabulary_load_multiple(array(), array('name' => trim($name)));
$vocabulary = reset($vocabulary);
$vid = $vocabulary->vid;

The code needs to be changed for Drupal 8, as the conditions (the second parameter of taxonomy_term_load_multiple(), and taxonomy_vocabulary_load_multiple()) will be removed in Drupal 8.


How to add alphabetized pager using glossary view? I have a member's directory that lists the last name, first name of all the users on the site, as well as other custom field values about the members.  I created a view, added contextual filter for the user's last name (Provide fixed value = "A", character limit =1), and enabled glossary mode. According to my google search results, I should automagically get an alphabetized pager.  This is not happening.  I made sure to save my new view.  Anyone have any other ideas?  What I want is an alphabetized pager that allows the user to choose the first letter of the person's last name, and display the info.

There is a module, Views Glossary, which provide different options to glossary views. According to the docs, it provide following features:

  A special kind of layout to glossary view (which is available by
  default with views) or any view, see in screenshot.
  Providing pager with selectbox and textbox.
  A default view is added for example.
  Making items per pager independent of expose form submit. (A usability
  improvement)


How to change the label of username field on all forms/pages that it occurs? The following snippet changes the label of the username field on the user registration form from 'username' to 'nick-name' (when inserted into the template.php of the theme:

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

    $form['account']['name']['#title'] = t('nick-name');

}

To be consistent I'd like to change the label everywhere that it occurs in the system, such as the user settings form... how do I do that!

Add the following code at the bottom of the settings.php file:

 $conf['locale_custom_strings_en'][''] = array(
   'username'      => 'nick-name',
 );

As alternative, you can use the String Overrides module.

  Provides a quick and easy way to replace any text on the site.

  Features

  Easily replace anything that's passed through t()
  Locale support, allowing you to override strings in any language
  Ability to import/export *.po files, for easy migration from the Locale module
  Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.


REST API 401 Unauthorized I am trying to create a new node with POST through REST in D8. I have enabled the relevant modules (hal, serialization, http basic authentication, Rest web services, rest ui) and added the required permissions to users (create content). I configured the services with restui and added basic_auth for authentication and allowed post on my endpoints. I send X-CSRF-Token together with Content-Type json (or jal+json as configured) and I get either a login popup (basic auth style with user/pass) in restlet client and a 401 Unauthorized with this response.

  { "message": "No authentication credentials provided." }

I even tried using cURL from command line to create my node, with the same result and a GuzzleHttp Exception.

  PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: POST http://www.xxxxxx.com/loyalty/node/?_format=json resulted in a 401 Unauthorized response:
  {"message":"No authentication credentials provided."}
  ' in /home/xxxxx/public_html/loyalty/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

If I allow anonymous to create articles and disable basic_auth everything works fine.

Any clues?

Can you post an exact curl request? Does the user in your request have permission to create content?

if basic auth is enabled then you need to add the user name and password to the request. For example curl request:

curl --include \
  --request POST \
  --user admin:admin \
  --header 'Content-type: application/hal+json' \
  https://ddj9.ply.st/node?_format=hal_json \
  --data-binary '{"_links":{"type":{"href":"http://ddj9.ply.st/rest/type/node/article"}},"title":[{"value":"Example node title"}],"type":[{"target_id":"article"}]}'

Otherwise If the user must be authenticated via cookie then:
 1. you have to send a post to login the user.

curl --header "Content-type: application/json" --request POST --data '{"name":"admin", "pass":"admin"}' http://drupal.d8/user/login?_format=json

The output will look like:

{"current_user":{"uid":"1","roles":["authenticated","administrator"],"name":"admin"},"csrf_token":"wBr9ldleaUhmP4CgVh7PiyyxgNn_ig8GgAan9-Ul3Lg","logout_token":"tEulBvihW1SUkrnbCERWmK2jr1JEN_mRAQIdNNhhIDc"}

Retrive a token from the returned value result
Do what you need to do. :

// get X-CSRF-Token.
$url = 'your_url';
$json = '{
"name": "admin",
"pass": "PASSWORD"
}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
 'Content-Type: application/json')
);
$result = curl_exec($ch);
$user = json_decode($result, TRUE);
$x_csrf_token = $user['csrf_token']
if ($x_csrf_token) {
    // do what you need
 curl_setopt_array($curl, array(
  CURLOPT_URL => "http://www.xxxxxx.com/loyalty/node/?_format=json",
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => $input,
  CURLOPT_HTTPHEADER => array(
   // if you need basic auth then uncomment the nextline
   // "authorization: Basic b64Value",
    "cache-control: no-cache",

    "x-csrf-token: $x_csrf_token"
  ),
));
$response = curl_exec($curl);


How to override core history_cron I want to display the reading history of nodes using Views.
For this reason there is a history module in core, but the history_cron  hook deletes history older than 1 month.
I want to override this hook so that history is not deleted.
What should i do?

With Ultimate Cron you can problably disable it from running using its configuration form.

If you look at its API, it adds a hook_cron_alter that you could implement if you wanted to do it by code.


Form Submit - Populate Title Before Validation I have no idea why I cannot find an answer to this.  I've been able to do this with other fields except the 'title' field.

I have a form which I need to automatically populate the title field.  I don't want the user to populate it, so I'm hiding it by wrapping it in a  that's hidden.

I used hook_form_alter() to add a callback function to the form's #submit array, but those functions are called after the validation.  This would result in an error telling the user to enter a title.

Now I'm trying to use hook_form_alter and adding a validation callback function to the BEGINNING of the array like so:

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    //Hide the title field
    $form['title']['#prefix'] = '
';
    $form['title']['#suffix'] = '
';
    //Callback function to execute before validation
    array_unshift($form['#validate'], '_previous_meetings_set_meeting_title');
}

Here is the callback function that is being called but NOT working:

function _previous_meetings_set_meeting_title(&$form, &$form_state)
{
    $form_state['values']['title'] = 'SOMETHING';
}

What am I doing wrong?  Can I set values in a validation callback?  Is there a right approach to this?

Thanks!

If you use #prefix and #suffix with display:none, it is hidden in display, but submitted and will be validated for required.
Try to use #required = FALSE and #type = 'hidden' and then set title in your submit handler.

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    // Hide the title field
    $form['title']['#required'] = FALSE;
    $form['title']['#type'] = 'hidden';
    // Callback function to execute before validation
    array_unshift($form['#submit'], '_previous_meetings_set_meeting_title');

}

And you could also use Automatic Nodetitles with which you may use token replacement.


Can't get hook_uninstall to trigger In mymodule.install i try to implement a hook_uninstall call, but it never triggers. What am I doing wrong?

function hook_uninstall() {
echo "uninstalling";
...more stuff...
}

First off, the implementation of a hook never has a name starting with hook_; you always replace hook_ with the machine name of the module, followed from an underscore. Similarly, the name of the file containing an implementation of hook_uninstall() must be the machine name of the module followed by .install.
So, if you are literally calling the function hook_uninstall(), and mymodule is not the machine name of your module, Drupal will never consider that function a hook implementation.

Second, if you are using echo to check if the hook is being invoked, you will not get any output. Use watchdog() (Drupal 7) or \Drupal::logger($module)->error($message) (Drupal 8) inside a hook, if you want to verify a hook is invoked.

Third, hook_uninstall() is invoked from Drupal only when a module is uninstalled. There is no other way to be sure Drupal is invoking that hook, if not installing and uninstalling the module implementing it. In Drupal 7, don't get confused from disabling a module, and uninstalling it: Disabling a module doesn't cause Drupal to invoke hook_uninstall().


How do I display different "No results behavior" based on exposed filter results and total results? e.g. A view for job postings has an exposed filter to search by title.

I want to show a "No results behavior" if there aren't any jobs at all "There are no postings at this time. Please check back later."
I also want to show different text if their search returned no results, but there are still postings available. It's just their search didn't match anything. "Sorry, there are no results matching your search criteria."

It appears that I can only do one or the other.

You could easily adapt the views-view.tpl.php to your specific view, eg, views-view--VIEWNAME.tpl.php and change up the portion dealing with no results...

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php print $empty; ?>

<?php endif; ?>

...with something along the lines of...

<?php if ($rows): ?>

    <?php print $rows; ?>

<?php elseif ($empty): ?>

    <?php if (count($_GET)>1): ?>
      Sorry, there are no results matching your search criteria.  Perhaps with other filters you may find some.
    <?php else: ?>
      There are no postings at this time. Please check back later.
    <?php endif; ?>

<?php endif; ?>

...with just some really simple logic based upon parameters Views uses for the exposed filters (eg, if more than ?q=PATH is sent it will have more than just 1 in $_GET).

Now if you want to get fancier than this you may want to investigate one of the Views preprocess hooks and actually change up the $empty variable and not put a lot of logic in the template.

If that's the case you could go further and re-run the View via views_get_view_result() without any filters and if it had any results, actually return your desired Sorry, there are no results matching your search criteria.  (You could do this in this template file but I really try to keep lots of deep logic outside of them)

(Is there any way to dynamically add a CSS class selector to a view with submitted exposed filters? has some more code you might be able to re-use here as well)


Configuration - > Zones admin page missing? I've installed Drupal Commerce 2 and as explained here:
https://drupal-commerce.readthedocs.io/en/latest/v2/building-blocks/address/zones.html
there should be a "Zones" admin page at Configuration -> Zones. But I don't have that page and I only have "default" zone?!?
Only relevant module I found is:
https://www.drupal.org/project/address_zone
but it exists only for Drupal 7?!
What I'm trying actually is to configure Commerce Product Tax, which exists only for D8 and at screenshot from module page:
https://www.drupal.org/project/commerce_product_tax
... they do have zones "France" and "France (Corsica)", so this should be possible somehow I guess.
How to administrate those zones and why I don't have that page under "Configuration" in my back-end?

Use the European Union VAT

As it has France and France (Corsica)


I deleted /devel_themer folder now my website reports an error devel_themer folder of my website that was in public_html had about 500MB size so I deleted this folder. now when I log in to administrative account it reports this error :

Fatal error: Maximum execution time of 30 seconds exceeded in /home/my_web_site/public_html/sites/all/modules/devel_themer/devel_themer.module on line 342

now what shall I do ?

I know its answered in comment, but for others who land here.

Increasing the execution time in php.ini can solve this. An ideal value would be 120.

If it doesn't solve the problem we might need to disable and uninstall the module and fix the problem. Ofcourse you can install it back after things are fixed.

If you can access the admin page:

Disable the module.
Uninstall the module from the uninstall tab in modules page and delete the module folder.
Clear the site cache if required.

If you can't access the admin page:

Delete the module folder.
Run update.php

If you were not logged in at the time of the error you will have problem accessing the update.php, then you will have to either use drush the command drush updatedb or temporarily enable access to update.php by changing settings.php file.

If you had drush, you an also consider disabling the module with it.

Line to change:

$update_free_access = FALSE;


How to update the URL Redirect module v1.4 to its latest version without losing redirects? When I last went to update the URL redirect module from 8.x-1.4 to its latest version I saw this note:

  After 8.x-1.4 version URL Redirect changed as config entity. If you are using before 8.x-1.4 version, it's strongly recommended to not upgrade module as it deletes all existing redirects in your system.

Since I didn't want to lose all my redirects, I just left the module as it was.  Unfortunately, as of yesterday, v8.x-1.4 is no longer supported.

What is the best fix for updating this module?
Is it just a matter of updating to v8.x-2.3 and redoing the redirects (fortunately I do not have a lot of redirects) or is there an easier way of doing it?

You can update module to v8.x-2.3 and run drush updb or update.php. In 8.x-2.3 version all existing redirects get converted to an entity in an update hook.

/**
 * Migrate old redirect data.
 */
function url_redirect_update_8103() {

  $db_connection = \Drupal::database();

  if ($db_connection->schema()->tableExists('url_redirect')) {
    $query = $db_connection->select('url_redirect', 'ur');
    $query->fields('ur');
    $all_data = $query->execute()->fetchAll();

    foreach ($all_data as $key => $data) {
      $values = array(
          'label' => 'Migrated Redirect',
          'id' => 'migrated_' . $key . '_' . time(),
          'path' => $data->path,
          'redirect_path' => $data->redirect_path,
          'roles' => Drupal\Component\Serialization\Json::decode($data->roles),
          'users' => Drupal\Component\Serialization\Json::decode($data->users),
          'status' => $data->status,
          'message' => $data->message,
          'checked_for' => $data->check_for,
      );
      $url_redirect_entity = \Drupal\url_redirect\Entity\UrlRedirect::create($values);
      $url_redirect_entity->save();
    }

    // We can drop 'url_redirect' table once we confirm everything is migrated properly.
    // $db_connection->schema()->dropTable('url_redirect');
  }
}


how to override module's theme function in a custom module? I'm a Drupal8 newbie. I installed a third party module simplelogin, and I attempted to change the {{site_name}} value in page--simplelogin.html.twig but can not find a right way.

I noticed that the variable is defined in simplelogin.module:

function simplelogin_preprocess_simplelogin(&$variables) {
  $path = \Drupal::service('path.current')->getPath();
  $module_path = drupal_get_path('module', 'simplelogin');

  $variables['#attached']['library'][] = 'simplelogin/simplelogin-library';

  // Able to use custom variables
  $variables['path'] = $path;
  $variables['base_path'] = base_path();
  $variables['logo'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));
  $variables['background_class'] = simple_login_settings('active');
  $variables['background_opacity'] = simple_login_settings('opacity');
  $variables['wrapper_width'] = simple_login_settings('width');
  $variables['site_name'] = \Drupal::config('system.site')->get('name');
  $variables['site_register'] = \Drupal::config('user.settings')->get('register');
}

I guess the second "simplelogin" presented in the hook function is a form element in the theme (I'm not quite clear although), as I found $form['simplelogin'] appears in the buildForm function of form controller.

  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {

    $form_state->disableCache();

    $simplelogin_config = $this->config('simplelogin.settings');

    $imageid = $simplelogin_config->get('background_image');
    if ($imageid) {
      $file = \Drupal\file\Entity\File::load($imageid[0]);  // File Load
      $fileUrl = $file->getFileUri();

      // check if image is valid.
      $image = \Drupal::service('image.factory')->get($fileUrl);
      if ($image->isValid()) {
        $image_render = array(
          '#theme' => 'image_style',
          '#width' => $image->getWidth(),
          '#height' => $image->getHeight(),
          '#style_name' => 'medium',
          '#uri' => $fileUrl,
        );
      }
    }
    //$renderer = \Drupal::service('renderer');
    //$renderer->addCacheableDependency($image_render, $file);

    $form['simplelogin'] = array(
      '#type'            => 'details',
      '#title'           => $this->t('Configuration'),
      '#open'            => TRUE,

      'background_active' => array(

WHAT I HAVE DONE:
                                                                                1. created a custom module named "mylogin", this is the info.yml:

name: myLogin
description: my login module
type: module

version: '8.x-1.0'
package: 8.x
core: '8.x'
project: 'mylogin'

dependencies:
  - simplelogin

2. override hook_preprocess_page in mylogin.module:

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\Core\Controller\ControllerBase;
use Drupal\simplelogin\Controller;

function mylogin_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'user.login') {
    $variables['site_name']= 'test';
  }
}

But it cannot work, and I believe the preprocess is not triggered. Is there a simple way to override the needed variable while keep the others in the module's preprocess function? Any help will be very appreciated.

You can create a new module use hook_theme_registry_alter like module simplelogin
like this:

/**
 * Implements hook_theme_registry_alter
 *
 * {@inheritdoc}
 */
function YOUR_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['page__simplelogin'][preprocess functions] = [
    0 => 'simplelogin_preprocess_simplelogin',
    1 => 'YOUR_MODULE_preprocess_function'
  ];
}


Call AJAX function in the beginning not just after change I've built a form that uses ajax to determine the number of text fields there should be based on a select field. It successfully adds the text fields based off the select field when it is changed, but it does not add the fields in the beginning before there is a change.

    $this->configuration['test'] = '3';
    $form['columnNum'] = [
        '#title'   => t('Number of Columns'),
        '#type'    => 'select',
        '#options' => [
            1         => '1',
            2         => '2',
            3         => '3',
            4         => '4',
        ],
        '#default_value' => $this->configuration['test'],
        '#empty_option'  => t('-select-'),
        '#ajax'          => [
            'callback'      => [$this, 'columnCallback'],
        ],
    ];

public function columnCallback(array&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $number   = $form_state->getValue(['settings', 'columnNum']);

    for ($i = 0; $i < $number; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $content[] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,
    ];

    $response->addCommand(new ReplaceCommand('#column_wrapper', $content));
    return $response;
}

I've attempted lines this

$this->columnCallback();

But that failed.
Is there a way to get an ajax callback in the beginning before the field as well? Or is there a better way to do this entirely?

Rather than calling the AJAX function at the beginning I simply built the form as it should be in buildForm. Like so

    for ($i = 0; $i < $this->configuration['test']; $i += 1) {
        $columns[$i] = [
            '#type'  => 'textfield',
            '#title' => t('Column Title'),
            '#value' => $this->configuration['test'],
        ];
    }
    $form['column_wrapper'] = [
        '#type'        => 'container',
        '#attributes'  => ['id'  => 'column_wrapper'],
        'columnTitles' => $columns,

    ];


How to update the uid of a node in node revision table? Is there any way to update the node's uid in the node revision table using rules.

I have used the node:author but it only update the uid in the node table and does not update in the node revision table.

Is there any other way?

Along with what Japo said, the latest revision will mirror the update, it does not get applied retroactively, not sure why you would want that specifically. Unless this is a case where anonymous users create content or are assigned content and you want them to have edit access to all past revisions?

Either way, nothing will solve this for you short of a custom module that does a db query to force the UID value on the table.


How do I load the $form_state for a form loaded with drupal_get_form? Or is drupal_get_form not the right way to go about loading node forms where I want to also get the $form_state?

The reason I am asking is I would like to be able to place multiple node forms on the same page and have them editable (not in a popup) on the same form as the parent form. I have already tried inline_entity_form and that would almost work, however that module does not load the entire form inline with the rest of the parent node form. Rather it places the referenced nodes in a table that you then interact with and save separately.

When you do drupal_get_form() the form and state is cached, otherwise other Drupal form functions wouldn't be able to get it back later.

The only way I know to get it is like this:

// Get the form.
$form = drupal_get_form('my_form_id');
// Get the default form state.
$form_state = form_state_defaults();
// Get the form and form state from the cache for the form you just got.
form_get_cache($form['#build_id'], $form_state);

Since form_get_cache() returns the form also you could do the last line like this:

$form = form_get_cache($form['#build_id'], $form_state);

and it would overwrite your form with the cached one and update your form state (since $form_state is passed by reference) but in the case of calling it right after drupal_get_form() there is no need to do that.


DB - local to a friend I want to duplicate my locally hosted website to a friend's environment. He says he needs a copy of website's database. I'm a bit of a an Drupal rookie so I have no clue of how do this. We are using a code base so all the other files are in there.

I check settings.php and it says I have mysql as the driver
I have drush and run the command

drush mysql-dump > random.sql

This didn't work. I got an error saying; the drush command mysql-dump could not be found.

Please follow me through the steps of how do this. I really need to sent share this website with my friend as quickly as possible.

Thank you

To export your database, for example to migrate it, simplest option is to use Backup and Migrate module.

  Back up and restore your Drupal MySQL database and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

Emphasis mine.

To do it with Drush, use:

drush sql-dump > my-sql-dump-file-name.sql

You need to have mysqldump installed in your system. In Linux, it usually can be found in mysql, mysql-client or similarly named package, and installing it should take care about path configuration etc. In Windows, it's probably already in path like C:\Program Files\MySQL\MySQL Server 5.6\bin (depending on where you have installed it). Make sure to add that path to system's PATH variable (My Computer -> Properties or similar, depending on Windows version; look for "system variables", "environment variables", names like that).


error while editing views When I'm editing a view and I click on one of the fields to edit them I get a javascript error

Error: TypeError: c.curCSS is not a function
Source File: http://drupal.mydomainname.ca/misc/ui/jquery.ui.position.min.js?v=1.8.7
Line: 13

When I click Apply or Cancel on the configuration dialog I get taken to a page with nothing but a JSON string on it at this url

http://drupal.mydomainname.ca/admin/structure/views/ajax/config-item/home_page_slider/block/field/field_image

Anyone else have this error or know what might cause it?

jQuery Update has some problems with v1.8.7 currently (related to the version of jQuery UI included); downgrading to v1.7 should fix the problem.

See these issues on D.o for more information:

Suddenly stopped working - TypeError: c.curCSS is not a function
Update jQuery UI to 1.8.24

The reason your View isn't working is simply that the Javascript error is preventing the relevant events from being attached to the elements. So when you click a link, instead of Views loading the JSON via AJAX and processing it, you're instead forwarded to the JSON page itself.


Anyone manage to work entity metadata wrapper with profile2 entity? Code:

$profile = profile2_load_by_user($account);
$profile = $profile['main'];

$wrapper = entity_metadata_wrapper('profile2_type', $profile);

$wrapper->field_first_name->set(devel_generate_word(mt_rand(6, 12)));

I'm sure that $profile is Profile object. Beside 'profile2_type' I tried 'profile', 'profile2' but got error too.

Current error:

  Unknown data property field_first_name.

The problem is that profile2_load_by_user() returns an array of all user profiles by default, whereas entity_metadata_wrapper() needs a single entity object.

Try loading a single profile:

$profile = profile2_load_by_user($account, 'profile_name');
$wrapper = entity_metadata_wrapper('profile2', $profile);
$wrapper->field_first_name->set(devel_generate_word(mt_rand(6, 12)));


Global search/replace on special characters accidentally taken in on an import ( â€™ ) I have imported (through CSV using Feed Import) and large amount of information. I have a large amount character encoding issues such as

  Grimsbyâ€™s teaching focus is on...

Where â€™ is in place of the apostrophe. Is there any way to search/replace myself out of this? Could I use an input filter?

You can try the scanner module to do these sitewide text search and replace operations but it may be a little tricky because of the characters you're replacing (they look like MS smart quotes?)

Better solution might be to rollback your import, rexport your CSV with a UTF-8 character set and try your import again.


How to display more than 10 items in link widget autocomplete? This is a question about the Link module. Since with the Link module you can enter external or internal links both, we strongly rely on it.

Unfortunately the number of items to be displayed from its autocomplete field is limited to 10. We have a lot of nodes with nearly identical titles and so it comes that the node we are searching for doesn't get displayed in the autocomplete field when there are more than 10 matching titles.

The limit is hardcoded in core/lib/Drupal/Core/Entity/EntityAutocompleteMatcher.php. Is there an elegant way to increase this little number from within a custom module? Do I have to extend class EntityAutocompleteMatcher? Where would I have to place my extension and how to ensure it gets executed from within the link widget?

If you can live with overriding all of the autocomplete limits, you can override a core service in Drupal 8;

The service you need to override is here in core.services.yml:

  entity.autocomplete_matcher:
    class: Drupal\Core\Entity\EntityAutocompleteMatcher
    arguments: ['@plugin.manager.entity_reference_selection']

In your custom module, add a class that implements ServiceModifierInterface

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class MyModuleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {

    for ($id = 'entity.autocomplete_matcher'; $container->hasAlias($id); $id = (string) $container->getAlias($id));
    $definition = $container->getDefinition($id);
    $definition->setClass('Drupal\mymodule\Entity\EntityAutocompleteMatcherCustom');
    $container->setDefinition($id, $definition);
  }

}

Then copy EntityAutocompleteMatcher.php into your module at /src/Entity/EntityAutocompleteMatcherCustom.php

Then update the hardcoded 10 to a 50, or whatever limit you'd like:

namespace Drupal\mymodule\Entity;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
use Drupal\Core\Entity\EntityAutocompleteMatcher;

/**
 * Matcher class to get autocompletion results for entity reference.
 */
class EntityAutocompleteMatcherCustom extends EntityAutocompleteMatcher {

  /*
   * {@inheritdoc]
   */
  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {

    $matches = array();

    $options = array(
      'target_type' => $target_type,
      'handler' => $selection_handler,
      'handler_settings' => $selection_settings,
    );
    $handler = $this->selectionManager->getInstance($options);

    if (isset($string)) {
      // Get an array of matching entities.
      $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
      // Changing limit from 10 to 50.
      $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 50);

      // Loop through the entities and convert them into autocomplete output.
      foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {
          $key = "$label ($entity_id)";
          // Strip things like starting/trailing white spaces, line breaks and
          // tags.
          $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
          // Names containing commas or quotes must be wrapped in quotes.
          $key = Tags::encode($key);
          $matches[] = array('value' => $key, 'label' => $label);
        }
      }
    }

    return $matches;
  }

}

Obviously override core services has some risks, but it's cool that you can do this.

What are the risks of overriding a core service?

1) You may lose the benefits of updates when you update core.  If there is a critical security fix in the service, and your altered copy has the security hole, you will not benefit from the community updating that code.

2) Other modules you install may have dependencies to the original service with its original feature set.  So let's say there is some code in another module that will break if the number of autocomplete entries are greater than or less than 10, you won't know about it, until it affects you.

3) It makes your codebase harder to maintain.  You have to remember that you are not using core Drupal, but an extended version.  Other developers who join your project after you left may have a hard time figuring out why a service is behaving in a non-standard way.

Is this hacking core?

Depends on how you look at it.  It's not going into the core module and changing code.  It's not even creating a patch and applying it and tracking it with a package manager such as composer.  It's more of a one-off customization that alters a sites core behavior, similiar to an ALTER hook. It's more self-contained that a core hack, because it's within your own custom module on your site.  So core updates to the original service will not be affected, the same way as if you patched or hacked the original service code.

But it does have some of the same risks as hacking core, as mentioned above.

In the original question, the issue was the node titles are not unique enough.  The better solution, other than changing the limit globally on drop downs would be solve the uniqueness problem.

What I would suggest is to add a new field field_display_title and use that on the page, and if you need it another field field_teaser_title for display on list pages where you need a shorter title.  Then the actual title that gets pulled into entity reference select dropdown can be useful to your editors and be unique, such as "My Article (page 1)" if the issue is each page has the same title.  Then you don't have to override a core service.

When you come across a problem with Drupal, try to find the solution that requires the least amount of custom code.  This makes your site more stable, easier to maintain and saves you time.


Where is the result of the query is stored? I have created a view page and a block. I need to get the query from the view block. The query preview can be seen.

The following code was found to fetch the query from view

function status_update_views_pre_execute(&$view) {
 if ($view->name == 'project_initiative') {
   $query = (string)$view->build_info['query'];
   echo $query;
 }
}

Where is the result of the query stored? How can I fetch it?

OR

the query is as follows

SELECT node.title AS node_title, node.nid AS nid, node.created AS node_created, 'node' AS field_data_body_node_entity_type, 'node' AS field_data_field_project_name_node_entity_type FROM  {node} node LEFT JOIN {field_data_field_project_name} field_data_field_project_name ON node.nid = field_data_field_project_name.entity_id AND (field_data_field_project_name.entity_type = 'node' AND field_data_field_project_name.deleted = '0') WHERE (( (field_data_field_project_name.field_project_name_target_id = '55' ) )AND(( (node.status = '1') AND (node.type IN  ('status_update')) ))) ORDER BY node_created DESC LIMIT 10 OFFSET 0

How can I execute it to get the result in drupal custom module?

You could get the nids like this:

// load and display view
$view = views_get_view('view_name');
$view->set_display('block_1');
$view->execute();
$nids = [];
// get all nids from the result
foreach ($view->result as $result) {
   $nids[] = $result->nid;
}
// render view
print $view->render();


What to do if you don't want to load JS files on mobile devices What to do if you don't want to load JS files on mobile devices? Let's say, the navigation of a website uses javascript (dropdown for example), and that Javascript is loaded within the .info file

Example of the .info file of an Omega Subtheme

scripts[0] = 'js/navigation.js'
scripts[1] = 'js/hoverintent.js'
scripts[2] = 'js/jquery.fancybox.pack.js'

Let's say, I don't want to load scripts[0] on mobile. What would be the easiest solution for this?

The easiest (probably only realistic) way would be to create a second, javascript-less theme, and use the ThemeKey module to show that theme to mobile users based on user agent string. It's not exactly a foolproof method but then device-sniffing never is.

The other option would be to write some javascript which responds to the Omega media query change event, and hooks/unhooks all other javascript events on the page based on the current device size. I can imagine that being very difficult to manage though.

The proper solution would be to design the theme in a mobile-first manner, building up the javascript functionality as you go and managing how it reacts to different breakpoints at an earlier stage.

Removing all javascript for mobile devices means your users will be experiencing a site like they would have 10 years ago, with no UI richness. These days people expect more than that, especially since their devices can easily handle javascript/


How to filter the view2 fields and show by clicking on view1 node I have view1 and view2,  when I click on the node link of view1 say

ex:  id [mc] it should get view2 and display corresponding  information like strain , projects etc based on the id[mc].

So far to get the view2 while clicking on view1 node, I have performed following,

In view1 I have rewritten the tittle[node] output to link and specified the path of view2.
Given contextual filter to filter and to get the related field value of view2.

Problem is when I click on particular node of view1 it gives the view2 but it is not filtering based on the  node we have clicked.

So can you please tell me how to filter and get the field values of view2.

Step 1)

I added a Entity Reference field called 111 to my Content Type

Step 2)

In view1 in RELATIONSHIPS click Add

in search type ref
select Entity Reference: Referenced Entity

Step 3)

In FIELDS click add, select File Usage: Entity ID.

Under Relationship, select your entity reference
check mark exclude from display.
Thousand Marker, select none

Step 4)

Move your title field below the File Usage: Entity ID field.

Step 5)

Click on your Title field.

Uncheck link this title to the original piece of content
Under Rewrite results, checkmark output this field as a link
link path: /view2/[id]

Save view1

Open View 2

Step 1)

Add a Contextual Filter of File Usage: Entity ID (Do the same as picture below)

Step 2)

In RELATIONSHIPS click Add

in search type ref
select Entity Reference: Referenced Entity

Step 3)

Change the page path settings to /view2/%

DONE :)


Site structure - nodes and blocks I'm new to drupal and I try to understand the structure of it.

Let's assume I want to do the following regardless of the existence of a module doing this concrete job – just to understand the structure and best practices.

What I need is a calendar module. This calendar should be displayed on an own page. So I think I must provide a special calendar content type, don't I?
Then I want to display the next 3 events as a list on a front page. Here, I guess, I must provide a special block, which is only visible on the defined front page?

Is this the standard way of doing it?

Your question is hard to answer because there are calendar modules.  How those modules are implemented could vary infinitely.

Drupal being so flexible you could pose this question to 10 people and get 10 different answers and they would all work!

If I were to have this problem I would look for a calendar module that would expose the data it may contain to Views so I could do anything I wanted with the data.  That would mean that the calendar module would use the Entity framework to save it's data which is the best way of doing things in Drupal.

The display of the calendar more than likely would not be a content type, it could be content you could insert into a content type using tokens or something like that or it may supply you a page and path to the calendar view or multiple paths.  Again I go back to you could pose this question to 10 people and get 10 answers.

This may not answer your question.  But your question is rather hard to answer without specifics in regards to modules.


insert fields for the links in my content type Good morning,
I have to put in my content type of fields to collect a variable number of links (www.example.com). how can I do to allow insertion of variable numbers of fields and how do I then access them with php?

If I understood the your question, your solution is here.
It gives you the chance to insert link such as field. Once you enabled the module, you can add the field through "manage field" tab of your content type.
If you want to access via php, you can use the Devel module.


Access referenced entity in Rules using hook_entity_property_info I am using the Reply module for comment threads on a custom entity (we'll call it myentity). I'd like to create a rule that triggers when certain properties of myentity are met. However, the Reply module has very minimal entity_property_info, and so there's no way for rules to reference myentity in a condition.

The Reply module creates a Reply entity, that references an entity via entity_id column and an entity_type column. So, I created a property_info_alter hook as follows:

function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['entity_id'] = array(
    'label' => t("Entity id"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'entity',
    'getter callback' => 'entity_property_verbatim_get',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}

When I create a condition in rules of "Entity is of Type", I expect to find my new property as an option like reply:entity-id but it doesn't. It only appears in the condition "Data Comparison".

I feel like I'm missing something very simple, but really can't put my finger on it. How do I get this property to appear as a referenced entity that I can then evaluate in Rules?

This works as-is. I actually had a typo in my code that took me a long time to catch. I'm leaving this up if anyone else has the same situation. The final code looked like this (cleaner):

function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['myentity'] = array(
    'label' => t("My Entity"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'myentity',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}


How can I create the views pager on top and bottom of the view? I need two view pagers / pagination to sandwich the view content or view results.

Is it possible to duplicate view pagers/pagination ?

What i've done is just printed out the pagers in the template twice; however, that requires me to hardcode the pager.

I need a little more flexibility because I'm required to build / place the top pager in different spots on different pages.

Could this be accomplished with views display (suite) somehow and a code field? I've attempted one and had no luck.

I think you are on the right track by editing the views template files. Do you know you can have a different template for each view, or each views display? When you are editing your view there is a link called "theme information" that will help you figure out how to name the templates.

Now, If you mean you need to have the pager in different places on page 1 of this display vs page 2 of the same display, you will have to dig inside the view object to figure out which page you're on in order to figure that out.

I also found this tutorial while Googling the answer:
http://www.adesignforlife.net/articles/drupal-tutorials/solution-how-print-pager-drupal-views-block


How to install a taxonomy system that represents records in another high-volume, non-content-node table? Here's the scenario:

A writer about celebrity gossip posts a node (article) on a Drupal website.
I have a module that scans the article and automatically creates taxonomy fields based on celebrity names posted in the article.
These taxonomy "terms" are based on a firstname/lastname list of celebrities that will be high-volume and perpetually growing.
This list of celebrities will have various fields to render in-depth profiles of the celebrities
Content nodes can have multiple celebrities attached to it.
Celebrity nodes can be attached to multiple content nodes.

Here are my assumptions:

The ever-increasing volume of celebrities and their atypical field requirements make it necessary to create a table specifically for celebrities.
The taxonomy-to-node relationships are really nothing more than node_id and celebrity_id in a relationship table.
While writers can tag an article automatically with my module, they will likely need to sometimes add additional celebrities due to misspellings or scanning errors, thus the celebrity firstname and lastname will need to be a part of the tagging process.
Due to name changes, misspellings, etc, we don't want to use celebrity firstnames and lastnames as unique IDs

So, here are my questions:

Is there a module already built that renders this functionality?
Is there a module already built that helps create a taxonomy that can represent a relationship between a node and entities in a custom table, not just a taxonomy table?
Is this functionality already present in a Drupal distribution somewhere?
Should I create a custom module to solve this problem (i.e. I won't be re-inventing the wheel)?

You don't specify Drupal 6 or 7. If you can, use 7. Then you can do the following

Have your content (gossip posts), as
nodes.
Put your celebrity names as taxonomy terms
Apply whatever fields you like directly to the taxonomy term. No need for attached nodes or custom content.

There are several auto tagging modules out there, Open Calais is free and would suit your needs. You could even just use the 'Person' results from it to only tag celebrities.

Drupal 6, did have some issues with very large taxonomies (over 100,000 terms and 2,000,000 individual tags). D7 has sorted most of these, so it is unlikely that you will have to go down the custom code route.

If you do you will not only need to sidestep the node system, but also the taxonomy system and mysql, so it is not as easy as creating a custom table.


Allowing users to add taxonomy terms but requiring administrators to verify them I would like to allow users to add new taxonomy terms, but I would like this to be verified by an administrator. The way I envision this working would have a user filling out a form which would send a notification to the specified admin; then, if the admin accepted the users request some hook or method would be triggered that would create the new taxonomy term.

Is there way to do this kind of thing with Drupal?

Brainstorming here...now that taxonomy is part of the entity system, it should be possible to do something like this:

Install http://drupal.org/project/workflow
Add a field to your taxonomy called "Published" or "Approved" that is a boolean checkbox
Setup a workflow that is triggered on taxonomy term creation with Approved as a field only accessible to admins
Write a hook into taxonomy terms that removes a term unless it is approved (this is the tricky part - there are a lot of ways to get to taxonomy terms, so this might make this approach moot).

Alternative:
Since you mentioned a user filling out a form - you could pretty easily have a content type called "Taxonomy Term" or something with the needed Taxonomy fields, then use workflow/Rules to send the submission to an admin, upon approval use Rules or custom code to create a new taxonomy term.


How to integrate captcha to multi page webform I have integrated a multi step form through the drupal webform modules. Need to add a captcha at the end of the form. I have used captcha module for it..but while enabling the module and assigning the form id from the backend it is adding the captcha to each step forms.

Can any one please help me how to add the captcha at the end of the form.

One thing that may work is altering the form using HOOK_form_alter() and than modifying the form to show the captcha only on the last step something as below:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Get the form id through dpm() or print_r().
  switch ($form_id) {
    // Add the form id as here.
    case 'webform_client_form_form-id':
      // Get the value of step number and the total number of steps in form.
      $page_num = $form['details']['page_num']['#value'];
      $page_count = $form['details']['page_count']['#value'];

      // Check if its not the last step and catcha present in form.
      if (($page_num != $page_count) && (!empty($form['captcha']))) {
        // Remove the captacha from the form.
        unset($form['captcha']);
      }
    break;
  }
}


How to ensure successful update after system failure during updb causing the site to remain in maintenance mode? Running drush updb to upgrade drupal core or other modules, puts the site in maintenance mode. I recently faced an issue (probably an edge case) where the site was stuck in maintenance mode after running updb in a pipeline of a containerized infrastructure. Here is the sequence of events:

Run drush updb -y
Container terminated (system failure or unknown reason)
Re-attempt at drush updb
drupal returns "no updates were required" (this tells me that the step 1 may have completed the update in the background?"
Site remains in maintenance mode.
I manually bring the site back online.

After all this it looked like the update was successful.
How do I ensure the integrity of the system when this happens without restoring a backup and running the updates again? When running subsequent drush updb that says "no updates required" does this guarantee the previous updates were successful.

When running subsequent drush updb that says "no updates required" does this guarantee the previous updates were successful.

When Drush queues up batch items to be processed for drush updb, it adds these operations:

Any module schema updates
Any entity definition updates (off by default, not supported after 8.7)
A cache clear & post hook update functions (on by default)
Toggle off maintenance mode (if it not already enabled)

If the only updates were module schema updates then you might be in a scenario where things are ok; there are no post-update hooks needed (e.g. some batch data ops following a schema change) and only the last step of toggling off maintenance mode didn't complete.

How do I ensure the integrity of the system when this happens without restoring a backup and running the updates again?

You'd have to audit the list of updated modules to double-check each schema update was applied and there were no post-update hooks missed in the update.
Depending on your update scenario this may or may not be easy, hence the best practice is doing a DB rollback and re-applying updates to ensure data integrity when uncertain.


Cant figure out what's wrong with my image style generation code The code outputs and does exactly what I intend it to do, but it throws the following notices:

  Warning: Illegal string offset 'effects' in
  image_style_create_derivative() (line 928 of
  /var/www/html/modules/image/image.module). Warning: Invalid argument
  supplied for foreach() in image_style_create_derivative() (line 928 of
  /var/www/html/modules/image/image.module).

The code I am using is so:

(Builds the actual image style from base uri if the file doesn't currently exist)

/**
 * Check for and generate image derivatives if none exist.
 *
 * @param string $style
 *   Image style to check.
 * @param string $uri
 *   URI of the base image.
 *
 * @return false|string
 *   Returns uri for the image that should now exist.
 */
function _srv_image_derivitives($style, $uri) {

  // So I have something to return.
  $final_uri = image_style_path($style, $uri);

  // Gets the absolute file name to the file to check for.
  $filename = drupal_realpath($final_uri);

  // If it's not there, make it there.
  if (!file_exists($filename)) {
    $style_load = image_style_load($style);

    if (count($style_load)) {
      image_style_create_derivative(
        $style,
        $uri,
        image_style_path(
          $style,
          $uri
        )
      );
    }
  }
  return $final_uri;
}

(Builds an array of images that will be converted to a json array for an rest post)

/**
 * Build derivatives array from base image uri.
 *
 * @param string $image_uri
 *   The base image to construct.
 *
 * @return array
 *   Array of image derivatives.
 */
function _srv_build_derivative_array($image_uri) {
  // Set up the image styles to be used.
  $image_styles = array(
    'carousel',
    'rotator',
    'leadlandscape',
    'focus',
    'linkthumbnail',
    'topstorythumbnail',
    'topnavthumbnail',
    'lateststoriesthumbnail',
    'headline',
    'subcategorylead',
    'opinionlead',
    'entertainmentlead',
    'entertainmentlatestthumbnail',
    'gallerylandscape',
    'gallerythumbnail',
    'reporterstory',
    'galleryportrait',
  );
  $images_array = array();

  foreach ($image_styles as $key_one => $style) {
    $image_style_uri = _srv_image_derivitives($style, $image_uri);

    // EFS path instead of public:// uri.
    $images_array[$style] = str_replace("public://", "/data/sites_default_files/", $image_style_uri);
  }
  return $images_array;
}

The first argument should be array in the image_style_create_derivative() function, so the error is in the caller code.

  Parameters

  $style: An image style array.

  $source: Path of the source file.

  $destination: Path or URI of the destination file.

https://api.drupal.org/api/drupal/modules%21image%21image.module/function/image_style_create_derivative/7.x

There is a incorrect sample in the comments at api.drupal.org.


How to Add Taxonomy description or other field value in a textarea with WYSIWYG? I want a content editor to be able to create re-usable content, then have access to that content through the WYSIWYG editor when editing the node body or other text field. The idea is that the information gets used in multiple locations through the site, and they want to both cut down on copy/paste errors and only have to edit this information in one place.

The best analogy I can give here is, think of a hotel chain that has several properties each with it's own page, and they wish to have a table on each page that has the room description, occupancy, and price, and based on those parameters, they want to set the price for all properties listed on different pages at the same time.

I'm thinking taxonomy is the simplest way to create re-usable content, so the question is, is there a module that allows simple selection/insertion of a taxonomy description directly into say a table that's being edited with the WYSIWYG editor?

There will be hundreds of items I believe, so the interface should ideally be as simple as possible (like a taxonomy reference autocomplete widget).

You have to add any wysiwyg module and enable it. Follow the installation instruction on your site (/admin/config/content/wysiwyg). You can use a wysiwyg editor like ckeditor. Then on same configuration page, for Filtered HTML select your editor.

Once an editor is set for a particular text format. You can follow these steps:

Add a Vocabulary to your taxonomy like Hotel Properties (hotel_properties). Edit it and add new fields to it like price.
Now in your content type, you can use Hotel Properties (hotel_properties) as term reference and widget type: autocomplete.
Now you can alter the node tpl or use panels (Node Template) to display information from taxonomy.

Note: To get the wysiwyg editor, use filtered text editor.


Menu Block change depth I'm converting an HTML template to a Drupal theme. The HTML template has a 2-level submenu:
ul (main) > ul (first-level) > ul (second level).

In my block--system--main-menu.tpl.php I do only have: <?php print $content ?>

When I check the structure of the Main menu in Drupal (list links) levels are correct.

Now on my frontpage Drupal shows only the first level of the menu. How can I make Drupal show more levels? I'd love to do this without a (non-core) module.

Thanks in advance!

I think you just have the primary navigation enabled in your theme. To see the second level, enable the secondary navigation in your theme settings. But this will split you're navigation. A probably better solution is, to use the "Menu Block" module. This allows you to build different kind of navigations in a block.


How to create a "Make this Sticky" link or tab I need faster way to promote a node I'm looking at.

I usually go for:

"Open node view page"  (IE: https://example.com/node/123)
"Click Edit"  (IE: https://example.com/node/123/edit)
Scroll down
Click "PROMOTION OPTIONS"
Tick the Sticky option
Scroll (again)
Save node

Is there a faster way than that? The idea is to have a "Make this sticky" tab or link.

Sure, you can simply add any field to your node type and use that. Let it be a simple checkbox for example. Hide that field from node display. It should just be displayed on the form display. Put it in a prominent position. Finally, via hook_form_alter add another submit handler that then checks the input of that checkbox and sets the node's sticky value accordingly.

I just released Toggle Sticky Toggler. Which adds a "Make Sticky / Unmake Sticky" tab next to the default "Edit" tab.


How to use modified (calculated) value of a field in Drupal entity query condition? I have a link field for a content type. I am implementing a validation where users cannot enter a domain name in the field if it has been used already. For that purpose, I need a direct way to derive domain from the field value (full url) for comparison with the domain name of the url entered.
$result = \Drupal::entityQuery('node')
->condition('type', 'ABC')
->condition('field_1', parse_url($url_entered)['host']->execute();

The problem is field_1 is a full url where as I only want validation over the domain name.
Is it possible to do using Entity Query? If not, any suggestions?

To do so you can use LIKE operator in your query like the following:
$host = parse_url($url_entered)['host'];
$result = \Drupal::entityQuery('node')
  ->condition('type', 'ABC')
  ->condition('field_link', "%" . $host . "%", 'LIKE')->execute();

UPDATE
if you want to check that the exact host exist, you should select all values of your field and then compare with the entered host.
$host = parse_url($url_entered)['host'];
// Select all uris of field link.
$database = \Drupal::database();
$query = $database->select('node__field_link', 'nfl')
  ->condition('nfl.bundle', 'page')
  ->fields('nfl', ['field_link_uri']);
$result = $query->execute()->fetchAll(PDO::FETCH_COLUMN, 0);
$hosts = [];
// extract all hosts.
foreach ($result as $item){
  $hosts[] = parse_url($item)['host'];
}
// Check if the host already exist.
if (in_array($host, $hosts)){
  // Do what you want ici !
}


\Drupal::database() ->insert - Error: Call to undefined method Using ->condition()? I am trying to insert a new row based on conditions. The ->condition() in $database->update() works fine, in $database->insert() they do not.

$database = \Drupal::database();

// Query our DB.
$queryDB = $database
  ->select('table_name', 'value3')
  ->fields('value3')
  ->condition('value1', $value1, "=")
  ->condition('value2', $value2, "=")
  ->execute()->fetchAll();

if (isset($queryDB[0])) {
  // Check if table row exists and overwrite.
  if ($queryDB[0]->value1 == $value1 && $queryDB[0]->value2 == $value2) {
    $database
      ->update('table_name')
      ->fields([
        'value3' => $value3,
      ])
      ->condition('value1', $value1, '=')
      ->condition('value2', $value2, '=')
      ->execute();
  }
}
// Create table row.
else {
  $database
    ->insert('table_name')
    ->fields([
      'value1' => $value1,
      'value2' => $value2,
      'value3' => $value3,
    ])
    // Without these conditions, I get a duplicate entry integrity restraint as value1 and/or value2 may already exist.
    // With them I get Error: Call to undefined method Drupal\Core\Database\Driver\mysql\Insert::condition().
    ->condition('value1', $value1, '!=')
    ->condition('value2', $value2, '!=')
    ->execute();
}

Very similar questions:
1. EntityQuery condition "is not equal to..."
2. How do I add a condition to a query?

But I am having no luck. Is it different with an insert?

What I want is that if value1 AND value2 don't both match, create an entirely new table row with all three values.

As described in Insert Queries, the object returned from \Drupal::database()->insert() doesn't have an condition() method. If the purpose of the code is creating a new database row if it doesn't exist, or update it if it already exists,
the code should use the object returned from \Drupal::database()->merge(). See Merge Queries.

For example, the following code will create a new row if none of the existing rows contains the value $name for the name database column; otherwise, it will update the existing matching row. ($connection is the object returned from \Drupal::database() or a Connection object obtained via dependency injection.)

$connection->merge('example')
  ->key(['name' => $name])
  ->fields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->execute();

It is also possible to use a set of values when the row is created, and another set when the row is updated.

$connection->merge('example')
  ->insertFields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->updateFields([
    'field1' => $alternate1,
  ])
  ->key(['name' => $name])
  ->execute();

What that documentation page doesn't show is how to use multiple keys, as the following code does, using Merge::keys() instead of Merge::key().

$connection->merge('example')
  ->insertFields([
      'field1' => $value1,
      'field2' => $value2,
  ])
  ->updateFields([
    'field1' => $alternate1,
  ])
  ->keys(['name' => $name, 'nickname' => $nickname])
  ->execute();

The only limitation is that the values passed to keys() are all used to match a single database row. In other words, the last snippet I shown doesn't look for a row containing $name in the name database column or a row containing $nickname in the nickname column.

In cases more complex, where the Merge class doesn't help, you need to first check what the database table contains and take the necessary action basing on the table content (which involves writing more PHP code to check the database content).


Automatically add a new node to a drop-down menu When a user creates a node of a certain type, I want that node to be added to a drop-down menu at the top of the screen: i.e., so that when the user mouseovers the parent item in that menu, a list of all the nodes of that type is displayed. What's the best way to achieve this?

I achieved this effect by using https://drupal.org/project/nice_menus, and building a view that contains all of the nodes I want displayed in the drop-down. Then https://drupal.org/project/menu_views can display that view as menu items within the menu that Nice Menus has built.


Render template file for view if no result? I need to render a view's template file even if there are no results for the view.  Is this possible out of the box?  If not, any idea on how to hack it?

Even though there is no results to display, views will call the appropriate theme functions and template files to render other information.

For example, If you go to views-view.tpl.php file you could see that views is rendering lot of information conditionally. For example if you have some exposed filters and there is no result for the execution, still view will call this template file to render the exposed form

If you specified No Results Behavior or exposed some filters you can check this.

Below is the sample code on how the views is rendering conditionally,

<?php if ($rows): ?>

      <?php print $rows; ?>

  <?php elseif ($empty): ?>

      <?php print $empty; ?>

  <?php endif; ?>

If there's nothing to render it will skip all the conditions and will not render anything.

If you want to override the way views is rendering the output, then you can create your own template for your view and place it in your theme directory. Template name should be something like this - views-view--.tpl.php


I can't log in after removing the user login left bar I removed the user login block on the left of my default drupal instalation (7.21) and now i can't login.

When i try: mysite/drupal/?q=admin
It gives me "access denid".

I Don't feel like reinstalling my drupal just for this there has to be a simple way to fix this?

Simply go to http://yoursite/user or if you don't have clean url enabled http://yoursite/?q=user


Making Twitter 1.1 API requests on site with OAuth and Twitter modules I've setup a Twitter app and placed the appropriate Consumer Key and Consumer Secret strings in the settings of admin/config/services/twitter/settings.

I'm able to make twitter 1 api requests just fine, such as drupal_http_request('https://api.twitter.com/1/statuses/oembed.json?id=507185938620219395'); Using api.twitter.com/1.1, however, causes a 215 Bad Authentication error.

Obviously I'm not passing the necessary data to authenticate myself, but how do I go about doing that? All my google searching comes up with Drupal situations utilizing modules which do everything from the UI, or code examples which use php libraries such as Twitteroauth.

I should add that I am running a localserver test site and have setup my app's callback as both http://127.0.0.1:8000/twitter/oauth or the domain name I have setup in etc/hosts on my linux server. Neither seem to help, but both are accepted just fine in the twitter settings.

Lastly, I have been getting the following Notice on admin/config/services/twitter:

  Notice: Trying to get property of non-object in user_access() (line
  808 of /var/www/twitcher/modules/user/user.module). (as well as lines
  820, 821, 827 and 830)

I only began seeing this 2 days ago, and have been unable to figure out exactly what is causing this (I've seen other threads about the same notice, usually relating to Administrative Views, but nothing on the Twitter module).

What is preventing authorization here?

Perhaps not a Drupal solution, but I thought I would update to say that I have settled on using Twitter-API-PHP found here https://github.com/J7mbo/twitter-api-php


how to theme select box drupal for css framework I am making a theme using semantic ui framework in drupal. I want to apply semantic ui select box effect to my theme but i was not able to do this. Here is the link for semantic ui select box http://semantic-ui.com/collections/form.html.

They used this for markup select box.

      <input type="hidden" name="gender">

Gender

Male

Female

But the standard markup for select box is:

<select id="edit-date-month" name="date[month]" class="form-select">
<option value="1" selected="selected">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
</select>

How can i apply semantic ui select effect to my drupal theme.
Any help would be appreciated.

You need to override theme_select(), which you can do in your theme's template.php file:

function MYTHEME_select($vars) {
  // Your code to produce the markup you need. You can find all pertinent data in $vars.
  // The original form element is at $vars['element'], so the options array is at
  // $vars['element']['#options'].
}


Passing variables in drupal_mail I have a custom module with form and I want to pass the values from form_state into email.
This is my code.

//The form page callback
function mymodule_page($form, &$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter name here'),
    );
    $form['surname'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter surname here'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_submit'),
    );

    return $form;
}

function mymodule_submit($form, &$form_state) {
    $name = $form_state['values']['name'];
    drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), array($name));
    dpm($form_state);
}

/**
 * Implements hook_mail().
 */
function custom_test_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_mail':

        $message['subject'] = t('Hello');
        $message['body'][] = t('This is a body text');

        break;
    }
}

I'm receiving the email with the subject and body, but without the value from $form['name'].

How can I pass the values from form fields?

You're already passing $name as a parameter, but you're not actually inserting it into the body so it won't show up in the email.

It's best to use a keyed array so you can easily refer to parameters by name, something like this:

$params = array('name' => $name);
drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), $params);

...

$message['body'][] = t('This is a body text');
$message['body'][] = t('Name: @name', array('@name' => $params['name']));


How to replace a string in a URL field when outputting it in a template file I created a new field for URL. What would the best way to replace certain strings in the URL when outputting the field into the field--field_url.tpl.php file be?

For example, in http://example.com/master/m/ I need to remove the "http://" part, and replace master with slave.

It is a single field; there will be no foreach() loops.

==== edit after using preprocess ===
i got a undefined index: field_url

with the devel i get this

field_url
   und
     0
       value

i put in the preprocess

$link = $variables['field_url'][LANGUAGE_NONE][0]['value'];

$link = str_replace('http://', "", $link);

$link = str_replace('master', 'slave', $link);

$variables['link'] = $link;

is this right?

====== entire hook =======

function lessxless_preprocess_field(&$variables)
{
    $link = $variables['field_url'][LANGUAGE_NONE][0]['value']; // grab value

    $link = str_replace('https://', "", $link); // trim http://

    $link = str_replace('master', 'slave', $link);

    $variables['link'] = $link;
}

sites/all/themes/lessxless/template.php

You probably want a preprocess function in your template.php for this. In your case, hook_preprocess_field() will be easiest to work with - for an example of how this is implemented, check out the API documentation for template_preprocess_field().

Remember, $variables is passed into preprocess hooks by reference. From within your hook_preprocess_field(), instead of modifying the field data directly (in case you need it elsewhere), you could do something like this after checking that you're operating on the right field:

/* devel's dpr() is handy for seeing where in the $variables array it lives if you
   don't have a debugger handy. If you see 'und', that's the value for the LANGUAGE_NONE
   constant. It's considered best practice to use the constant instead. */
$slave_link = $variables['field_url'][LANGUAGE_NONE][0]['value'];
$slave_link = str_replace("http://", '', $slave_link); // Trim http://
$slave_link = str_replace("master", "slave", $slave_link); // s/master/slave
$variables['slave_link'] = $slave_link;  /* You can now access this variable from your
                                            field--field_url.tpl.php as $slave_link */

You may also need to clear your cache after making these changes.


Google doesn't see the friendly URLs Google doesn't see my SEO friendly URLs, while the other search engines can.

The browsers (IE, Chrome, FF), the RSS, the TweetFeed everything can see the SEO friendly URLs; in the XML sitemap, the system also see them.
Google Webmaster, and Google Analytics also see the friendly URLs, but if I search on my site via Google ("site:mywebsitedomain"), it can see only the node system URLs (e.g. mysite.com/node/6574).

Before the system update, it was working well. My host supports friendly URLs; I have installed the PathAuto, and the Global Redirect modules; clean URLs are enable.

Why doesn't Google see the SEO friendly URLs I set for the site?

Google will only index one version of the same page. It sounds like you have multiple URL's showing the same page. This is called dublicated content. Google will just choose one of the URL's, in your case, the wrong one.

When you enter mysite.com/node/6574 are you redirected to the friendly url? If not, then the GlobalRedirect module is not active or there is no aliases for the URL.

So make sure it's active and in admin/config/system/globalredirect check Deslash and Non-clean to Clean to further minimize dublicated content.

Also make sure that all internal and external links are pointing to your clean url's.

If the above is done, you just need to wait. Be patience - it can take weeks/months.

And forget about the sitemap. The important part is your internal links.


Rewrite results for user picture to except tokens I have a user role called "Residents" in D7, and created a view the show profile information. I want to add colorbox to the User Picture, but there is only one token available [picture]. How do I add the image path as the destination if I can only use one token (see attachment)?

Please take a look at these two solutions:

https://www.drupal.org/node/2396813#comment-11571515

and

Getting user photo url and profile url using views_json


When doing a page preprocess, how do you know if the page is a form? When doing a preprocess on a page (I need to conditionally change something at the page template level) is there a way to tell if the page is going to render a form? The xdebug output didn't show any variables that would tell me this in an obvious way.

Since I wanted to apply a change to the page.html.twig template based on if it was a form, I looked first for the form suggestions I was given. Since I couldn't find a way to generically apply a template to all forms, I instead created a template that I would then tell all of the forms that I have to use this template. I used a hook_theme_suggestions_HOOK_alter to add my new template and check the existing suggestions to see if the forms I want to use are part of the current suggestions:
function listed_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $forms = [
    'page__user__register',
    'page__admin__people',
  ];
  foreach ($forms as $form) {
    if (in_array($form, $suggestions)) {
      $suggestions[] = 'page__forms';
    }
  }
}

From here, I can add additional forms as they are needed to use this single template. So, this solution doesn't exactly answer my original question, but it solves my original problem.


Omega theme not rendering correctly when css aggregation is disabled I have tried clearing the drupal caches and manually deleting the aggregated files. Also tried clearing the browser cache.

Anyone seen this problem before?

Can be because it needs polyfills which are only loaded with aggregation turned on.

Try with a CSS3 standards compliant browser (ie. latest version of Chrome) which would not need the polyfills at all.

Omega 4 comes with these polyfills:

Selectivizr.js
CSS3 Media Queries JS
Respond.js
CSS3 PIE
HTML5 shiv


Use REPLACE in update query using db_update I need to run an update query that involves using the SQL REPLACE and LEFT functions, and I need to do it with three different queries for multiple tables, so I'd like to do it in a loop. The problem I'm having is getting the REPLACE function to be interpreted properly. The query I need to run is this:

UPDATE field_data_field_myfield
SET field_myfield_value =
REPLACE(field_myfield_value,
'old_value', 'new_value');

From what I've found, I need to use the expression function like so:

foreach ($tables as $table => $field) {
  $num_updated_1 = db_update($table)
    ->expression($field, 'replace(:field, :old, :new)', array(
      ':field' => $field,
      ':old' => 'old_value',
      ':new' =>  'new_value',
    ))
    ->execute();
}

However, when I run it like this, the field just gets updated with the field name as a string for every field.

What do I need to change for this to work?

The replace function doesn't work when the field is a placeholder. This will insert the field string as new value in the database. I've solved this problem removing the placeholder. Check it out:

foreach ($tables as $table => $field) {
  $num_updated_1 = db_update($table)
    ->expression($field, 'replace(' . $field . ', :old, :new)', array(
      ':old' => 'old_value',
      ':new' =>  'new_value',
    ))
    ->execute();
}

This way the code will work perfectly. I hope this may help someone.


How do I join across two different databases? I have two databases, the normal drupal db and another db to another system. I want to join two tables from these two different dbs. I have already set up the second database using information from here, but I don't know how I would go about doing a join across two databases.

Imagine both have a users table, but the second database also has a field called "telephone number". I want to join the two users table on uid, so that telephone number (and other fields) are also included in the result.

Any ideas on how to go about this? Is it even possible?

Yes, with caveats that your DB infrastructure config will dictate if you can do this.

While MySQL allows you to do cross DB table joins, the DB user needs privileges to access both DB's to do it. Additionally, Drupal can only use one DB connection to execute a cross DB table join query.

So if you had a connection defined in your settings.php, called my_connection, and it had access to 2 DBs called DB1 / DB2
You could do things like:

// Assuming 'my_connection' defined in settings.php has access to DB1 & DB2
$db_key = 'my_connection';
$example_join_query = 'SELECT * FROM `DB1`.users AS u1 LEFT JOIN `DB2`.users AS u2 ON u1.uid = u2.uid';
$connection = \Drupal\Core\Database\Database::getConnection('default', $db_key);
$example_results = $connection->query($example_join_query)->fetchAll();

// Same idea, with dynamic queries
$query = \Drupal::database()->select('`DB1`.users', 'u1')->fields('u1');
$query->join('`DB2`.users', 'u2', 'u1.uid = u2.uid');
$query = $query->fields('u1');
$query = $query->fields('u2');
$example_results = $query->execute()->fetchAll();

If your DB infra config is something like 2 isolated hosts, you'll need to take a different approach, like querying data for each DB connection then joining the resulting datasets in PHP code (instead of using a SQL JOIN).


Ignore UUIDs when comparing the difference between configuration exports When building Features, i find it useful to keep a 'backup' of the full configuration and commit it to version control.

If something breaks when i package a feature after i test how it works by doing a full re-install of the profile that brings together the feature modules, i can restore things i missed from the configuration export.

Unfortunately, every site install produces different UUIDs in every configuration file, so i cannot use a diff to determine if there are missing or unexpected changes in the site-install version of the configuration i packaged up.  Drush does not have an export option to strip UUIDs on export.

In the past we used a script to delete all the UUID lines, but not being built into Drush, it was Python or Bash i think, it was awkward to use.  But if i find it i'll post it.

How can i get a clean diff of changes that filters out the noise of the UUID changes?

The use case in question here is for building features; the config/sync directory is never used to import, but it can be used to check if the result of a site install is about what we expect (and to copy wanted files or changes we wanted to keep, and missed, from a saved version).

The meaningless UUID changes in every file, however, make it impossible to find that information in all the noise.

Here is a workaround that presumes you are using Git for version control, exporting configuration and committing it, then running a site install, and re-exporting the configuration (but not yet committing it):

git diff -G '^[^u]*([^u][^i][^d][^:]).*'

will show only files with non-uuid changes. If there's a change to a uuid other than the one for the configuration as a whole (that is, indented under some other part of the configuration), that will be shown.

Super unsure about the regex in this but it's not had a false negative or positive yet.

Here's what i have in my .bashrc to make this easier to use:

# Diff that ignores config files whose only change is the UUID (ignores lines
# starting with 'uuid:' and probably other stuff but it's solid so far.)
alias gdu="git diff -G '^[^u]*([^u][^i][^d][^:]).*'"

Took me forever to come up with this workaround; hope it helps others.


Is it to possible add placeholder text for link fields? Been trying to add placeholder text for my link fields.

Using hook_form_alter to add the attributes. It works fine with text fields

$form['field_first_name']['und'][0]['value']['#attributes']['placeholder'] = t( 'Your First Name' );

But not able to get it work with link fields

$form ['field_twitter_link']['und'][0]['#attributes']['value']['placeholder'] = t( 'Your Twitter profile link' );

You could do something like this in

function formalter(){
$form['#after_build'][] = 'mytheme_after_build';
}
function mytheme_after_build(&$form, &$form_state){
    $form['field_twitter_link']['und'][0]['url']['#attributes']['placeholder']=t('my new');
    return $form;
}

Taken from here https://drupal.org/node/1002560


Drupal site Phonegap application field collection I'm in the process of making a Phonegap application to create nodes of a certain content type. The site I'm writing data to/getting data from utilises Field Collection module, and I've looked at the database structure. It creates additional tables for the contained fields and cross-references them. I was wondering if anyone has come across this situation and how did you manage to solve it.

Note:

I'm using Drupal Services for endpoint,  and my request needs to send all those fields in my fiddle altogether (more than one row).

As for what the fiddle does, I'm creating a table then add more rows to the table.

make sure a field collection exists if you want to go through the Field collection module. Then write the custom php code make sure to use the field collection api. here is an example. another example.

You will have to use AJAX from your phone gap app and send the data you are collecting to your server then use the drupal code to process and insert.
AJAX from phonegap to PHP

Let me know if you need any more help, i'm just really busy as of late or I would provide a more detailed answer. It's difficult not having the code in front of me.


Views with both menu and jump menu taxonomy terms as contextual filters I have a page view with a category taxonomy menu and a city jump menu.  I want them to work together so that if the view shows all content and a user clicks on a category in the menu, the view will be fitered by category and if the user chooses a city in the jump menu, the view will be filtered by city.  If a category has already been chosen and the user selects a city, the view should be filtered by both category and city and vice versa.

I know this should be possible but I don't know where to start or what the best way of doing it might be.  If the best solution requires coding, I am capable of doing it.

I'm editing my response based on your latest comment!

============================================================

One way I think you can do what you're trying to do is incorporate facets into your page with those specific taxonomy terms placed on the page as facets.

You'd need to use the Facet API module and the Faceted Navigation for Search module.  You can see the module page for an example interface - do you see how the screenshot on the module page shows a site where you can narrow the results based on fields/facets on the side?  I'm adding a screenshot from a site of my own that I've set up to use facets, though it's themed very differently.  The other great thing about facets is that they show you how many nodes you have tagged with the fields/terms you want to filter on.

Essentially, what facets do is give you the ability to FILTER/narrow listings based on select-type fields or taxonomy terms.  You can combine these filters, just as you describe.

I've only used the facet api with solr search, not core drupal, so I don't know if I can help you much on the exact setup, but perhaps this can at least guide you into another potential way to achieve your goal (if it's not overkill to learn all about facets and how you may be able to do this through search).

Let us know how it works out or if you figure it out!


Drupal 8 paragraph access in views-view twig file 1.) I have added a paragrah with multiple field in my node form

2.) Now i have created a View and added the paragraph field and selected the Formatter as Rendered Entity

3.) In the preview section i can see all my paragraph data , as my twig debug is on i can see file suggestions where i can override the paragraph file

4.) But i want to access my paragraphs fields inside the views-view--unformatted-{{ view_machine_name }}.html.twig file

5.) I access the normal fields inside my content type using

view.field.{{ machine_name }}.getvalue(view.result[0])

6.) I can access the paragraph complete section by

view.field.{{ paragraph_machine_name }}.original_value

How can i access the fields inside the paragraph in this view file

This is how i solved this ..

--> I added a relationship of the paragraph field and made it as required

--> After that i selected the relationship in the filter criteria section

--> And then i was able to select all the paragraph fields while adding a new field in the view

Hope this helps someone


Maybe think about alternatives? We use BOTCHA module everywhere these days to combat spam submissions. Works much better than any captcha and is far less intrusive for real people. Just a thought.


How can I get the email address of a user who has just registered? I need to add a hash key to users on register, generated from their email address and the current time, I added the field 'field_subscription_key' to user's fields and I hooked into

  custom_newsletter_mail_user_insert(&$edit, $account, $category)

in module's .module file, I have no idea how can I get the email address and time the user was created from these above parameters.

Also, I don't know how to get the user entity, so I would insert the hash key.

The docs on the core entities are really good. Here are the docs on the User class.

You should be able to get the email with:

$email = $account->getEmail();

And the created time with:

$created = $account->getCreatedTime();


How do you give permissions to certain roles to get certain menu items to display in the admin_menu toolbar? Currently I'm using the admin_menu module and have certain roles restricted todo certain things. As an admin I can see the full admin_menu bar in full, but as a restricted user I can only see Add content. Since I'm running the commerce module, I only want certain roles to get the Store dropdown menu. Right now I only see Add content and I'm not sure where to go to enable it to show up in the admin_menu toolbar.

Select People or users in admin bar, the user section on the right side there is permissions tab click it. then scroll down to store section, there u can set the permission for each type of user in your site.

Just to be clear user account ur are using as restricted go to his account page and see what type of user he is? ex admin or user or author.

then tick yes the setting u want for your restricted user in the permission tab.


Ajax calls not properly queued I ran into this issue on my own plugin and then decided to download the Drupal Example Modules to discover the same issue was happening to me in the 'ajax_example' section.

Ajax calls don't seem to queue, and the last message sent to the server overrides the last.

This is the code I am using. (It can also be found in ajax_example.module.)

function ajax_example_autotextfields($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my first name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['ask_last_name'] = array(
    '#type' => 'checkbox',
    '#title' => t('Ask me my last name'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );
  $form['textfields'] = array(
    '#title' => t("Generated text fields for first and last name"),
    '#prefix' => '
',
    '#suffix' => '
',
    '#type' => 'fieldset',
    '#description' => t('This is where we put automatically generated textfields'),
  );

  // Since checkboxes return TRUE or FALSE, we have to check that
  // $form_state has been filled as well as what it contains.
  if (!empty($form_state['values']['ask_first_name']) && $form_state['values']['ask_first_name']) {
    $form['textfields']['first_name'] = array(
      '#type' => 'textfield',
      '#title' => t('First Name'),
    );
  }
  if (!empty($form_state['values']['ask_last_name']) && $form_state['values']['ask_last_name']) {
    $form['textfields']['last_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Last Name'),
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Click Me'),
  );

  return $form;
}

function ajax_example_autotextfields_callback($form, $form_state) {
  return $form['textfields'];
}

This is the screenshot of the page.

After selecting 'first name', 'second name' before 'first name' has time to finish loading.

The 'first name' field is never loaded.

How can I fix this?

Drupal doesn't queue AJAX requests, no. If it's causing a problem, you might want to implement some JS to disable the form while a request takes place.

Alternatively, as it doesn't appear your fields are required, you could use #states instead. They don't require an AJAX call, but (depending on your ultimate requirements of course) will give you the same effect as your current code.


Advertisement view sorted by Nodequeue relationship I have a Advertisement type of View listing Ads by taxonomy but I need to order them by Nodequeue and I don't see it available in the Relationships area.
Is there a hack for this anywhere?

thanks

I figured it out.
You need to tell the view to have a relation from Advertisement to Node (Ad: Aid). Do this by going to Relationships and adding a relationship based upon "Ad: Aid". You'll then see under Fields all of the Node fields such as Title and Body available. Then add another relationship "(Node) Nodequeue: Queue".


Condition plugins: two on the same form? I'm working on porting the CAS module to Drupal 8. On the main configuration form, users can list paths that will activate a feature of the module.

I read about using the new condition API recently, which has a condition for matching request paths, and decided to try and incorporate it into the module settings since it seems perfect for what I'm doing.

On the form submit handler, I have code like:

$this->myPathCondition->submitConfigurationForm($form, $form_state);

And the actual submitConfigurationForm code from the RequestPath class looks like this:

public function submitConfigurationForm(array &$form, array &$form_state) {
  $this->configuration['pages'] = $form_state['values']['pages'];
  parent::submitConfigurationForm($form, $form_state);
}

Couple problems though:

I have two instances of the condition plugin, so they would trip over each other in the form submission
For that reason, I would typically "namespace" each to a section, like: $form_state['values']['forced_login']['paths']

But since the condition plugin looks at a specific array structure for the value, this won't work. This appears to be a limitation of the plugin, but perhaps there's a reason for this, or a method around it?

I understand D8 isn't even in beta yet, but I didn't want to comment on the closed issue where this was implemented: https://www.drupal.org/node/1921544

You are responsible for only passing a sub-key of the form to each plugin configuration method.

Have a look at BlockBase::buildConfigurationForm() and the corresponding validate and submit methods. Note that this itself is already a partial form of BlockForm::form().

For a more flexible approach, have a look at https://drupal.org/project/page_manager, which has an UI that allows to add conditions and configure them in separate forms, but those forms also pass only a part of the form to those methods.

The main advantage of the page_manager approach is that BlockBase only works in a useful way with condition plugins that have a no-op mode, meaning, that you can configure them so they don't do anything (and that is the default configuration) because all condition configurations are saved and all plugins are invoked.

Yes, this is sometimes limiting and inconsistent, but that's how it works and I don't really have an idea to improve it...


show preview and not all page/forms I need to show only the preview and not all page and forms

I made a new window after clicking preview but I see ALL page (a duplicate) including header, footer and form compiled. I need to show the preview only.

function node_form_build_preview($form, &$form_state) {
  $node = node_form_submit_build_node($form, $form_state);
  $form_state['node_preview'] = node_preview($node);
}

can someone help?

If you dont like what Drupal is doing by default for this preview feature, override it in your site theme, there is an example of this in the node_preview Drupal 7 API node_preview() comments.

the comment incorrectly titles the function THEME_Node_preview() it should all be lowercase

  /**
   *Output customized node preview on node edit and add forms.
   *
   * @return
   * This just outputs the Full node ignoring the teaser mode.
   */
  function YOURTHEME_node_preview($variables)
  {
      $node = $variables['node'];
      $elements = node_view($node, 'full');
      $full = drupal_render($elements);
      $output = '
';
      $output .= '
' . t('Preview of your posting') . '
';
      $output .= $full;
      $output .= "
\n";
      return $output;
  }

If that still doesn't look right you could try altering this code further to:

provide an override to node.tpl.php or node--preview.tpl.php using theme suggestions for drupal's theming layer functions.
alter the results of $full above using Regular Expressions to hack off the beginning and end of the HTML page content.


Alter a Views query to use "OR" through the user interface I have a view with a few different displays, each of them with slightly overridden filters, like this one used in a panel.

How do you add this pseudocode via the UI?

AND (node.type='story' OR node.comment_count >=1)

I found an article (Better WHERE's for your Drupal forums with hook_views_query_alter), but I still don't know what to do.

What does the following code do, and what is "advf_filter"?

if ($view->name == 'YOURVIEW') {
  $view->query->add_where('advf_filter',"(node.type='%s' OR node_comment_statistics.comment_count >= %d)",'forum',1);
  $view->query->set_group_operator('AND');
}

In Drupal 7 (Views 3), it's pretty simple, for regular filters at least:

For regular Filters, open the 'rearrange' (or "and/or, rearrange") window by clicking on the arrow next to 'Add'. From here it's simple and self-explanatory - you put your filters into Filter Groups, and can set each filter group to be 'OR' or 'AND'.
For Contextual Filters, it's a little bit stranger and is currently undergoing development work. Keep an eye on this issue: Document that contextual filters are included in the first 'and/or' filter group . As the title of that link suggests, all your contextual filters are treated as being part of whatever your first Filter Group is, so make sure there is at least one, and edit that as above.

There's talk in that issue of changing this to something more flexible (watch above link), but that'll take time.

(note - talking about contextual filters is relevant to this question because someone closed a question about setting 'OR' on contextual filters as a duplicate and pointed it to this one)

-----UPDATE-----------

That issue closed with just a documentation change, here's a couple of relevant ongoing issues to follow...

Using OR in filters breaks contextual filters
Views AND/OR Contextual filters two ways