What are the steps to create a custom widget based on taxonomy_select? I need to create a widget for fields of type "taxonomy_term_reference". The widget "taxonomy_select" is very nearly what I need to build, but needs some modification. I have seen examples that start with a given widget to build a custom version. The function below fails because there is no "taxonomy_select_field_widget_form" defined. Where is the "taxonomy_select" form creation code?

/**
 * Implements hook_field_widget_form().
 */
function taxonomy_multiselect_add_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  $element += taxonomy_select_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

  return $element;
}

The taxonomy_term_reference field type uses the core options_select widget and implements hook_options_list() to provide the values, the taxonomy module doesn't implement any of the widget code itself.

The options_select widget is defined in options_field_widget_info() in the code options.module file (inside the field module folder). The form elements themselves are built up in options_field_widget_form() in the same file. They're pretty well commented so you should be able to get a good idea of how they work.

I'd also recommend the Examples module if you haven't already got it, it has a field type/widget example module with good sample code and comments.


How to not let users remove the entity reference once they added I'm using D7.
I have one content type, let's say Content-A. And, the Content-A has a field whose field type is Entity Reference. Content-A's authors can reference other user with the content through the Entity Reference field.
I want to make authors be unable to remove the entity reference between the content and other users who he already referenced. Does anybody know how to do it? Any advice will be appreciated.

Using Hook_form_FORM_ID_alter on the node form and disabling the field for users that are not the initial author should work.

Code is untested but shows the general idea behind the solution

HOOK_form_FORM_ID_alter($form, &$form_state){
  global $user; // Get the current logged in user information
  if($user->uid != $form_state['node']->uid){ // Is the current user not the original author of this node?
    $form['FIELD_REFERENCE']['und'][0]['#access'] = 0; // Restrict access to this field (You'll have to check where exactly in the tree to place this).
  }
}


Move DB from Apache to IIS I've been working on a Drupal site under a LAMP configuration. My client uses SQL Server, so after I'm done with development I need to move the site over to their configuration. I work on Linux, so I have no way to test the site live (I can remotely connect to my client's server but if I want anything changed I have to go through their IT department, which is painful and slow at best).

I found this module, driver for SQL Server, but from the instructions I gather this is for a fresh Drupal install. Could it work, if I already have some work done, to move my current DB over to their server? If not, is there another option to keep working on MySQL and later migrate to SQL 2008?

I'm not familiar with SQL Server, so any help is appreciated.

Here is the way I would approach your issue:

Prepare two IIS+MSSQL servers, Staging and Production
Do a fresh install on Staging
Use tool like Features, UUID, and data migration module of your choice to move configuration and data from Development to Staging
Tie loose ends on Staging
Copy Staging to Production
Replace my dev with something less unlike production


Media Wysiwyg + CKeditor. Replace inline images with custom images programmatically I am trying to replace individual images in old node body with a default image using media + ckeditor programatically so as to save disk space as there are lot of images in server.

I was successful in replacing image for an image field programmatically. However, I am not able to determine how do I replace those images embedded within a body along with body text while loading a node using node_load.

I intend to replace these images using hook_cron and run replacement operations on older nodes images.

The purpose of this question was to replace old node images with a default image so as to reduce disk space usage, as old nodes are not frequently visited by users.

To achieve this first you load the node using node_load function, and grab the body field:

$node = node_load($nodeID);
$body = isset($node->body[$node->language][0]) ?$node->body[$node->language][0] : array();

$text = isset($body['value']) ?  $body['value'] : $body['safe_value'];

After this you create DOMDocument object:

$doc = new DOMDocument(null, 'UTF-8');

Here, UTF-8 is for languages that are not Latin/Plain English.

$doc->loadHTML(mb_convert_encoding($text, 'HTML-ENTITIES', 'UTF-8'));

Convert your text to HTML entities following UTF-8 format.

$tags = $doc->getElementsByTagName('img');

You grab all your image tag from body.

Next, Loop through those tags:

foreach ($tags as $tag) {
// Get default Image.
$file_temp = file_get_contents($urlToDefaultImage);
// Get Image information.
$info = pathinfo($urlToDefaultImage);
// Replace if it exists.
$file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);
// Get old image fid.
$oldImage = $tag->getAttribute('data-fid');
// Remove the file info from db and server if not used by any.
$status = file_delete(file_load($oldImage)),
$tag->setAttribute('src', file_create_url($file->uri));
$tag->setAttribute('data-fid', $file->fid);
}

After looping through each img tags save the newly generated HTML.

$replacedBody = $doc->saveHTML();

Remove extra html, body and Doctype from the new body using str_replace:

$replacedBody = str_replace('', '', $replacedBody);
$replacedBody = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', '', $replacedBody);
$replacedBody = str_replace('', '', $replacedBody);

Next update the newly formated body to node object:

$node->body[$node->language][0]['value'] = html_entity_decode($replacedBody);
$node->body[$node->language][0]['safe_value'] = html_entity_decode($replacedBody);

Save the node

node_save($node);

Bonus: Updating images in node image field.

Grab the field data.

$field = !empty($node->field_{machine_name}[$node->language]) ?  $node->field_{machine_name}[$node->language] : array();

Here, {machine_name} represents the name for image field you created using Content UI.

// Loop through old images.
foreach($field as $key => $row) {

    // Check if the image
    if($row['type'] == 'image') {

        // Get default Image.
        $file_temp = file_get_contents($urlToDefaultImage);

        // Get Image information.
        $info = pathinfo($urlToDefaultImage);

        // Replace if it exists.
        $file = file_save_data($file_temp, 'public://' . $info['basename'], FILE_EXISTS_REPLACE);

        // Change the current image with default.
        $node->field_{machine_name}[$node->language][$key] = array(
        'fid' => $file->fid,
        'filename' => $file->filename,
        'filemime' => $file->filemime,
        'uid' => $file->uid,
        'uri' => $file->uri,
        'status' => $file->status,
        'display' => 1,
        );
    }
}

Performing these operation will remove default image from your db and server and will save disk space. While we need to use file_delete function when removing files from body, it is not needed when when perform this operation while we replace on an image/media field. file_delete function will safely delete the files from server if that file is not used by any other nodes in website, if second parameter is not set to TRUE. While file_manage_delete does the same thing, though it will not lookup for database and check for its existing usage, it will simply release your disk space from that file, result in 404 not found image on other reused nodes.


Retain content while deleting user using services I need to delete a user account using services module & does it fine.

I can see that content(forum) created/updated by the user gets deleted.

Is it possible to achieve below screenshot option via services module in drupal 7?

Answering my own question,

I have updated the default account setting of when cancelling a user account in the path /admin/config/people/accounts to Delete the account and make its content belong to the Anonymous user

Resolves my query.


Views show / hide filter via dropdown Is there a way to show / hide filters via a dropdown select. What I want to achieve is, that there is a dropdown with all my filters, and only the one I select in dropdown will show up.

I've found the Composite Views Filter  module. But this works only with one group. If I have two Dropdowns to select filters, it won't work.

The mentioned Module Composite Views Filter was extended by it's maintainer. It is still in patch-test-phase, but it is working now to bring in as much filter groups as you like.

  Allows you to create one filter condition that enables a bunch of filter conditions. Sometimes one condition isn't enough for your filter, but you still want the user to be able to change the filter (group).


Auto-complete show everything by default I have an field of "User reference" on a content type -- using an auto-complete control. This works but our user list is in the order of 300+ and it's difficult to remember who all should be selected for various tasks.

Auto-complete by default shows a list only once you have entered a single character -- is it possible to have the list show everyone the minute you click the text field???

Mabye you can use the Chosen module :

Install, enable and configure the Chosen module
change the widget type of your field to "Select list"
in the field settings screen, check "apply chosen on this field" :

Now in your content edit form, you should see something like this, where the entire list appears in the dropdown, but where you can also type an autocomplete request :


How to create another html.tpl.php file for logged in users? I'm using Drupal 7 and I want to create another (different) html.tpl.php file for logged in users only.

So, I need to check if user is logged in and set other html.tpl.php file if a user is logged.

Is this possible and how to do that?

Implement hook_preprocess_html() in your theme (or module, both are equally valid) like so:

function MYTHEME_preprocess_html(&$vars) {
  // Determine if the user is auth'd
  if (user_is_logged_in()) {
    // Add a theme hook suggestion.
    $vars['theme_hook_suggestions'][] = 'html__auth';
  }
}

Then add a html--auth.tpl.php file to your theme, clear the caches, and you should be good to go.


Get field value from referenced entity in twig loop I have a content type with a multiple referenced field and I need to iterate trough each item and display the item information in a table but I don't know and didn't find a way to access the content field information like the value of a specific field.

Example:
I have a content type called Task and in Task I have multiple Entity Reference to Worker content type, Worker has title, name and phone. How can I iterate each worker and display the information in a table?

What I want to do is to override node--task.html.twig to do something like this:

Assuming that we have a field_workers field in task content type.

         Name

         Phone

    {% for worker in content.field_workers %}

        {{worker.field_name.value}}

         {{worker.field_phone.value}}

     {% endfor %}

Is it possible? Thank you!

You want to work with node instead of content.
something like this should work
{% for item in node.field_workers %}
 {{ item.entity.field_name.value }}
{% endfor %}

See Entity API Cheat Sheet and Twig and Entity Field API or how to take control of node.html.twig (my blog post) for more information.


Search API autocomplete group suggestions I am using Search API, Search API autocomplete and Solr search.
I'we made a view with an exposed filer that has a funcionality of search api autocomplete.

For now, autocomplete suggestions are just this boring regular template...

Important to notice is also that I am searching two Content Types (Book and Autor)

I would like to implement grouping in my autocomplete suggestion so that my autocomplete looks like this:

Book:     |     Autor
Book 1       |    Autor n
Book 2       |    Autor n
Book 3       |    Autor n
Book 4       |    Autor n
Book 5       |    Autor n
Show all      Show all

One way to do this requires you to get a bit javaScript-ey

As normal Drupal autocomplete uses "https://jqueryui.com/autocomplete/"

or a wrapper of it see "core/misc/autocomplete.js"

You can do is take 100% control over it.
you can add JS to the view and optionally create a controller to handle better  "label" : "value"

$("#the-id-of-your-search").autocomplete({
      source: function (request, response) {
        var url = '/the-ajax-end-point';
       // or custom Controller returning JasonResponse() :)

       // or custom view with rest Response :)
        $.ajax({
          dataType: "json",
          type : 'Get',
          data: {
            q: request.term
          },
          url: url,
          success: function(data) {
            // play with grouping the data here.
            response( data );
          },
          error: function(data) {
            // do some thing here.
          }
        });
      },
      select: makeSelectAwesome,
      minLength: 3,
    });

   function makeSelectAwesome(e, ui) {
    if (ui && e) {
      if (ui.item) {
        // ui.item.value, ui.item.label
        $("#the-id-of-your-search").val(ui.item.label);
        // in the case of your own controller
        // you can return a whole crap load more stuff
        // Then just label / value
        // Example var data = JSON.parse(ui.item.value);
      }
    }
   }

       // php excerpt for controller ideas
       $request = $this->requestStack->getCurrentRequest();
       $query = $request->get('q');
       /// build a result.
       $value = [
         'type' => $node->getType(),
         'image_url' => $node->field_image ...
         'extra_data_to_make_ui_awesome' => []
       ];

       $results[] = [
         'value' => json_encode($value, TRUE),
         'label' => $node->getTitle(),
       ];
       return new JsonResponse($results, 200);

then i guess you just live the dream.


hide passwords in drupal module settings we have a local community site for drupal and site is run by volunteer admins. my question is, is there any way I can 'hide' passwords in module settings? some modules ask for user password of the service they integrate. it's not safe to have them in plain text in their settings page.

and I don't want to restrict access to those module settings.

this is a common issue with drupal. you can create the permission using hook_permission in your own module. then in your own module use hook_form_alter, find the form of the module andon those password fields use '#access' => user_access('your_permission'). but I have no idea how.

for example, Bot module has a password field. Mailchimp has API Secret field. etc

As you've already noted in the question, you can set '#access' => FALSE to any form element to remove it from display.

The correct place for this is in hook_form_alter():

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'relevant_form_id') {
    $form['some_element']['#access'] = FALSE;
  }
}

If you're asking for a way to do this generically, without having to target each element with a specific form ID/element key, then you're out of luck. Those fields are nothing special, just standard text fields, so there's nothing to distinguish them from any other text field.

Bottom line - you need to decide exactly what fields you want to disable, find the appropriate form IDs/element keys, and use the method above to apply the rule one-by-one.


How can I flag content programmatically? The Flag module is still in development for Drupal 8, but it's working nice. However, I didn't find how to add a flag programmatically; the API documentation seems to speak of the Drupal 7 version.

How do I programmatically add a flag?

Here's how to flag or unflag an entity programmatically, using the Flag service.

$flag_id = 'bookmark';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

// Flag an entity with a specific flag.
$flag_service->flag($flag, $entity);

// Unflag an entity with a specific flag.
$flag_service->unflag($flag, $entity);


How to get the nid for a newly created node? If I've created a node in an install hook, how can I immediately get a reference to the nid property? It doesn't appear to be set on the entity during save.

use Drupal\node\Entity\Node;

function my_frontpage_install() {
    $node = Node::create(array(
        'type' => 'page',
        'title' => t('Welcome'),
        'body' => array(array(
            'value' => 'Hi there'
        )),
    ));

    $node->save();

    $siteConfig = \Drupal::service('config.factory')->getEditable('system.site');
    $pageConfig = $siteConfig->get('page');
    $pageConfig['front'] = 'node/' . $node->getId(); // this returns null
    $siteConfig->set('page', $pageConfig);
    $siteConfig->save();
}

I've tried variations on the theme of getId, getNid(), get('nid'), getOriginalId(), but if I dump out the node object afer saving, the nid property is clearly not set.

The nice thing about Drupal 8, is that it's object oriented, with interfaces, abstract classes etc.

This means that all entities share a lot of methods. To get the id of a node, use the id method

$nid = $node->id();

This also works for users, taxonomy terms and any other entities you create yourself or get from contrib modules modules.

For Drupal 8 development, using an IDE becomes really powerfull as it can help you with what available methods, various instances of classes has.


How to change OG "subscribe to group" link text? I want to customize the link text, don't want to use string overrides module for this small job.

In my template_preprocess_node() function I tried to change the #title element of the render array. But it doesn't change the link. Any ideas?

//change the "subscribe link for tribes
if ($variables['type'] == 'tribe'){
    if (isset($variables['elements']['group_group']['0']['#title'])){
        $variables['elements']['group_group']['0']['#title'] = 'Join this Tribe';
    }
}

You don't necessarily need to use the string overrides module. You can add string overrides directly in your settings.php.
$conf['locale_custom_strings_en'][''] = array(
  'Subscribe to group' => 'Join this Tribe',
);

For more information, see Change default strings (text) without using full translation system.


How to remove (not verified) status in anonymous comments? If I allow users to comment while they are not logged in (anonymous authors), they will have a 'not verified' tag next to their name in the comments of my site. How can I remove it?

You can implement hook_preprocess_username and remove the extra variable:

function THEME_preprocess_username(&$variables) {
  $variables['extra'] = '';
}


PHP Errors with Drupal 8 (Shared Hosting) Using Bitbucket, I've cloned my Drupal 8 site to my Media Temple server. It is shared hosting. Anyways, I'm getting the following php warning and error:

Warning: require(/nfs/c11/h04/mnt/55555/domains/domain.com/html/../vendor/autoload.php): failed to open stream: No such file or directory in /nfs/c11/h04/mnt/55555/domains/domain.com/html/autoload.php on line 17

Fatal error: require(): Failed opening required '/nfs/c11/h04/mnt/55555/domains/domain.com/html/../vendor/autoload.php' (include_path='.:/usr/local/php-7.0.6/share/pear') in /nfs/c11/h04/mnt/55555/domains/domain.com/html/autoload.php on line 17

This is my first time working with Drupal 8. I've done some research and troubleshooting, but I've not been able to solve the issue.

I'm actually having a similar issue with a separate D8 website on Bluehost (CPanel). Has anything run into this before? If so, what steps were taken to resolve the issue?

Following @Clive's advice, I committed the /vendor and /core directories. The php errors shown in my initial question were resolved, but new, similar php errors appeared. After much trial and error, I discovered the Drupal VM was added some sort of configuration to the Drupal install. Whatever that configuration may be, it did not translate to the server environment. I downloaded a fresh Drupal 8 copy and manually installed it. After I pushed up the fresh files, it worked like a charm.


Advanced people filter in Drupal 7 I would like to set up more filtering for the 'People' list in a D7 site -- by username and also by other fields I've attached to my users.

I haven't yet seen any way to hook into or modify the default functionality (please update me if I am mistaken). I did some googling and found reference to the Views Bulk Operation, but even the maintainer said very recently that it's still buggy, so I don't want to use it.

I also found this page which recommends creating a view -- is this the way I should do it?

Yes views is what you want to do. So long as you are using fairly standard modules (like profile) for your fields. You can create filters for any of them.

Create a view with the base type of 'user' and you should be good to go. You will need views and views_ui module enabled.

Just be a little careful that if your view is open to the public you could potentially expose things like email address to the web.


Access field object (not render array) in field templates In most entity templates like node.html.twig or paragraph.html.twig I do get two major variables, the render array variable {{ content }}, but also the entity object variable like {{ node }} or {{ paragraph }}. Usually they are passed down to Twig in template_preprocess_ENTITYTYPE via $variables['element']['#ENTITYTYPE'].

I'm looking an equivalent for this in field templates, e.g. if I can do {{ node.field_whatever.something }} in node.html.twig I also want the get the same thing by using {{ field.something }} in field.html.twig

I guess I need the FieldItemList in template_preprocess_field to achieve this, but I don't know how to get it there.

The field template receives its values from the parent entities' view display build array. This build array doesn't contain separate keys for the original fields on their components build arrays.

But a field preprocess function receives enough information to extract them: The 'element' item contains an '#object' key that holds the original entity, and a '#field_name' key that holds the name of the field. (Which is also available in the template as field_name thanks to template_preprocess_field().)

If you'd like to access the original field, you could do something like:

$element = $variables['element'];
$field_item_list = $element['#object']->get($element['#field_name']);

Which should return an instance of a class that implements FieldItemListInterface (FieldItemList, EntityReferenceFieldItemList, ...).


What is the best way to get array in some drupal data By example, I get this array :

content_device
    ...
    fields_examples
        und
            0
                sub_field_one
                sub_field_two
                ...
            1
                sub_field_one
                sub_field_two
                ...
            2
                ...
            ...

And currently, if I want modify a subfield, I do this :

content_device['fields_exemples']['und'][1][sub_field_two] = ...

Is there a best way (drupal or php way) for get a sub data more cleany ?
I mean (sorry for my poor english writing x) ), I find the "['und'][1]" heavy. If I get the fields_examples array, can I get the sub-arrays '0', '1', '2' ... without use the 'und' in this example ?

My example isn't very explicit, but I know I have some array in my website who contain sub-sub-sub-...-array in sub-sub-...-array in ... in array.
And often, an array contain one only sub-array. So if I want get the sub-sub-array, I find the 'only' sub-array very useless, and he complicates the code.

I hope I was clear x)

I'd recommend you to look at entity_metadata_wrapper() function which comes with the Entity API module.

  The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier. Wrappers make it easier to get and set the values of fields and properties as well as to programmatically retrieve additional information about these elements and iterate over lists of values in a consistent manner.

For example, using entity_metadata_wrapper() you can modify a field (or a "subfield" with your terms, I think you mean a field in a field collection) in a following way:

// You should first wrap your node with entity_metadata_wrapper().
$node_wrapper = entity_metadata_wrapper('node', $node);

// To get the value of a field
$field_value = $node_wrapper->field_example->value();

// To get the value of a field in a field collection etc.
$field_value = $node_wrapper->field_example->sub_field_one->value();

// To set/modify the value of a field in a field collection etc.
$node_wrapper->field_example->sub_field_one->set('Some new value');

// To save the entity after modifying some values
$node_wrapper->save();


How auto load items on page Taxonomy page will have sidebar which will have taxonomy menu items and grid layout with image and brief details.

For example, taxonomy items have brand by certain names, price range, etc. User click on brand name, the grid layout will auto load the brand products without have going to /products/brand_name. On page, it will be /products, and then every brand name will show different products automatically loading on same page.

Is there such a way to do this? Or there is a module which can do that?

Example I found is
http://www.cynosure.com/products/

Click on any from menu on left column, you will see the products reloaded by menu click.

This can be achieved using exposed filters feature of the Views module. Here is an article explaining this process in detail.

http://www.bryanbraun.com/2013/08/06/drupal-tutorials-exposed-filters-with-views

You would also need the Better Exposed Filters(BEF) module for displaying the filters as links.


How to add a menu tab to a user profile? I want to create an additional tab (dashboard) on my site's user profile page. There is a Homebox module installed and a dashboard was created for users. The dashboard is accessible by user/dashboard. How can I do this? I tried doing it as below:

New module created with name add_menu_tab
In add_menu_tab.module file I wrote as below
I want to create an additional tab (dashboard) on my site's user profile page. There is a homebox module installed and a dashboard was created for users. The dashboard is accessible by user/dashboard. How can I do this? I tried doing it as below:
New module created with name add_menu_tab
In add_menu_tab.module file I wrote as below:

code :

function add_menu_tab_menu() {
     $items['user/dashboard'] = array(
    'title' => 'Dashboard',
      'type' => MENU_LOCAL_TASK,
      'weight' => 7
    );
    return $items;
  }

The menu is still not visible in user profile
What should I do?

You should implement hook_menu_alter() instead of hook_menu.

function add_menu_tab_menu_alter(&$items) {
  $items['user/dashboard']['type'] = MENU_LOCAL_TASK;
}

Then you should clear the cache, at least the menu cache, as Mołot suggested.

There is also another approach using hook_menu_local_tasks_alter(). But the first method is better since it is called only once, after the hook_menu and saved in the database, while the latter is being called each time the local tasks are rendered.


Views filter: show nodes last year Following this tutorial https://www.drupal.org/node/2481343 i made a filter where the user can select the nodes, createad from a date till now.

Is there an easy way to make a button with 'show nodes from last year'? I was thinking about a button, switchting between 'last year' and 'all' (in fact a reset of the filter).

Not very beautiful and dynamic but as a quick fix you could for instance add a Global: Text area to your views. (See screenshot also)

Show nodes from last year
Show all nodes

To make this more dynamic you could enable the php module (not recommended! https://drupal.stackexchange.com/a/2512/8606) and use date("Y",strtotime("-1 year")); to retrieve the previous year dynamically


Where are .po translations supposed to go? I have .po file with translation and I have it in modulename/translation/xy.po

When I installed profile in XY language the file was not loaded.
I did a little digging and found that \FileTranslation::getTranslationFilesPattern looks for drupal-8.xy.po pattern so I renamed the file, reinstalled my profile but the language still was not picked up. The interface translation was downloaded just fine though. If I manually import the file it works. So it looks to me like the directory for translations has changed maybe?

I have checked the installer and it looks like Drupal only looks into the site's files/translations directory. So how are modules supposed to ship with translations?

So it looks like the translations ARE being imported just fine(entries are present in the locales_source table), but for some reason not everything is displayed translated.

Ok, so I came to a conclusion that my translation file is not imported at all. The reason for incomplete translation is because it comes from downloaded Drupal localization and not my file. I am looking at installer and there is nothing that would suggest po files discovery mechanism in any way, only the drupal core(or any po file) in the files/translations directory(which is where the drupal translation is downloaded into).

Be sure the directory sites/default is writable, so that during installation the translation files can be copied to the translations directory at sites/default/files/translations


Add multiple items to cart Is there a module or a detailed how-to out there that can help with creating a form to add multiple products to the cart at once for Drupal 7, Ubercart 3.0?

One way of doing it is by using the Views Bulk Operations module. There is a patch which has recently been committed and offers the "Add to cart" action over here: http://drupal.org/node/1553700

Once your view is built (fields only) you can add a Content VBO field and choose the Add to cart action from there. In theory, redirection to the cart can be done by including the ?destination=cart parameter when calling the View which should be honored once the form is submitted. However, at the moment this appears to only add one item and redirecting rather than all items that have been selected.


How to customize the node info being shared on Facebook and other sites? This article describes how to use hook_process_html() to customize the node info when you embed your page into Facebook or other sites.

Is this still the best way to go or are there other ways?

I would use the Meta Tags module. It makes the Facebook Open Graph information easy to update and configurable per node, if necessary.


Encapsulate fields in div I need to encapsulate in Drupal 7 some fields intro a div and other fields in another div. How can I do that?

Thanks.

You can change the way the html is genereated for a field by overwriting the apropriate theme method.

Tho find the method you can use the theme developer module. After enabling the module you can click on the appropriate field to see the theme methods which are important for you.

Have a lookg at the themeing giude if this is all new for you.


Disable caching for a front page path processor I’m working on a project where users can create a book (core functionality). In a simple text field they can connect a domain to this book. This way the book is only accessible via this domain.
For example I have Book A with path node\1 and with domain a.book.com. I also have Book B with path node\2 and connected to domain b.book.com.
What I want now is if a visitor goes to a.book.com the frontpage is node/1. And if they go to b.book.com the frontpage should be node/2? I created a custom module for this book_frontpage.
For this I used large parts of the PathProcessorFront.php from core.
The code of my book_front.services.yml is:
services:
  book_frontpage.path_processor_front:
    class: Drupal\book_frontpage\PathProcessor\FrontPagePathProcessor
    tags:
      - { name: path_processor_inbound, priority: 300 }

The code of my FrontPagePathProcessor.php is:
<?php

namespace Drupal\book_frontpage\PathProcessor;

use Drupal\Core\Database\Database;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Path processor to replace 'node' with 'content' in URLs.
 */
class FrontPagePathProcessor implements InboundPathProcessorInterface{
  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request)
  {
    if ($path === '/') {
      //current domain
      $currentDomain = $_SERVER['SERVER_NAME'];

      //get nid of reader where domain is set
      $nid = Database::getConnection()->select('node__field_domain', 'd')
        ->fields('d', ['entity_id'])
        ->condition('field_domain_value', $currentDomain, '=')
        ->execute()
        ->fetchField();

      //get path
      $path = \Drupal::service('path_alias.manager')->getAliasByPath('/node/'. $nid);

      if (empty($path)) {
        // We have to return a valid path but / won't be routable and config
        // might be broken so stop execution.
        throw new NotFoundHttpException();
      }
      $components = parse_url($path);

      // Remove query string and fragment.
      $path = $components['path'];

      // Merge query parameters from front page configuration value
      // with URL query, so that actual URL takes precedence.
      if (!empty($components['query'])) {
        parse_str($components['query'], $parameters);
        array_replace($parameters, $request->query->all());
        $request->query->replace($parameters);
      }
    }

    return $path;
  }
}

Now when going to a.book.com I see node/1 but when I go to b.book.com I also see node/1.  When I clear cache and first go to b.book.com I get node/2 but when going to a.book.com I also get node/2. So this looks like a cache problem.
How can I disable caching of this front page path?

As discussed here, Hide path on frontpage redirect, you need to make caching of route collections domain-specific. Other than the discussed overriding of the core service, since Drupal 8.8 you can use the service method addExtraCacheKeyPart().
Add this code in a request event subscriber:
/src/EventSubscriber/RouteCacheDomainSubscriber.php
<?php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class RouteCacheDomainSubscriber implements EventSubscriberInterface {

  public function onKernelRequest(GetResponseEvent $event) {
    $routeProvider = \Drupal::service('router.route_provider');
    $domain = \Drupal::request()->getHost();
    $routeProvider->addExtraCacheKeyPart('domain', $domain);
  }

  /**
   * {@inheritDoc}
   */
  public static function getSubscribedEvents() {
    // run before RouterListener (priority 32)
    $events[KernelEvents::REQUEST][] = ['onKernelRequest', 33];
    return $events;
  }

}

mymodule.services.yml
services:
  mymodule.route_cache_domain_subscriber:
    class: Drupal\mymodule\EventSubscriber\RouteCacheDomainSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

Also, you need to invalidate the cache tag route_match when book nodes are saved. See Is there a way to partially rebuild the router or invalidate a route cache?


How to identify where a particular block come from? I have to modify a block that appears on the home page of the website, that I did not make myself. The block appears in admin/build/block with the title "Block Title (nodeblock)", so I assume that this has  been created by the nodeblock module, but I can't find where I can edit this content.

Can someone help me to find the right administration menu to view and modify this nodeblock content ?

The easiest way for Drupal 6 would probably be to use the Contextual links module.

  Hover over nodes, blocks, and views blocks to expose styled
  edit/configure/delete tabs.

It's a backport of the same functionality that is in D7 core, but for Drupal 6.

Just hover over the block on the front page, and hit edit to edit that particular block.


Drupal view shows multiple results to a single row I am using a view with table format.

I need to show results in a given format. I am unable to find..

Can anybody tell me how to achieve in views..

Thanks

Option 1: Set the format of the view to "grid" and columns to 2.
Option 2: Set the format of the view to "HTML list" and then with css set the width of the li and float it left.


Search through page titles? Is the Search module supposed to search through the node/page titles, or just the node content?

Because, for me it is only searching through the content, and not the page titles.

Note: I am using Drupal 7.

You didnt say what version of Drupal your using, but if you are using D6
check this out Views Search

If not then check out Views

Then I guess you just have to get the node titles and make them as a exposed filter.  So you will need to expose 1 Filter, one for the node title and then also check out Autocomplete Filter

This link can also help you Views Exposed Filter Search

Update :

You might also wanna take a look on this, if your not to happy about using Views
, Its more integrated to the Search API
 Custom Search Module


Views query alter but Views calc is not rendering right result I am alter the views query with this

 <?php
function cc_invoice_views_query_alter(&$view, &$query) {
    foreach ( $query->where[0]['clauses'] as $key => $value) {
      $explode = explode('.',$value);
      if($explode[1] == "field_status_value = '%s'") {
         $alias = $explode[0];
         if($query->where[0]['args'][$key] == '0') {
            $query->where[0]['clauses'][$key] =  $alias . ".field_status_value IN ('%s' ,'%s')";
            #$query->where[0]['clauses'][$count] =  $alias . ".field_status_value IN '%s'";
            $query->where[0]['args'][] = -2;
         }
         elseif ($query->where[0]['args'][$key] == '1') {
            $query->where[0]['clauses'][$key] =  $alias . ".field_status_value IN ('%s' ,'%s')";
            $query->where[0]['args'][] = 8;
       }
         break;
      }
    }
}

?>

In this code, I just altered the views query. the result is displaying rightly, but in the views calculation section, the subtotal and total is not rendering right. It does not add the altered value while calculating the total or sub-total. Is there anything else i need to correct here. Please advise.

I have the same problem (pagers not working for custom queries), and while I am getting close to the solution I do not have it yet. Something that helped me to understand what is happening is a piece of code from OG that generates a table with pagers.

og_ui.admin.inc line 221

query:

  $query = db_select('users', 'u');
  $query->innerJoin('og_membership', 'ogm', 'u.uid = ogm.etid');
  $query
    ->condition('ogm.gid', $group->gid, '=')
    ->condition('ogm.entity_type', 'user', '=');

and the important part where the query gets cloned jost for the counter:

  $count_query = clone $query;
  $count_query->addExpression('COUNT(u.uid)');

  $query = $query->extend('PagerDefault')->extend('TableSort');
  $query
    ->fields('u', array('uid', 'name'))
    ->fields('ogm', array('state', 'created'))
    ->limit(25)
    ->orderByHeader($header)
    ->setCountQuery($count_query);
  $result = $query->execute();

My current solution is
do not use pagers when you edit view queries,
if you have to use a pager than create a whole template using the example from OG module (og_ui_menu() in og_ui.module + og_ui.admin.inc).

Hope it helps, but I would still be happy to know how to fix counter in views.


Drupal Custom Search Results Per Content Type So I have a View that is a list of all content on my site. I have an exposed form in a block that is "Search Terms". I have a custom template for my view to customize the results page. I have a couple of content types including "Products" and "Locations".

I'd like the Products to be displayed in a grid format with their corresponding product images and the Locations to be displayed in a list with a corresponding map. What would be the best way for me to accomplish this?

Here's a sketch of an answer: in a views template for the result set you will have access to the original results in $view->result. If the view is set up for fields output, and includes all the fields required including content type, you can iterate through it 3 times, each time ignoring entries that have the content type you don't want for that case.

It's quite hard to come up with clean-looking code because of the way that views names the field data, but if you don't mind that, you can use the dpm() function of the Devel module to inspect it then code accordingly.


Filter by text of a field of an entity displayed in a view I have following content types: "Person" and "Publication" and I'm showing the publications using a view on a page, showing title, year, venue and authors. The authors in "Publication" are referenced to "Person" via entity reference.
I added filter criteria so the users visiting the page can search publications based on title, author etc. The problem now is, that the field for searching by author only accepts the author's entity ID. But I want the user to search by a part of the author's name (either the entity title or a specific field in the "Person" entity).
What would be the best way to do this? I tried different ways via contextual filters, relationships and entity reference on the view, but neither of them worked for me, or I made something wrong. Any help would be appreciated!

Entity Reference Fields only store the entity ID. To pull other information about the referenced entity into the Views you need to add the Relationship for the ER field.
It will be called something like Content referenced from field_person.
Once you add that Relationship you unlock new Fields and Filters inside Views that relate to the Person entity.
You can now add (Content) Title Filter that uses the Relationship and it will filter text within the Title Field of the Person Content Type.
Without the Relationship the Title Field/Filter will show information about the Publication, the base type chosen for that particular View.
The same goes for other Fields/Filters. If you make them use the Relationship they will pull information from People CT.
Fields/Filters that only exist on People CT will have the Relationship prefilled, as a requirement (because that data isn't accessible in that View without the Relationship).


How do I disable update checks for locked projects? I am using drush @sites cron in order to get update notifications in a Drupal 7 multisite configuration.
However, I need to have some projects locked, using drush up --lock=context_mobile_detect.

Example:

.var.vhosts.drupalmulti#example.com           >>  Name                     Installed Version  Proposed version  Message
.var.vhosts.drupalmulti#example.com           >>  Context Mobile Detect    7.x-1.3            7.x-2.0-alpha1    **Locked via drush.**
.var.vhosts.drupalmulti#example.com           >>  (context_mobile_detect)                                       (Installed version not
.var.vhosts.drupalmulti#example.com           >>                                                                supported)

Since this command checks many sites, it sends many unnecessary emails of the form: "New release(s) available for example.com", although most of the time no module needs to be updated.

Is there a way, using code or not, to disable update checking of locked projects?

drush cron will trigger the default update manager search, whereas locked project are only locked during drush pm-updatestatus. If you want to prevent Update Manager from checking for particular modules, you'll need a custom module that implements hook_update_projects_alter. All you have to do then is unset($projects['context_mobile_detect']);.

E.g.

/**
 * Implements hook_update_projects_alter().
 */
function MYMODULE_update_projects_alter(&$projects) {
  unset($projects['context_mobile_detect']);
}

I do this quite a lot for Features modules, or custom code.


How to import entities? When using nodes, I use the rather good Feeds Import module and all is well with the world. I now need to use an entity as don't need URLS, comments etc so have created one called 'Cars' and have various fields attached to this.

I now need to import 1000 cars but have no clue how to do it? Using nodes this is very simple from csv, xml etc but entity seems to have no such module.

Does anyone know what I need to use to do this? Would I need to create a custom script that connects directly to the mysql and that writes to the fields I created?

it all depends on what functionality your entity provides. are you defining entity yourself or are you using some other module?

anyway simplest way is to create entity manually

$entity = entity_get_controller($entity_type)->create(array('bundle' => $bundle_type));//this could look this way ->create($bundle_type); depending on your constructor

$entity->your_field['und'] = $value;//assuming you don't use entity translation then language is und

entity_get_controller($entity_type)->save($entity);

in case your controller extends EntityAPIControllerExportable then you could use import/export  but if you importing from external source probably custom code would be easier


How to preserve element type validation upon adding custom element validation? I have ConfigFormBase.
It has a form element with '#type' => 'entity_autocomplete'.

When I add my custom element validation by '#element_validate' => [[get_class($this), 'validateReferencedItemExistence']] the original element validation which comes by the element type (Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete) won't be added anymore.

After spending hours in the jungle of the FormBuilder class code I finally found the corresponding lines:

   if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = $this->elementInfo->getInfo($element['#type']))) {
      // Overlay $info onto $element, retaining preexisting keys in $element.
      $element += $info;
      $element['#defaults_loaded'] = TRUE;
    }

I find this kinda bad approach, that you cannot extend the list of the validation items. What is the reason behind it?

How could I make a workaround / solve this issue?

(Just by calling Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete in my custom validation I would create an unnecessary depedency in my code. (Just think about if they change their way of validation with a different function))

You need add the definitions defined in the getInfo() method of that type explicitly yourself, there is currently no other way to do that.


Node Gallery Lightbox I am using Node Gallery Module, just want to know if there is a way we can open the images in Lightbox or Colorbox? I know this can be done in Media Gallery module but can not find any way in Node Gallery.

It can be done quite easily. I'm assuming that you are using Drupal 7 and using the Node Gallery as well as the Node Gallery API.

Install Colorbox for Drupal (including the library - follow the instructions on that page).
Now you have to some editing of the site structure (exact paths may vary but the provided paths will work if you are using the default Node Gallery installation settings):
go to admin/structure/file-types/manage/image/file-display (or browse: Admin->Structure->FileTypes->Image [Manage File Display]). Select Node Gallery File Thumbnail and put a check before Colorbox. Scroll down to Display Settings and under Content Image Style select node_gallery_thumbnail and select Per page gallery in the Gallery (image grouping) dropdown. Then Save Configuration.

Slightly complicated but not horribly so.


Android submission: I get a "CSRF validation failed" error while using a cookie The Drupal Version is 7 and the Services version is 3.4.

So, My login into Drupal goes like this:

Fetch a token. (POST)
Fetch a Cookie using the token. (POST)
Make GET Requests using DefaultHttpClient class to download data.
(GET). This uses a token and cookie

This all works fine. But when I try to post my submissions to drupal server, look at the code below

 DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(submissionURL);
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SurveyReviewActivity.this);
        String id = prefs.getString("sessid", "FAIL");
        Log.e("SRA", id);
        String name = prefs.getString("sessname", "FAIL");
         Log.e("SRA", name);
         //String token_test = prefs.getString("token", "FAIL");
        //Log.e("SRA", token_test);

          httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
         httpPost.setHeader("X-CSRF-Token", X_CSRF_Token);
         // httpPost.setHeader("X-CSRF-Token", token_test);
         httpPost.setHeader("Cookie",name+"="+id);  try {
             httpPost.setEntity(new StringEntity(message, "UTF8"));
         } catch (UnsupportedEncodingException e) {
             Log.d("Encoding Exception",e.toString());

        }
          try {
            HttpResponse httpResponse = httpClient.execute(httpPost);
             if(httpResponse.getStatusLine() != null && httpResponse.getStatusLine().getStatusCode() == 401) {
                 Log.d("Submission failed ", httpResponse.getStatusLine().toString());

             }

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                String json = sb.toString();
                Log.d("Response", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
        } catch (ClientProtocolException e) {

            Log.d("Protocol Exception",e.toString());
        } catch (IOException e) {

            Log.d("Protocol Exception",e.toString());
        }

When I set the last header (the cookie header), I get a token invalid or CSRF Validation Failed Error to be specific. If I don not use a token the submission goes through, but submissions are shown as anonymous on the drupal CMS side. I thought that my shared preferences are crapping up my stored cookie, but they are not thats why I was verifying them by printing them to logcat. I can get a new cookie and even tried that, but its still the same error. Whats going on here? Here are my references to the previous posts I checked on various sites.

...so if you plan on giving a solution which says your shared preferences are giving you the wrong cookie back or your token is coming down with a new line....tried that all...not working. But its working great on the iOS side, the exact same logic and actions.Please also note that, my cookie was working in fetching the data (bolded that part on step 3), but not while uploading data, its giving me a CSRF validation failed or token failed error . Please help me out on this issue.....and yes for testing the current cookie lifetime is 2 years..

CSRF token error comes when user is allready login to drupal site just logout then send the request you wont give this error again..hope this will help.


How can I get count of deleted rows How can I get count of deleted rows after db_delete?

db_delete('node')
  ->condition('uid', 1)
  ->execute();

something like

$count = db_delete('node')
  ->condition('uid', 1)
  ->execute()->columnCount();

doesn't work

The delete query will return a query object for all methods except ->execute(). Methods can be chained until the query has been assembled. Execute() completes the chain.

Try:

$count = db_delete('node')
  ->condition('uid', 1)
  ->execute();


Drupal distro for landing pages At my current work we do often landing pages (with their own domain)
I was wandering if someone already thought to do them with Drupal:

A multi-site (only one database) with several landing pages, each of them with their own domain. Anyone did it already?

How to face the multidomain feature?
Which are the best modules for accomplish this?

Have yo check the domain module? I think is the best option to solve this.

Another option, but more complex will be to create a Drupal as publisher backend and also Drupal as front end to the differents domains, you can share the content with feeds.

Oskar


user flag count in rules Is it possible to add a condition - user flag count? Meaning to count every flag that user gave.
I could find only - user is flagged and user has flagging count.

You should be able to run the action "Fetch entity flag count" against the entity you're dealing with. In Rules you can have variables to store that and compare later.


Add class on cck image field(img tag) I want to add a class on cck image field output img tag, not on field wrapper div.
How can i do it?

I think you should use Field Formatter CSS Class module for this. Module page says :

  The Field formatter CSS class module allows you to set any
  text/list/option/taxonomy field to render as CSS class on the node.
  This enables the node author to select predefined CSS styling per
  node.


Convert Acquia Clear Varnish For One URL Curl Command to Drupal::httpClient() I am trying to convert a command to php curl or Drupal::httpClient().
The original command
Curl -k -X PURGE -H "X-Acquia-Purge:[site-name]" --compressed -H "Host: example.com" https://bal-12345.prod.hosting.acquia.com/my-url

Here is the conversion I tried (but it is not working) This one returns 200 status code but it is not working.
$varnishUrl = "https://bal-12345.prod.hosting.acquia.com/my-url"
$headers = [
  'X-Acquia-Purge'  => "site-name",
  'Host'            => "example.com"
];
$options = ['headers' => $headers, 'body' => $varnishUrl];
try {
  $client = \Drupal::httpClient();
  $response = $client->request('PURGE', $domainUrl, $options);
  $code = $response->getStatusCode();
  if ($code == 200) {
    return $code;
  }
}
catch (RequestException $e) {
  watchdog_exception('module_name', $e);
}

This is the second conversion to php and also not working.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $varnishUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PURGE');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$headers = array();
$headers[] = 'X-Acquia-Purge: site-name';
$headers[] = 'Host: example.com';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
curl_close($ch);

I would appreciate any input.

I found the solution: https://docs.acquia.com/cloud-platform/performance/varnish/manually-purge/#manually-clearing-caches-for-applications-using-ssl
PHP way:
    $varnishUrl = 'https://bal-' . $elbDomain . '.prod.hosting.acquia.com' . $nodeUrl;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $varnishUrl);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PURGE');
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    $headers = [];
    $headers[] = "X-Acquia-Purge: {$xAcquiaPurge}";
    $headers[] = "Host: example.com";
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($code == 200) {
      return $code;
      curl_close($curl);
    }
    $errorMsg = curl_getinfo($curl);
    \Drupal::logger('module_name')->error(json_encode($errorMsg));
    curl_close($curl);

Drupal way:
    $varnishUrl = 'https://bal-' . $elbDomain . '.prod.hosting.acquia.com' . $nodeUrl;
    $options = [
         'verify' => false,
         'headers' => [
           'X-Acquia-Purge' => $xAcquiaPurge,
           'Host' => 'example.com',
         ],
       ];
       try {
         $client = \Drupal::httpClient();
         $response = $client->request('PURGE', $varnishUrl, $options);
         $code = $response->getStatusCode();
         if ($code == 200) {
           return $code;
         }
       }
       catch (RequestException $e) {
         watchdog_exception('module_name', $e);
       }


Image field - 'Number of values' is not showing up in admin form Something's very wierd with my existing Drupal 7 setup (current Drupal version, set up in early 2013, custom Zen Subtheme). When I create a new Content Type with a new Field Type "Image" this 'Number of values' pulldown isn't showing up where it should. I've now spent the whole day researching how this could be, without any luck.

I've tried default themes, checked user permissions and also file permissions (while always rebuilding the theme registry). I googled around for hours but I couldn't find any clue how to fix this .

What could be the reason for this?

Any tips for further testing are welcome.

Edit:

The field value is internally called cardinality.
The problem seems to affect all field types of this installation.

Answering my own question:
I tracked down the bug by disabling module by module and finally found out that disabling the Gigya - Social Infrastructure module was bringing back the form fields.

Fortunately the issue was already listed and solved five days ago!


Disable a field for input, without deleting it (to not lose old data) I have a field in my customer profile (shipping/billing, doesn't matter which).
I don't need this field anymore on checkout, but I want to keep the data of older orders.
(this can be extended to any entity type, it just happens that commerce customer profile is my use case)

Is it possible to somehow disable the field for input, but not really delete it?

Ideally with a UI solution.
I already know hook_form_alter() would do the trick..

You can use the Field Permissions module to remove permissions for users to access the field.


Get the value from $node inside two objects I have an array output like this from drupal, how do I access the value of [name] from
field_episode_tags, I have this so far

print $node->field_episode_tags['und']['0']['taxonomy_term']->['name']

When I get up to 'taxonomy term' there is another object i tried using another -> poitner but that did not work.

stdClass Object
    (
        [vid] => 25
        [uid] => 1
        [title] => Is there any cosmos theory?
        [log] =>
        [status] => 1
        [comment] => 1
        [promote] => 0
        [sticky] => 0
        [nid] => 25
        [type] => tv_episode
        [language] => en
        [created] => 1380610491
        [changed] => 1381115053
        [tnid] => 0
        [translate] => 0
        [revision_timestamp] => 1381115053
        [revision_uid] => 1
        [body] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [value] => summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text
                                [summary] =>
                                [format] => filtered_html
                                [safe_value] =>
summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text summary text

                                [safe_summary] =>
                            )

                    )

            )

        [field_video_category] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [tid] => 25
                            )

                    )

            )

        [field_featured] => Array
            (
            )

        [field_kaltura_video] => Array
            (
            ) und 0 taxonomy term->name

        [field_episode_tags] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [tid] => 95
                                [taxonomy_term] => stdClass Object
                                    (
                                        [tid] => 95
                                        [vid] => 1
                                        [name] => zen
                                        [description] =>
                                        [format] =>
                                        [weight] => 0
                                        [vocabulary_machine_name] => tags

                       [rdf_mapping] => Array

The correct way would be

print $node->field_episode_tags['und']['0']['taxonomy_term']->name

without the square brackets and quotes. Elements with in objects are accessed with

->objectname

and elements with in arrays are accessed by ['object']


Insert multiple checkbox value from webform into table I created:

a webform named Test Number checkboxes
checkboxes named Number with values one, two and
three using Form Builder
a table named checkbox_check

Aim: When the webform is submitted, the values selected are placed in a string and saved into the table. Example: If "one" and "two" are selected from the checkboxes, they will be saved like "one,two" in the table when the webform is submitted.
The table name is checkbox_check with field Number (Vachar 11)
EDITED: I just added these codes within the function webform_webform_submission_insert($node, $submission) from the webform.module file in my drupal project:
$accessnode=$node->nid;
if($accessnode==11)// the **Test Number checkboxes** webform containing the checkboxes
{
    $lastestSub=db_query("SELECT MAX(sid) FROM {webform_submitted_data}")->fetchField(); //retrieving the highest number of sid which is the lastest submission
    $selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchAll();

    $text='';// This will be used to concatenate the different values into a string and placed in the table afterwards
    foreach($selectedData as $valD)
    {
            $text=$text.$valD.",";
    }
        db_insert('checkbox_check')
        ->fields(array(

        'Number' => $text,
        ))
        ->execute();

}

When I submitted the webform, I got this error message:

Can you guys help me with this?

It works if I replace these codes:

$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchAll();

by this:

$selectedData=db_query("SELECT data FROM {webform_submitted_data} WHERE nid = :nid AND cid =:cid AND sid= :sid",array(':nid'=>$accessnode, ':cid' => 1, 'sid'=>$lastestSub))->fetchCol();


how do I configure a view to make two fields be inline what format should I use in order to make two fields out of three be inline in a drupal 7 view, and how do I configure this?

Hide the two fields in the views ui, then add a Global: Custom text field (make sure it is below the two hidden fields). In this field's text box you then add the two hidden fields back via replacement patterns (that's why it needs to be below the two hidden fields, else it will not see them), and wrap them in inline html or html that you will style inline.

You can use unformatted list format.

To make two rows out of three inline you will just use CSS with :nth selector. Else you can override the theme template for views (in advanced section). You copy and paste the template, then rename it to a proper suggestion. In that template it uses a loop to write the rows. You can rewrite that so that it loops over three at a time, prints two inline, one as block-level element.


Datepicker widget. How can I add some variable javascript code from my module to configure the date popup calendar? I need to personalize some settings in the date popup calendar in a date field.
This is the documentation for the popup calendar used in the Drupal date field:
http://api.jqueryui.com/datepicker/

I would to configure for example, the minDate property, to set a minimum selectable Date, according the documentation this is the code:

$( ".selector" ).datepicker({
  minDate: new Date(2007, 1 - 1, 1)
});

But... How and where do I type it in a custom module? It looks javascript, but I don't know how to make this code work for my date form element.

You can add it with #datepicker_options, e.g.:

$form['date'] = [
  '#type' => 'date_popup',
  // ...
  '#datepicker_options' => [
    'minDate' => 0,
  ],
];


Entity reference default value to first value I have an entity reference field using a view to dynamically create a list based on a contextual filter from a user ID in URL. Works perfectly.

Question is, how can I default the value to the first result in the list, instead of displaying -None- or -Please select-

You can do easily using jQuery

$("#target").val($("#target option:first").val());


field_create_field enable chosen I am using field_create_field and field_create_instance to create a taxonomy_autocomplete field in a rules action.

Can anyone help me enable chosen by default for these fields?

$vocab = '[vocabulary:machine-name]';

$field = array(
  'field_name' => 'field_termref_' . $vocab,
  'type' => 'taxonomy_term_reference',
  'settings' => array(
    'allowed_values' => array(
      array(
        'vocabulary' => $vocab,
        'parent' => 0
      ),
    ),
  ),
);
field_create_field($field);

$instance = array(
    'field_name' => 'field_termref_' . $vocab,
    'entity_type' => 'node',
    'label' => '[vocabulary:name]',
    'bundle' => 'product',
    'required' => false,
    'widget' => array(
        'type' => 'taxonomy_autocomplete'
    ),
    'display' => array(
        'default' => array('type' => 'hidden'),
        'teaser' => array('type' => 'hidden')
    )
);

field_create_instance($instance);

Using devels dpm function i managed to find the correct name of the setting, so the following now works...

$vocab = '[vocabulary:machine-name]';

$field = array(
  'field_name' => 'field_termref_' . $vocab,
  'type' => 'taxonomy_term_reference',
  'cardinality' => -1,
  'settings' => array(
    'allowed_values' => array(
      array(
        'vocabulary' => $vocab,
        'parent' => 0
      ),
    ),
  ),
);
field_create_field($field);

$instance = array(
    'field_name' => 'field_termref_' . $vocab,
    'entity_type' => 'node',
    'label' => '[vocabulary:name]',
    'bundle' => 'product',
    'required' => false,
    'widget' => array(
        'type' => 'options_select',
        'settings' => array(
           'apply_chosen' => 1
        )
    ),
    'display' => array(
        'default' => array('type' => 'hidden'),
        'teaser' => array('type' => 'hidden')
    )
);


How can I add "data-target" additional attribute in mega menu? How can I add an additional attribute to menu item I am using mega menu?

On element inspect my current menu url is displaying as :

 something

I need to create it as :

 something

I have used menu links attribute module but its not working with mega menu
any other suggestions by doing some custom code?

You can use below code to set attributes. This will add an attribute to all links in the page. But make sure to add the condition check for your URL.

/**
 * Implements template_preprocess_menu().
 */
function THEME_preprocess_menu(&$variables) {
  foreach ($variables['items'] as $item) {
    $item['attributes']->setAttribute('data-target', 'YOUR TARGET NAME');
  }
}


Performance and loading times of theme like Zen vs building a theme from scratch? Ive used Zen for every Drupal site ive made for years so im well aware of the benefits and how much it speeds up front end development. However I have noticed that there are far more div tags and css than would be needed if I built a theme from scratch and only included exactly what was needed. Especially as my clients are increasingly interested in mobile optimisation, are there any stats or anecdotal evidence about how much of a performance hit this extra markup is causing?

Although I have used Fusion, instead of Zen, my personal experience is probably applicable.  You can run some comparisons using Zen vs. Stark, which is very stripped down to get an idea how they compare.  There are, of course plenty of other factors that can contr5ibute to the equation.

Regardless of the performance issue, there is also the development question.  Styling one of these themes can be a challenge especially if you include panels, views, superfish menus, or any other module that may also affect appearance.  I had a full head of hair when I started.

I found it much easier to use Panels-Everywhere and Panels to bypass the them system and create my own display formats. This removes a lot of inherited CSS and made styling much easier.


Display specific node type in different path I have created a new content-type Document Template. I need to display the contents of type Document template in a different path.

localhost/site_name/document_templates

not in

localhost/site_name.

What should I do?

Use the pathauto module and configure it so this content type automatically gets the right path settings by default when creating a node.
https://www.drupal.org/project/pathauto


Add action links in custom module page I am writing a custom module for my project which handles a list of content (from custom db table) and content addition, following is my code.

function cp_menu() {
    $items = array();
    $items['admin/structure/package'] = array(
    'title' => t('Packages'),
        'page callback' => 'cp_packages_list',
        'access arguments' => array('administer access control'),
        'description' => t('Packages'),
        'type' => MENU_CALLBACK,
    );
    $items['admin/structure/package/add'] = array(
    'title' => t('Add package'),
        'page callback' => 'cp_form',
        'access arguments' => array('administer access control'),
        'description' => t('Add package'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function cp_packages_list(){
    return 'this is a test page';
}
function cp_form() {
    return array('#markup'=>drupal_get_form('cp_my_form'));
}

it is working properly, but i want to show action links (add content type) at top of page like

How can i add action links on page?

my action links would be 'Add package' and 'View orders'

$items['admin/structure/types'] = array(
    'title' => 'Content types',
    'description' => 'Manage content types, including default status, front page promotion, comment settings, etc.',
    'page callback' => 'node_overview_types',
    'access arguments' => array('administer content types'),
    'file' => 'content_types.inc',
  );
  $items['admin/structure/types/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/structure/types/add'] = array(
    'title' => 'Add content type',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_type_form'),
    'access arguments' => array('administer content types'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'content_types.inc',
  );

This is what exist on node.module, modify to set the type to MENU_LOCAL_ACTION

Hope that help.


Error: Class 'Drush\Sql\Sql' not found This is my first attempt at installing Drupal using Composer. I have successfully installed Composer and the Drupal Project template, which comes configured with Drush. To install I use

composer create-project drupal-composer/drupal-project:~8.0 {dir} --stability dev --no-interaction

Next, when I try to install Drupal using Drush with

../vendor/bin/drush site-install --db-url=mysql://{username}:{password}@localhost/{database}

I receive this error

Error: Class 'Drush\Sql\Sql' not found in /Users/.../vendor/drush/drush/src/Sql/SqlBase.php on line 81

I have installed Drush and Composer locally. I have tried requiring drush again after the composer install. I have tried using Drush 9.2.3. SO, If I go through the manual install of Drupal, Drush init does run, but any other command other than version gives me

In Connection.php line 149:
SQLSTATE[HY000] [2002] No such file or directory

I'm using:

Composer 1.6.5
Drush 9.3
Drupal 8.4.5

Does your password contain a #? Try this test:

<?php

function test_url($url) {
    $message = (parse_url($url) === false)?"parse_url unable to parse url:
{$url}\n":print_r(parse_url($url),true);
    echo  $message;
}

test_url("mysql://user:password@site/database_name");
test_url("mysql://user:C0mPl3XP4ss@site/database_name");
test_url("mysql://user:Ci)(*$!@@site/database_name");
test_url("mysql://user:pass#word@site/database_name");
?>

The last URL example fails to be parsed. This appears to be coming from

vendor/drush/drush/src/Sql/SqlBase.php:dbSpecFromDbUrl().

I hit the same issue and traced it to a '#' in my MySQL user password. Changed the password to remove the '#' and everything is working.


Using Doctrine in D8 I have downloaded the latest version of Drupal 8 my project structure looks like:

private/
  EntityOne.php
  EntityTwo.php
  Test.php => Test Script (Eventually AUT)
public/
  index.php => Drupal Engine

Inside Test.php I wish to begin building a series of entities which at first will be used externally and eventually be moved into Drupal modules.

I have Googled and spent hours trying to get Doctrine to start letting me build tables with my entities, but I am doing something wrong.

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/getting-started.html#obtaining-the-entitymanager

Is of no help, there is no "vendor/autoload.php"  but there is a "core/vendor/autoload.php"

I can include this file in Test.php and everything is fine but when I start adding code:

  include '../public/core/vendor/autoload.php';

  use Doctrine\ORM\Tools\Setup;
  use Doctrine\ORM\EntityManager;

  // Create a simple "default" Doctrine ORM configuration for Annotations
  $isDevMode = true;
  $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);

I get an error:

Fatal error: Class 'Doctrine\ORM\Tools\Setup' not found in ...\private\index.php on line 10

There is no "Doctrine/ORM"

What am I missing???

Alex

Drupal 8 uses the annotation reader from Doctrine Common but it does not use the ORM. The handbook page for the Drupal entity field API is being written at https://drupal.org/node/2078191


How to correct a view query? I would like to know how to correct a view query, when Drupal goes nuts ?
I'm using a view that should list media by categories (taxonomy term).
This view is called by a node, that held a reference to the same categories (same taxonomy term) that the medias I wish to display.
I need to order thos categories according to the delta field on my node object.
So in my views I did a join from the media taxonomy field to the taxonomy terms.
Then, I have a join on my any node that hold the taxonomy field.
I filter on the nid through contextual filters.
Until then all is good.
However, if I add the sort Critera on the delta value of categorie, the views module add another (unnecessaray) join on the table holding data for my taxonomy field on my node. This confuses my database and then I get a scalar product as results (every media is sent back, for each existing delta line).
Exemple of the query (I get two joins on node__field_categorie) :
    SELECT DISTINCT field_categorie_taxonomy_term_field_data__node__field_categorie.delta AS field_categorie_taxonomy_term_field_data__node__field_catego, media_field_data.mid AS mid, taxonomy_term_field_data_media__field_standard_termref_1.tid AS taxonomy_term_field_data_media__field_standard_termref_1_tid, field_categorie_taxonomy_term_field_data.nid AS field_categorie_taxonomy_term_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {media__field_standard_termref_1} media__field_standard_termref_1 ON media_field_data.mid = media__field_standard_termref_1.entity_id AND media__field_standard_termref_1.deleted = '0'
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_media__field_standard_termref_1 ON media__field_standard_termref_1.field_standard_termref_1_target_id = taxonomy_term_field_data_media__field_standard_termref_1.tid
INNER JOIN {**node__field_categorie**} taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie ON taxonomy_term_field_data_media__field_standard_termref_1.tid = taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.field_categorie_target_id AND taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.deleted = '0'
INNER JOIN {node_field_data} field_categorie_taxonomy_term_field_data ON taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.entity_id = field_categorie_taxonomy_term_field_data.nid
LEFT JOIN {media__field_domain} media__field_domain ON media_field_data.mid = media__field_domain.entity_id AND media__field_domain.deleted = '0' AND (media__field_domain.langcode = media_field_data.langcode OR media__field_domain.bundle = 'useful_document')
LEFT JOIN {**node__field_categorie**} field_categorie_taxonomy_term_field_data__node__field_categorie ON field_categorie_taxonomy_term_field_data.nid = field_categorie_taxonomy_term_field_data__node__field_categorie.entity_id AND field_categorie_taxonomy_term_field_data__node__field_categorie.deleted = '0'
WHERE ((media_field_data.status = '1') AND (media_field_data.bundle IN ('useful_document'))) AND (media__field_domain.field_domain_target_id LIKE 'intranet_adapei69' ESCAPE '\\')
ORDER BY field_categorie_taxonomy_term_field_data__node__field_catego ASC

Exemple of my view, so you can better understand.

How can I correct such a query ?
I'm using Drupal 8.7.12 and can't upgrade for the moment.
I guess the easier way around this would be to be able to add an order by clause using the column made available by my first join on : node__field_categorie
I looked into query_alter and views_query_alter hooks, but it seems it is no longer possible to add an order by clause there (or I tried the wrong way). Any ideas ?

Finally, I found how to do it. I don't understand why I got lots of errors previously.
 function sully_ad_import_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
if ($view->id() == 'document_list' && in_array($view->current_display,array('block_1','block_3'))) {

  $query->addField(
    'taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie',
    'delta',
    'delta'
  );
  $query->addOrderBy(
    NULL,
    NULL,
    'asc',
    'delta'
  );

}

}


Add validation on views bulk operations form I have a content type on which I added a custom validation that there can't be more than 7 items of that content type that is marked as 'sticky'.  That validation was added on the add and edit pages through omhm_mod_form_blog_node_form_alter(&$form, &$form_state, $form_id) with the line $form['#validate'][] = 'omhm_mod_form_nouvelle_node_form_validate'; and my custom validation omhm_mod_form_nouvelle_node_form_validate.

Now I have to make a page with views bulk operations with the same custom validation in place ... how can I do that ?

I'm trying to add the custom vbo validation views_bulk_operations_form_validate($form, &$form_state) to my omhm_mod_views_bulk_operations_form_alter($form, &$form_state, $form_id) hook with the line $form['select']['submit']['#validate'][] = 'omhm_mod_carrousel_views_bulk_operations_form_validate'; but nothing happens.

Your omhm_mod_views_bulk_operations_form_alter($form, &$form_state, $form_id) takes $form by value, not by reference, so any changes made to $form are scoped to the function only. That's why $form['select']['submit']['#validate'][] changes nothing. It should be omhm_mod_views_bulk_operations_form_alter(&$form, &$form_state, $form_id)

When you fix mistake I pointed above, and it will not help, be sure to test if your hook is run at all, and if it is, then test if your validator is. It'll be needed for your next question, if you will need to ask it.


Help with LDAP module for user authentication in Drupal 8.3.7 I just installed Drupal 8.3.7 via composer and am trying to get user logins to work against our LDAP server. I added and enabled the following modules:

We are using ldaps on port 636 rather than START-TLS on port 389 so I configured the LDAP settings as follows:

[SERVER section]
  Name: <whatever>
  Machine-readable name: ldap (not the hostname of our LDAP Server)
  LDAP Server Type: Default LDAP
  Server address: ldaps://<ip address of ldap server>
  Server port: 636

[BINDING section]
  Binding method for searches:L Service Account Bind: Use credentials in the Service Account field below to bind to LDAP
  DN for non-anonymous search: <dn for ldap auth user>
  Password for non-anonymous search: <password for ldap auth user>

[USERS section]
  <base dn for users>
  AuthName attribute: cn

When I try to test this config, I enter my cn in the "Testing Drupal Username" field and then click the Test button. I receive the following errors:

  Failed to bind with service account. LDAP error: Can't contact LDAP server (-1)
  Failed to find test user <my cn> by searching on cn = <my cn>.'

I can perform an ldapsearch using the auth ldap bind DN ok on the Drupal server. I enabled logging but the messages sent to /var/log/localmessages are not useful. I just see things like:

  ldap_search() function error. LDAP Error: Can't contact LDAP server (-1), ldap_search() parameters:
  LDAP search error: Can't contact LDAP server (-1). Context is base DN: <base dn> | filter: (cn=<my cn>)| attributes: []

Anyone have any ideas? I looked at the tcpcdump output comparing ldapsearch and the Drupal LDAP test and I don't see any TLS handshakes in the Drupal test case so I'm not convinced I have the ldaps part of the configuration working correctly.

Found the problem. I had a temporary cert in /tmp and specified in /etc/openldap/ldap.conf but systemd starts httpd with a private /tmp so the cert was not being found.


How is my website infected? My web server company recently reported me that my website is sending spams. I scanned the whole file system and found a number of infected php files like index.main.php, ipopup.php and  wtm9309n.php in sites/default/files directory.

All permissions for files and directories are set correctly. I have only one custom content type having 2 textbox fields that all users can create a new content of that type.

I checked the files table in database. except my uploaded files, there was no other files listed there, so (I think) that means the infected files are not uploaded via upload forms.

This is the only infected website among of the tens in my web server, so I think this a problem with this website instead of other things like OS vulnerabilities and ...

Enabled modules:

admin
cck
contact_forms
faq
filefield
imageapi
imagecache
imagefield
imce
nice_menus
node_export
views

Any suggestion? (Drupal 6.20)

There really isn't a lot to go on here.  You really need to try to match up the ctime (creation timestamp) on the malicious files with the Apache logs to see what may have happened.

Other than that, you should

Take a backup.
Do a yum update on your server to make sure you have all relevant patches.
Clean out your temp folders on the server, and reboot it.
Bring Drupal core up to date.  You are several versions behind, and have other security vulnerabilities.
Bring your contrib modules up to date.
Double check all permissions that may involve PHP input, like the PHP input filter, block visibility rules, view rules, etc.  To be honest, I would disable the PHP input filter altogether.
Audit your custom code to see if there are any problems.


How should I create a custom form? I create a module like this:

<?php
function mymodule_menu(){
    $items['mymodule/edit']=array(
        'title'=>t('Edit item'),
        'type'=>MENU_CALLBACK,
        'page callback'=>'mymodule_edit_view',
    );
    return $items;
}

function mymodule_edit_view(){
    //...
    $html.='<form '.$form_attr.'>';
    //...
    $html.='</form>';
    //...
    return $html;
}

function mymodule_form_alter(&$form, $form_state, $form_id){
    //...
}

I create a form in mymodule_edit_view, but when I access mymodelu/edit, the drupal did not call mymodule_form_alter. I do not want to create the form with drupal_get_form(), So how should I create the form?

This shouldn't work as @Alex said, because you are not using Drupal's Form API. You should implement hook_form($node, &$form_state), to create a form.

Sample code which creates a form with a single text field:

function MODULE_form() {
  $form = array();
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Field description goes here...'),
    '#required' => TRUE,
  );
  return $form;
}


Passing Arguments between an EntityReference field and an EntityReference View So I'm trying to figure out how to filter a couple of entityreference view I'm using to populate an entityreference field. It has the option to pass arguments to the view, but I'm not sure HOW to do that.

In one node add/edit form I need it to take the values of two taxonomy terms. Those terms would then filter down the list and only return values that included those values. The Taxonomy terms can have three values though.

I also have another form that I need to be able to filter based on what name is in the Authored by Field. I need to be able to pass that back to the view and only return nodes that are authored by the authored by user.

I'm not sure how you set that up and I'm trying to find documentation to figure it out. So far no luck.

If anyone has any ideas, let me know.

Add a contextual filter of Has Taxonomy Term ID

Select Provide Fixed Value and type Fixed Value. For fixed value type the ID's of your terms separated by a comma. (You can find the ID of your taxonomy terms inside the edit url when you edit your terms)

Scroll all the way down to the MORE section.

Click on MORE and check mark allow multiple values.

For your other view, use Author Uid and follow the picture below.


How to programmatically create a large taxonomy in Drupal 7? I need to create a taxonomy with an entry for every living language in the world (nearly 7,000, using ISO 639-3 codes: http://en.wikipedia.org/wiki/List_of_ISO_639-3_codes). Note that the ISO 639-3 code is stored as a custom field.

In light of this: what is the easiest way to create this list directly via MySQL using a PHP (or other) script?

I have attempted to directly create entries by inserting values directly into MySQL:

INSERT INTO taxonomy_term_data (vid, name, description, format) VALUES (2,"Ghotuo","
Africa
","filtered_html");

INSERT INTO field_data_field_iso_639_3 (entity_type, bundle, entity_id, revision_id, language, delta, field_iso_639_3_value) VALUES ("taxonomy_term", "language", 3, 3, "und", 0, "aaa");

INSERT INTO url_alias (source, alias, language) VALUES ("taxonomy/term/3", "language/ghotuo", "und");

I am obviously missing something, because this entry is not seen by Drupal in the "Languages" taxonomy.

I have looked at this question but am unsure how to set this up as a stand-alone PHP script (not incorporated into the site itself).

Any ideas how to programmatically create this taxonomy? TIA.

Myself still learning how to properly write modules, I managed to come up with the following code for saving the terms into separate table named MODULENAME_data. It may not be perfect - but it apparently worked. I'm open to downvoting, but even more to suggestions on how to improve it.

// Make the table name a constant for easier coding
// We will store it's vid as system variable after we have created it
define("MODULENAME_VOCAB_MACHINE_NAME", "iso_639_3_codes_data");

function MODULENAME_enable(){
  // Create the vocabulary.
  $vocab = array(
    'name' => 'Vocabulary name',
    'machine_name' => MODULENAME_VOCAB_MACHINE_NAME,
    'description' => t('Vocabulary of iso 639-3 language codes'),
    'module' => 'taxonomy',
    'hierarchy' => 0,
    'module' => 'MODULENAME',
  );
  taxonomy_vocabulary_save( (object) $vocab);

  // Now that we've created the vocabulary, let's store its vid as a system variable
  $vocab = taxonomy_vocabulary_machine_name_load(MODULENAME_VOCAB_MACHINE_NAME);
  $vid = $vocab->vid;
  variable_set('MODULENAME_vocab_id', $vid);

  // Create custom field.
  $field = array(
    'field_name' => 'field_custom_field',
    'type' => 'text',
    'label' => t('Symbol') // where is that used? I dunno, but API says so ;-)
  );
  field_create_field($field);

  // Create field instance on the vocab
  $instance = array(
    'field_name' => 'field_custom_field',
    'entity_type' => 'taxonomy_term',
    'bundle' => MODULENAME_VOCAB_MACHINE_NAME,
    'label' => t('Custom field'),
    'description' => t('Description'),
    'required' => true,
    'widget' => array(
      'type' => 'text_textfield',
     )
  );
  field_create_instance($instance);

  // Here you would include an include file that provides row data
  // (probably an array) and then iterate over it to populate table
  // such as

      // Save terms.
      foreach ($items as $item) {
        taxonomy_term_save((object) array(
          'name' => $item[0],
          'vid' => $vid,
          'field_custom_field' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => $item[1] ,
              )
            )
          ),
        ));

}

function MODULENAME_disable(){
  // Some system cleanup.

  // Delete vocabulary. This deletes terms and field references too.
  taxonomy_vocabulary_delete(variable_get('MODULENAME_vocab_id'));

  // Delete variable from system.
  variable_del('MODULENAME_vocab_id');
}

Word of comment:

I'm still not sure whether the hook_disable() would be supposed to do what I put into it, but my understanding is that once a module is disabled, the features installed by it would be supposed to be unavailable too. I'm unsure about the field references - not only do they remain in the system in my code, but once we re-enable the module, the references will not be restored due to new IDs.
I'm also not sure how one would make the vocabulary i18n-savvy, meaning - when you would like to install the vocabulary along with translations - vocabularies provide several i18n modes and I'm not in the knowledge how to support them programatically.

This is something I would love to learn from someone.


Content type export with drupal console not working I have a content type called slider as the image below shows:

I tried the following to export the content-type:

drupal config:export:content:type slider

when I enter the command, I am prompted to type a module name, which doesn't sound right.

Enter the module name [admin_toolbar]:

How can I export a specific content type using the drupal console?

Drupal console will create a new module for you and export the content type as configuration in new module under config folder.
Eg.  drupal config:export:content:type slider \
--module="new_module"


Hide the title of a form element? I'd like to use placeholders instead of labels for a form built with the form API.

I can get placeholders working well with the Elements module, but now I want to hide the labels. If I just set ['#title'] = NULL; then form errors don't have descriptive names, and it ruins accessibility.

In Drupal 7, you could set the #title_display to invisible (documentation). Was something like this backported in a contrib module somewhere?

Or is there a way I can set my own class on the label element?

You could override the theme_form_element() function in your theme's template.php so that the label does not output:

// Remove  from output

function THEMENAME_form_element($element, $value) {
  // This is also used in the installer, pre-database setup.
  $t = get_t();

$output = '\n";
  $required = !empty($element['#required']) ? '*' : '';

if (!empty($element['#title'])) {
    $title = $element['#title'];
    if (!empty($element['#id'])) {
      $output .= $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
    else {
      $output .= '$t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required));
    }
  }

$output .= " $value\n";

if (!empty($element['#description'])) {
    $output .= ' ' . $element['#description'] . "\n";
  }

$output .= "\n";

return $output;
}

Alternatively, you could target the form id > label and set it to display:none without modifying the theme function.


Custom access callbacks for user entities not being called I'm trying to implement some custom access control for user entities, in Drupal 7.

I've used hook_entity_info_alter to set

$entity_info['user']['access callback'] = 'MYMODULE_user_access_callback';

and when I call entity_get_info at a later point, I can see that this is still successfully set.

But MYMODULE_user_access_callback never ever seems to get called when I try to display users directly, or load Views of users.

It looks like the custom access callbacks are normally called from the entity_access function in entity.module. But the user_access function in user.module doesn't ever call them.

user_load in the user module calls entity_load, which calls entity_get_controller($entity_type)->load(...)

but this still doesn't seem to invoke entity_access.

So is setting 'access callback' for the user entity a wrong way to go about trying to implement custom user access control? Do I need to override UserController perhaps?

The problem might be the execution order of the modules

  How to change access callback of user entity when entity module is installed? (how to make sure my alteration is the last)


How to configure drupal-nodejs with https? In drupal-nodejs configuration we have IP with port but how can I have the https for that configured.

Go to /admin/config/nodejs/settings and select https.

Then scroll down a bit to javascript and also select https here.


Is there a way to add content templates for blog I've been asked to add templates (where a blog post is pre-created with certain content) and the user simply selects it and make minor changes. Please note this is not a visual template, but a content one.

Thanks!

Go to Manage fields

Ex: /admin/structure/types/manage/article/fields

Then click on edit, for example, the body field. Look for Default Value and put whatever you want there.

Now when a user tries to add a new article, it will have the body pre-filled-out and they can change it if they wish.


Are there alternatives to using URL to Image Formatter? We had a need to set an image as a background element for a
 tag (see example below). When we tried to the following (with Image as formatter) it only returned the original image url, not the image URL based on the image style.

Without having to use preprocess hooks to modify the URL, we have set the display formatter to be "URL to Image" on the default View Mode and we get the desired results. If I want to use Image formatter, I had to write a preprocess hook, which I want to avoid and adding an additional module like twig_tweak seems over complicating it.

Are there any other alternatives to using the URL to Image formatter and {{ content.field_image.0['#markup] }} without having to use a preprocess hook?

Example using Image formatter

{{ content.field_image.entity.uri.value }}

Results

Example using "URL to Image" formatter

{{ content.field_image.0['#markup] }}

Results (desired results)

Alternative solution

This looks like it will get the url to image with image style.

Set formatter as URL to Image
in twig template use {{ content.field_image.0 }}

Background Image Formatter provides a new formatter that can do this. You will probably want a unique identifier on your target div, but this module should do the trick otherwise. There's a responsive_bg_image_formatter submodule for using responsive image styles for your bg image.


address dependent locality field not shown drupal 8.8.2  address 8.x-1.7

address module is working in that i can add an address to my content, however I am not able to display the "dependent locality " field  even when it is set to "no override" or "required"

from the doc i did find : https://docs.drupalcommerce.org/commerce2/developer-guide/customers/addresses/countries-and-subdivisions

it shows a "suburb" field, which i am assuming is this field.  I was planning to use this to contain the "county"

is there a dependency i need to check to enable this field ?

thanks for your time.

ps. i was not sure how to tag this question, i did not see a tag for modules or address

i must be blind... right under the doc i was reading i see

The Commerce Guys addressing data set only includes subdivisions that are required for addressing.

so this field is not included because it is not needed for an address.