User band management I have a content type of band. I have a view filtering by user id to see my bands.

What I'm trying to accomplish is allowing users to create a band and have a management dashboard. This dashboard would be separate from their public facing page.

I would like the dashboard to have the ability to add shows, members, photos etc all on the same screen.

My guess would be to create a page with multiple views filtered based on some type of criteria either a reference field to members or the single node author.

Is there a better approach to handling this type of functionality?

Your question is about relationships between the different entities or content types like users, bands, shows and so on. You build this relationships with reference fields.

For the dashboard you don't need necessarily views.

When you use a reference field to another entity you can configure in the display mode to render the referenced entities. Then you can configure the display mode of the referenced entity, which can contain itself other reference fields which you then configure in the same way and so on.

So you can build and theme the complete dashboard without views by only showing the parent entity.

Though at some point you probably need views, as view block in a header, footer or sidebar or from the start as view page, if you need more options for filtering. The entities displayed in these views can contain again rendered reference fields. This is how you combine these tools to build the layout you want.


Alter existing 'Log In' route so URL includes request_uri as query string I am trying to alter the existing 'Log In' URL so that it points to a certain location and also includes  the REQUEST_URI as a query string that is not encoded. How do I do this?
Based on this article, Altering existing routes and adding new routes based on dynamic ones and this SE answer I can change the 'Log In' URL so it points to a different location (/login). What I can't seem to figure out is how to add a query string that isn't encoded.
This code:
$route->setPath('/login?destination=' . \Drupal::request()->server->get('REQUEST_URI'));

Gives me:
/login%3Fdestination%3Dpage2

What I want is:
/login?destination=page2

I have looked into RequestContext::setQueryString and Route::addOptions but can't seem to get anything to work.
Full code:
<?php
namespace Drupal\myModule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {

    /**
    * {@inheritdoc}
    */

    protected function alterRoutes(RouteCollection $collection) {
        // Change path '/user/login' to '/login'.
        if ($route = $collection->get('user.login')) {
            //$route->setPath('/login');
            $route->setPath('/login?destination=' . \Drupal::request()->server->get('REQUEST_URI'));

        }

        // Always deny access to '/user/logout'.
        // Note that the second parameter of setRequirement() is a string.
        if ($route = $collection->get('user.logout')) {
            $route->setRequirement('_access', 'FALSE');
        }
    }
}

I think you'll need to have a look to PathProcessors, you might do something like that:
mymodule/mymodule.services.yml
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }

mymodule/src/PathProcessor/MymodulePathProcessor
<?php

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class MymodulePathProcessor.
 *
 * @package Drupal\mymodule\PathProcessor
 */
class MymodulePathProcessor implements InboundPathProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function processInbound($path, Request $request) {
    if ($path == '/user/login') {
      $request_uri = $request->server->get('REQUEST_URI');
      return "/login?destination={$request_uri}";
    }
  }
}

Don't forget to clear the cache before to try it.
You might need the processOutbound function too in which case you'll need one more line in your service
mymodule/mymodule.services.yml
mymodule.path_processor:
  class: Drupal\mymodule\PathProcessor\MymodulePathProcessor
  tags:
    - { name: path_processor_inbound, priority: 250 }
    - { name: path_processor_outbound, priority: 250 }


How to stop drush displaying a Drupal error message? This question is a follow-on from this one about creating managed files. If you look at the question in the link, you'll see that I am writing a drush command to detect all the inline-images in a just-migrated Drupal 8 system, and add them into Drupal as managed images attached to the relevant nodes. To cut a long story short, this bit of code takes the existing file name and creates an entry in Drupal:

$file = entity_create('file');
$file->setFilename($file_name);
$file->setFileUri('public://images/'.$file_name);
$file->save();

This works fine, except that it very irritatingly displays this error message with every file: Object(Drupal\Core\Entity\Plugin\DataType\EntityAdapter).uri: The file public://images/rint135_graph4_0.articleimage.PNG already exists. Enter a unique file URI.

Of course the file exists! That is precisely the point! Despite the error message everything seems to work ok, but I would really like to get rid of those error messages. I guess that they are being set by drupal_set_message(), since they include HTML which of course is pointless in drush - but I can't find any way to switch them off.

Two options:

Hide the messages with ob_start() and ob_end().
Avoid the messages by moving the target file out of the way, and moving it back again after saving the entity.


Is there a hook that could manipulate the list of field items before the field is built? I am currently porting a custom field module from Drupal 7 to 8. The field (Topic Access) has 3 select fields, typically about 10 to 20 items per field, and uses a custom widget. When the form is loaded, I typically insert several "inherited" items to the field before displaying it. When saving, only the items that vary from the inherited ones are actually saved to the database.
In Drupal 7, I used hook_field_load() to add these "inherited" items to the form. As explained on Dynamic/Virtual field values using computed field property classes, that hook has been removed from Drupal 8 in favor of computed field properties.
I can't see an elegant way to manipulate the list of items. I could use hook_form_alter() on the forms that contain the field to update $form['field_topic_access']['widget']. However, it would end up duplicating code from the widget and have to specifically pick out the fields by name.
Is there a hook that could manipulate the list of field items before the field is built?

What about hook_entity_prepare_form()? This simple example loaded an extra item into the form.
function mymodule_entity_prepare_form($entity, $operation, $form_state){
  if ($entity->bundle() == 'domain_groups') {
    $items = $entity->get('field_topic_access')->getValue();
    //just a hardcoded item for test purposes
    $demo_item=['topic_tid'=>'74','available_to_group'=>'1', 'publish_to_group'=>'0'];
    $items[] = $demo_item;
    $entity->set('field_topic_access', $items);
  }
}

There may be a more elegant solution but I could use this hook to show my inherited items and hook_entity_presave()  to remove inherited values before saving.


Cloudflare Clear Cache For One URL, Convert Curl Command to Drupal::httpClient() Or php I am creating a custom module to clear caches on cloudflare for one url.
The original curl command:
curl -X POST "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache" \
     -H "Authorization: Bearer 123456789" \
     -H "Content-Type: application/json" \
     --data '{"files": ["https://example.com", {"url": "https://example.com/my-url"}]}'

Drupal::httpClient
try {
  $client = \Drupal::httpClient();
  $url = "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache";
  $options = [
    'headers' => [
      'Authorization' => 'Bearer 123456789',
    ],
    'json' => [
      'files' => 'https://example.com',
      'url' => 'https://example.com/my-url'
    ],
  ];
  $response = $client->request('POST', $url, $options);
  $code = $response->getStatusCode();
  if ($code == 200) {
    return $code;
  }
}
catch (RequestException $e) {
  watchdog_exception('module_name', $e);
}

php version:
$data = Json::encode(['files' => 'https://example.com', 'url' => 'https://example.com/my-url' ] );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/zones/123456789/purge_cache');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$headers = array();
$headers[] = 'Authorization: Bearer 123456789';
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
curl_close($ch);

I got one working by clearing all caches on clouldflare.
Original:
curl -X POST "https://api.cloudflare.com/client/v4/zones/123456789/purge_cache" \
     -H "Authorization: Bearer 123456789" \
     -H "Content-Type: application/json" \
     --data '{"purge_everything":true}'

The working Drupal Version:
    try {
      $client = \Drupal::httpClient();
      $options = [
        'json' => [
          'purge_everything' => TRUE,
        ],
        'headers' => [
          'Authorization' => 'Bearer ' . $authorization,
        ],
      ];
      $response = $client->request($method, $url, $options);
      $code = $response->getStatusCode();
      if ($code == 200) {
        return $code;
      }
    }
    catch (RequestException $e) {
      watchdog_exception('cloudflare_purge', $e);
    }

The drupal version return 200, but it is not doing anything and the php version I could not get it work. I would appreciate any input.

https://api.cloudflare.com/#zone-purge-files-by-url
I found the solution, so this command:
curl -X POST "https://api.cloudflare.com/client/v4/zones/abcdefghijklabcdefghijkl/purge_cache" \
     -H "Authorization: Bearer abcdefghijklabcdefghijkl" \
     -H "Content-Type: application/json" \
     --data '{"files": ["https://example.com", {"url": "https://example.com/url"}]}'

It will be in Drupal like:
      $client = \Drupal::httpClient();
      $options = [
        'headers' => [
          'Authorization' => 'Bearer abcdefghijklabcdefghijkl',
        ],
        'json' => [
          'files' => ['https://example.com/url']
        ],
      ];
      $response = $client->request('POST', $url, $options);
      $data = $response->getBody()->getContents();
      $data = json_decode($data, TRUE);
      if ($data['success']  == TRUE){
        return TRUE;
      }


Reference three types of entities and render them in one list I have this requirement, where a Node needs to reference instances of three different types of entities (a Node, a custom entity, and a webform). These three entities will then be rendered as one list of "related content".

Currently, I have them as three separate entity reference fields. But I could not figure out how to render them as a single list (it ends up being three lists of entities). Also tried the Dynamic Entity Reference module, but that one doesn't reference Config Entities (webform).

Am I missing an obvious way to achieve this?

If I understand your question correctly, you currently have three different reference fields (one for each entity type to reference to) that each can have multiple values. And you want to combine the value of these three fields in groups, so the first values are displayed as a set, the second values are displayed as a set, etc.

I think the Paragraphs module is what you are looking for. You can create a paragraph that contains the three reference fields, in your case allowing only one value per field. And on your node (type) you add a multi-value paragraphs field, allowing your editor to provide groups of references which are rendered together.


Can I use Node Reference Field as a Text Field if there are no references? I'm creating a content type Event. I want to reference the node of another content type Venue, so the user will be able to click to the venue node from the event.

To reference the venue on the Event creation page, ideally it would be a text field with autocomplete showing a list of possible venue nodes.

Now if the venue node hasn't been created yet, can Drupal allow the Event to be created using the entered text as display (i.e plain text)?

Use the Node Reference Create module.

  Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.

  When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.


How do I theme a webform? I am in need to theme webform in D7.

How can I do that ?

In the search I've come to know that by using web-form-nid.tpl.php we are able to theme a drupal individual form.

Could any one guide me in this case to theme a webform.

You can theme a individual webform using webform-form-nid.tpl.php.

For example if our webform node id is 7 , create a template file namely webform-form-7.tpl.php and place it in your theme folder. Clear site cache.

Do a print_r($form); to see all the elements. Then render each elements in file within your html elements.

<li>
    <?php print drupal_render($form['submitted']['name']); ?>
</li>

As  @Patrick Kenny said read the theming.txt, it explain all aspects of theming a webform


Form API - match field with error I have a weird question. Let's say we have this form:

$form['field1'] = array(
  '#type' => 'textfield',
  '#title'  => 'First field'
);
$form['container'] = array(
  '#type' => 'container'
);
$form['container']['field2'] = array(
  '#type' => 'textfield',
  '#title' => 'Second field'
);

Now if you set an error for field2, you do it like this:

form_set_error('field2', 'error message');

and not like

form_set_error('container][field2', 'error message');

I wonder how does drupal does recognize the right form element to add the error class. I wanna do something like that, to add a suffix for every field who did not passed validation.

I tried getting the error field with form_get_errors() but it returns field2 as a field with an error. It's obvious that $form['field2'] does not exists add I can't add a suffix to it.

Any help is greatly appreciated. Or at least a hint to the right direction. Thanks :)

Drupal does it on elements theme level with _form_set_class function. This function gets $element array and checks if it has errors with function form_get_error. Because errors are set with indexes like 'foo][bar][value' (parents) that can be not so easy to find them in the $form array. So I suggest to use the same check as in _form_set_class with your function at pre_render, theme or validate level when you have $element array. hook_element_info_alter can be useful.

The super simple example:

function YOUR_MODULE_element_info_alter(&$elements) {
  foreach ($elements as $type => $value) {
    $elements[$type]['#pre_render'][] = 'YOUR_MODULE_element_error_check';
  }
}

function YOUR_MODULE_element_error_check($element) {
  if (isset($element['#parents']) && form_get_error($element)) {
    $element['#suffix'] = t('error!');
  }
  return $element;
}


Undefined variable block...when trying to integrate a form into a block i was just beginning to build my first module which should display a checkbox in a block.

With this code (see below) I get an Error:
Notice: Undefined variable: block in ios_lang_checkbox_block_view()

<?php
function ios_lang_checkbox_menu() {
    $items['ios'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('ios_lang_checkbox_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM
    );
    return $items;
}

/**
 * Define a form.
 */
function ios_lang_checkbox_nameform() {
    $options = array(
        'de' => t('de'),
        );
    $form['ios'] = array(
        '#title' => t('Your Name'),
        '#type' => 'checkboxes',
        '#description' => t('Choose language'),
        '#options' => $options,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit')
    );
    return $form;
}
function ios_lang_checkbox_block_view($delta='')
{
  switch($delta) {
    case 'ios_lang_checkbox':
      $block['subject'] = null; // Most forms don't have a subject
      $block['content'] = drupal_get_form('ios_lang_checkbox_form_function');
      break;
   }
   return $block;
 }

?>

Any help with that?

In order for hook_block_view() to work properly you also need to implement hook_block_info(), which in your case would look something like this:

function ios_lang_checkbox_block_info() {
  return array(
    'ios_lang_checkbox' => array(
      'info' => t('Block Name'),
      'description' => t('Block description')
    )
  );
}

That will register a block called ios_lang_checkbox, which will become the $delta var when your implementation of hook_block_view() is invoked.

At the moment, when that function executes there's no $delta available (since one hasn't been defined), and hence $block is undefined when you return it. Usually one would write $block = array() at the start of the function to avoid this, but in your case that would actually just have masked the problem.

The signature for your form function is slightly wrong, that needs to be:

function ios_lang_checkbox_nameform($form, &$form_state) {

It won't actually affect anything on a form that simple, but it's a good practice to get into...eventually it will come back to bite you if you don't!

The other small issue is the name of the form function you're calling inside hook_block_view()...I suspect you mean it to be the same form that's available from the path defined in hook_menu(), in which case that line should be:

$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');

Once you've made the changes, make sure to clear Drupal's caches...otherwise your new hook implementation won't get picked up.


Toggle Modules on or off at a certain time with Rules I'm looking for a way to toggle a Module on or off based on the time of day using Rules. Ideally, the logic behind it would be something like:

IF

The time is between 1700 and 0900 AND Module X is turned OFF

THEN

Turn Module X ON

ELSE IF

The time is between 0900 and 1700 AND Module X is turned ON

Turn Module X OFF

ELSE

Turn Module X OFF

I'd like this to run with each CRON run (15 minutes). Is this achievable using Rules and without going into PHP?

Since you run cron in every 15 minutes, you can use module_disable or module_enable in hook_cron of your module. Using

format_date(time(), 'custom', 'l j F Y');

you can get the current date and time. What is difficult for you to build such module?


How to programtically queue a function for 48 hours (to change webform Author) The code below changes the submission author to that of a user referenced in the webform (pulls username:uid). However now need this to change after 48 hours.

I am unsure how to effectively queue this for 48 hours before it runs or even if that is possible (I guess I will have to change the hook to "hook_webform_submission_update")..

I was thinking of rules but is there a hook which would help? Also if rules is the answer could anyone shed some light on how I can implement it into my code?

// change submission author to the submitted user lookup
function helper_custom_webform_submission_presave($node, &$submission) {

    // get uid from user_lookup
    $user_lookup_cid = 1;
    $user_string = $submission->data[$user_lookup_cid]['value'][0];
    $user_string = explode(":", $user_string);
    $uid = $user_string[1];

    //change submission to be saved by user
    $submission->uid = $uid;
}

Implement hook_webform_submission_insert() such that it saves $node->nid, $submission->sid and the current time to a designated table (e.g. newsubmissions).

Implement hook_cron() such that it goes through all records in the newsubmissions table, that are more than 48 hours old. For each such record, you should

load the submission by calling webform_get_submission(),
change the owner of the submission,
save the submission by calling webform_submission_update(),
delete the record from the newsubmissions table.

Implementing hook_webform_submission_presave() the same way as hook_webform_submission_insert() will not work, because

$submission->sid is not yet set and
hook_webform_submission_presave() is also called for old submissions.


define my own entity.tpl for my custom entity? How to define my own entity.tpl for my custom entity? I am using entity API to declare my entity and its controller and class. I don't want to use entity.tpl of entityAPI but my own tpl.

Unfortunately, is not as simple as creating a custom template named ENTITYNAME.tpl.php.

You may want to reconsider theming an entity.  Entity-level code should only deal with low-level data manipulation.  Rendering for the browser should handled separately by the Drupal theme layer, not the entity itself.

However, if you want to override the theme layer for your entity, you can do it by overriding the page template for your entity (i.e. page–-ENTITYNAME.tpl.php (where "ENTITYNAME" is the machine name of your entity).

But this is probably not what you're asking about.  If you insist on theming your entity, there is a solution is written up here: Theming Custom Entities @ Drupal.org.

To summarize: You do it by means of three functions that you place in the module defining the entity:

MODULENAME_menu() hook.
Page Callback
MODULENAME_theme() hook.

The MODULENAME_theme() hook is used create this module's Theme Registry entries.


How to control Block revisions before being published? Does Drupal support blocks versioning? Are there any modules can be used for controlling blocks revisions and publish selected version?

For example: a newly created blocks shall be published after being reviewed by a reviewer role user. So that the content will not be displayed in the page until it is published, meanwhile the content can be edited and sent for review and publish many times between the creator and reviewer.

Any suggestions about how to achieve this?

I would use the Bean module for this. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.

Moreover, by using Beans (i.e. entities), you qualify also for considering the Content Publishing System module (CPS for short) ... from commonly known "merlinofchaos". Here is an excerpt from that project page:

  ... CPS is a radical way of handling revisions for entities. It takes total control over revision management for all supported entities. For CPS-enabled entities, the revision tab is completely replaced and users are not allowed to manually create or move around revisions.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A few more interesting issues related to all this:

bean workflow (published-deploy, unpublished-nodeploy)
Bean revision workflow support?


How do you combine exposed filter string text searches into one input field for Drupal 7 Views? Currently I have a bunch of exposed filters in my view but I want to combine them where I can search them using only one input field. How can this be done?

If you want to be super-flexible in your search, essentially searching through the whole listing rather than just a particular field or two, I'd suggest you simply add the 'Search Terms' filter.

If you go to add another filter to your view, you can narrow the options by the 'Search' related ones and select the 'Search Terms' one:

You can name it anything you want, but it will essentially search through your entries the way a regular search does - so, by default, it will search through all fields that are displayed on your node, not just the ones you're displaying in your view at the moment.  Hope that makes sense - just another option to consider in the mix.  :-)


How to make Entity View show Entity's custom dynamic label as page title (D8) My custom content Entity overrides label() to provide a dynamically generated, human-readable label like:

public function label() {
  return $this->displayName();
}

Unfortunately, that label does not get used by the EntityViewController. In my module.routing.yml file I have:

entity.veranstaltung.canonical:
  path: '/admin/veranstaltung/{veranstaltung}'
  defaults:
    _entity_view: 'veranstaltung'
  requirements:
    _entity_access: 'veranstaltung.view'

I can now view my "veranstaltung" entities, but the page title is blank and the breadcrumb just shows the entity's id instead of its label.

Looking in EntityViewController::buildTitle() I can now see why this is the case:

$label_field = $entity->getEntityType()->getKey('label');
if (isset($page[$label_field])) {
  $page['#title'] = $this->renderer->render($page[$label_field]);
}

I don't have a label key, as I want the labels to be dynamically generated.

Any suggestions how to best deal with this problem?

Similar to the NodeViewController, you can write you own VeranstaltungViewController extending EntityViewController, and implement a title function. In your route can then set _title_callback to use this function (see NodeRouteProvider as reference).


How to apply theme to Drupal view or block I have created 1 view for displaying Category on home page using Ubercart module.

but i want to apply custom css  changes to my Category view fields like image and title

can any knows how to apply css change to DRUPAL views.

Thanks in advance.

Go to your view display and look at the bottom of the "advanced" column. You'll see something like "Theme : Information". Try to locate your template name and click on it to get it's base code.


How to copy current directory into Drupal profile folder via drush? I've this yml file in my current folder:

$ cat profile.yml
api: 2
core: 7.x
projects:
  drupal7:
    type: "copy"
    download:
      url: "file://."

and 3 empty files (just for now): drupal7.info, drupal7.install, drupal7.profile.

And I've downloaded fresh Drupal:

$ drush -y dl drupal
Project drupal (7.39) downloaded to drupal-7.39.

Now I'm trying to copy my profile into Drupal directory via:

$ drush make --no-core profile.yml drupal-7.39/
Beginning to build profile.yml.
Non-existent project type copy on project drupal7.

and the same with:

$ drush make -r drupal-7.39/ --yes --no-core profile.yml

This is based on this example:

projects[example][type] = "profile"
projects[example][download][type] = "copy"
projects[example][download][url] = "file://./example"

but I'd like to achieve that in yml format.

What is the correct syntax then? Or how does it work?

I actually had to specify extra type: "profile" (to follow this example), so type is specified twice (type of project, and type of download), as below:

api: 2
core: 7.x
projects:
  drupal7:
    type: "profile"
    download:
      type: "copy"
      url: "file://."

Then this would work fine:

$ drush make --no-core profile.yml drupal-7.39/
Beginning to build profile.yml.
drupal7 copied from file://..

To avoid copying docroot/ it-self, it's good to actually create a separate folder for profile (as specifying wildcard won't work).


How to add indexed:has taxonomy term id(with depth) in the contexual filter of view? I have created a view and added indexed fields to that view to show content.

I want to show content related to taxonomy "related place" as well as its related child taxonomy content. For selecting child taxonomy I used simple hierarchical module, but the problem I am facing is that I'm not getting any option to select Indexed:has taxonomy term id(with depth) in contexual filter to show content .

The propose of using indexed fields in views for filtering content using facet api.

I've tried everything to achieve this, but no result.

In custom module

you can use hook__views_pre_view to change contextual filter,
add children terms till depth to the contextual filter,
function taxonomy_get_children_all() defined below, will fetch all child terms till depth:
In view, don't forget to allow multiple value contextual filter for contextual filter.

function taxonomy_get_children_all($tid, $vid = 0, $key = 'tid'){
  $c = taxonomy_get_children($tid, $vid, $key);
  $result = array();
  foreach ($c as $t => $d){
    $result[$t] = $d;
    $below = taxonomy_get_children_all($t, $vid, $key);
    if (!empty($below)) {
       foreach ($below as $nt => $nd){
         $result[$nt] = $nd;
       }
    }
 }
 return $result;
 }

 function formalter_views_pre_view(&$view, &$display_id, &$args){
 if($view->name == "category_view") { // && $display_id == "page") {
   $vid = <Your vocabulary id>;

   $t = $args[0];

   $tt = taxonomy_get_children_all($t,$vid);
   foreach($tt as $k => $v) {
     $a = (string)$k;
     $args[0] = $args[0] . "+" . $a;
   }
 }
}


How to redirect to l() function link after login? I'm having a Simplenews newsletter template with a link guiding newsletter readers to a intranet site with more news.

<?php print l('hier.', 'node/' . $build['#node']->nid, array('absolute' => TRUE)); ?>

My problem now is, that if the user is not logged in, that link only brings him to the login site, where he is then stucked.

What would I have to do or what function would help me to somehow provide a link that redirects the not logged in user to the proper aim after logging in, and which would not affect the already logged in user?

You can add a additional destination parameter to the function.

<?php
print l(t('Title'), 'url', array('query' => array('destination' => 'destination_url')))
?>

This will create :

Title

Hope it helps.


Dynamic link in nodes to hidden Quick Tabs tab How can I make an URL that points on the same page Quick Tabs TAB. It will be good if link works without reloading page.

In Drupal 7, you can achieve it by using jQuery

Without reloading page :
Just create a Dynamic link using ID attribute or some other attribute, by using these attribute just click the TAB using jQuery.
Dynamic link like

Link text OR

Link text OR

Link text

  jQuery("#dynamic_link_ID").click(function(e) {//OR by using other attribute
    e.preventDefault();//it will not redirect when link is clicked
    jQuery("#quicktabs-tab_ID").click();//OR use any selector as per you requirement
  });


Building a link with l() and t() I'm trying to build this:

Adopt NAME-OF-PET

the code I'm using:

$adopt_me_link_male = l(t("Adopt !name",
 array('!name' => $node->field_pet_name['und'][0]['safe_value']), array('context' => 'Male pet name')), 'node/163', array('query' => array('edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]=' => $node->field_pet_name['und'][0]['safe_value'])), array('attributes' => array('class' => array('btn', 'btn-primary', 'btn-xs'),),) );

The above code generates the link but I have two problems:

the link looks like this:

Adopt NAME-OF-PET
there's no css class applied to the anchor

Why the classes are not applied and the link looks so messy?

Thank you!

There is a bug in your URL snippet (syntax error), so I'm writing the code.

<?php
$adopt_me_link_male = l(
  t('Adopt @name',
    array('@name' => $node->field_pet_name['und'][0]['safe_value']), //t() function replacements array
    array('context' => 'Male pet name') //t() function options array. Not necessary in this case though.
    ),
  'node/163', // l() function - URL
  array(
    'query' => array(
      'edit[submitted][nameofthepet_webform_fieldset][webform_nume_animal_comp]' => $node->field_pet_name['und'][0]['safe_value'],
    ),
    'attributes' => array(
      'class' => array('btn', 'btn-primary', 'btn-xs'),
    ),
  )
);

?>

In this example, I changed !name to @name for the security (Read t() function documentation). Also, if you want to use HTML inside the anchor (say, an image), you have to pass 'html' => TRUE the last parameter array in the l() function (add it along with the attributes and query array keys).


Show block for pages of every content type but one; including the front page I've created a custom block, and I want to show it on every page including the front page, except for pages of one specific content type.

In block settings, under "Visibility Settings", there is a list of checkboxes for each content type.  If none are checked, the block shows on every page; but if any are checked, the block only appears on pages with the checked content type.  So I tried checking everything except the one content type I want to exclude.

Except that this also excludes the block from the front page.  It appears as though the front page doesn't have a content type you can choose to make the block show up.

Is there a way to get my block on the front page as well, while still excluding some content types from showing it?

The Context module is perfect for this task.

Download and enable the Context module and add a new context under Structure -> Context
Add a 'Path' condition and set it to <front> http://d.pr/i/x4R5
Add a 'Node type' condition and check every node type, except the one where you don't want your block to show http://d.pr/i/PSO4
Add a reaction called 'Blocks', on the right check the block you want to show when the first to conditions are met, and click 'Add+' next to the region where you want your block to show. http://d.pr/i/a3RG
Save the context and that's it

Also make sure to leave 'Require all conditions' unchecked so the context will activate if the first or second condition is met.


How to create a custom Twig Template for Menu Block I'm using a menu block to output a section of my main menu into a region so I can have a "In This Section" type of sub menu on every page.

Unfortunately, I can't find a way to pinpoint in menu.html.twig which rendition of "main_menu" I am working with.  (they both have the same "menu_name") I want to adjust the markup for the menu block, but not for my main menu.

A similar question was asked here:
Additional twig suggestions for menus in Drupal 8

I don't quite understand the suggested answer.  Is there some way I can extend some class to call a different Twig Template?  Is there some hook I'm missing?

Ok, I think I found the answer.  Kristian Kaa answers it on his blog here:
http://kristiankaa.dk/article/drupal8-region-specific-menu-theme-hook-suggestion

Basically you use 2 preprocess functions like so:

/**
 * Implements hook_preprocess_block().
 */
function mymodule_preprocess_block(&$variables) {
  $variables['content']['#attributes']['block'] =    $variables['attributes']['id'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mymodule_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  // Remove the block and replace dashes with underscores in the block ID to
  // use for the hook name.
  if (isset($variables['attributes']['block'])) {
    $hook = str_replace(array('block-', '-'), array('', '_'),    $variables['attributes']['block']);
    $suggestions[] = $variables['theme_hook_original'] . '__' . $hook;
  }
}

This will add the block ID as a new theme hook suggestion.  Many thanks to Kristian.


How can I make Drupal use token for summary instead of breaking at ? I'm using "Long text with summary" fields for some different content types.

Right now the summaries are rendered until the first -tag (the web site already contains ~5000 nodes) but I would like to use a token created by a module that I'm currently using for the meta description of each page.

How can I use a token to display a nodes summary in a standard taxonomy node listing?

Assuming you're using Drupal 7, you can change how the content type is displayed in 'manage display'. You need to make sure you are using the correct view mode (probably teaser) which can be selected in the top left. You can then set the format to 'Summary or trimmed' and adjust the trim length by clicking the cog button.


Why my hook_block_view doesn't work? I installed "Form block" and it creates blocks. I want change block title via my module, but it doesn't work.

I create module and set function with hook_block_view:

function zzz_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'user_register':
      global $user;
      // Don't display the form to logged in users or if registration is disabled
      if (!$user->uid && variable_get('user_register', 1)) {
        $block['content']['form'] = drupal_get_form('user_register_form');
        $block['subject'] = t('MY TITLE IS HERE');
      }
      return $block;
  }
}

What did I do wrong?

hook_block_view() is only invoked for the module that defines the block via hook_block_info().

To alter the content of a block provided by another module, use hook_block_view_alter() instead.


Display the Last saved date on articles I want to know how can i display the Last saved date and time of the article to the users. How can i do that ? since it doesn't appear on the Manage display fields ?

You can simply edit the view mode you're using, Default, Full or Teaser for example:

Download Display Suite and enable the "Display Suite" and "Display Suite UI" modules.
Go to admin/structure/types/manage/article/display/teaser where "article" is your content type and "teaser" is the view mode.
In the "Layout for article in teaser" fieldset, select the "One column" layout and click Save.

You will now see a lot more fields, provided by the Display Suite module. One of those fields is called Last modified.

Drag that field to the top, and you're done! No custom theming or coding required.

As a side-note: in views, the field you're looking for is called "Changed":


Add a Canvas Form Control in Drupal Custom Module Im currently developing a module and I have this code in html:

<canvas id="cnv" name="cnv" width="500" height="100"></canvas>

I want it to add in my page using form controls but when I scan through Form API Reference, there's no canvas form control available. How to make it possible in Drupal? Any idea?

The form api does not support every tag in HTML. For special cases use a form key of #markup to embed raw HTML. Scan the form APIs for that keyword for examples.


Change Add to cart button text in Drupal 7 I am using Drupal 7 and Ubercart 3. I want to change the text for the button "Add to cart", how can I achieve this?

Any help, thanks.

The string overrides module is handy for these kind of things.

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

  Features

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


How to embed view in basic page content? I want to embed a view in  content of type basic page in D8.
How to I do that. Insert View module is still not stable to be used in D8.

You might want to have a look at Paragraphs and some of the new Views Reference fields. You could then intersperse Views and content.

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

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


admin toolbar not showing sub-navi in Firefox any more First the admin toolbar worked perfectly fine in Mac-OS-FF – then suddenly the sub-navigation (the fly-out sub-pages) stopped showing – partly. The sub-navigation seems to be covered or cut off:

At that time I neither updated FF nor added/removed any browser-plugins or dp-modules. The same happened to three different dp7 installations simultaneously. I then updated FF – no change.

In chrome everything works fine.

Has anybody else witnessed similar behavior?
Any pointers / tips would be much appreciated.

It was a bug in the admin menu module. I think it was fixed in the latest stable version (if not in stable, then in dev). Try updating to the latest stable version of admin menu (currently 7.x-3.0-rc5).


Can the same entity type (bundle) have different fields in different instances? I have a question about adding fields to an entity I've defined in a drupal 7 module upgrading from d6 which has 4 types.  The modules get a list of fields from a 3rd party server and if the user enables them through the admin interface they are added to the node object as cck fields before the node gets saved.  Can I add fields to a bundle in a similar fashion using field_create_instance?  Is it okay if the same type entity has different fields in different cases, or does the field get added to every entity of that type once it's added?

There are different resources (think data coming from different servers with potentially different fields) each with the same 4 entity types, and different fields could be enabled for each resource.  I'm considering adding the fields which are enabled to the entity before it is saved.  Entity type 1 could have different fields selected for resource 1 and resource 2.  This is the first time I have used d7 entities which is why I'm asking how they work.

field_create_instance already adds a field instance to a bundle. You can't add fields to an entity type or an entity itself.

I'm not quite sure if I understood you right:

Guess 1:
You want for example two nodes of type person where one has a field phone number and the other one not, which is not possible. Your node type has to define all possible field types, but they may be optional, so if the external system doesn't provide data for it, simply leave it empty.

Guess 2:
You want to adjust a whole entity type (this means all existing entities) based on external systems, user input or whatever. Thats possible with the Field CRUD API.


Parameter upcasting in Forms: buildForm works, submitForm doesn't Route:

mymodule.applications.payment_form:
  path: '/payment/{submission}'
  defaults:
    _form: '\Drupal\mymodule\Form\PaymentForm'
    _title: 'Pay Fee'
  requirements:
    _role: 'applicant'
  options:
    parameters:
      submission:
        type: entity:webform_submission

This works:

public function buildForm( array $form, FormStateInterface $form_state, WebformSubmission $submission = NULL) {
    $submission_data = $submission->getData();

This doesn't (null):

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmission $submission = NULL) {
    $submission_data = $submission->getData();

Is it intentional that upcasting is only available to buildForm?
Is there a workaround?

(My logic being: the form, when submitted, still POSTs to /payment/123, so it's still convenient to load the object.)

Yes, this is intentational. submit and validate callbacks aren't tied to the request, they only receive exactly those two arguments.

As mentioned in the comments, you can store the information either on the object, with $form_state->get()/set() or a form elemnt of #type value, doesn't make a big difference which you chose.

You could also store only the ID instead of the whole object but actually, I believe it is stored anyway in form_state somewhere when you pass it as an argument to the form (pretty well hidden though, so better to store & access it in a more explicit place)


Rules to remove user from role on node publish I have tried the following:

Event: updating an existing content
condition: NOT node-unchanged published
remove user role (I'm stuck here)

The last item is my problem. There is no user reference in the data selector field, it just has site and node items and even the node items has nothing related to the node's field. It just has stuff like status, vid, uid, comments, nothing referring to the nodes field items.

What I think I need is to select Romove user role, I select the user from the data selector and then select the role it needs to be removed from.

DETAILS ON CONTENT TYPE
The content type provides field for two email addresses to be provided by the node author - the node status at this time is unpublished. The two emails are then used to create new user accounts (with notification to the email owners) which are added to specific roles (these are done with rules). The two new accounts are granted permission (via the field permission module) to provide values to corresponding fields in the same content type. When the two users update the node by providing the values, the admin changes the status of the node to published.

Once unpublished the two new users need to be removed from the respective roles, though they remain authenticated users.

Thank you for looking into this

I solved this with the rule on updating node and by setting the following  conditions:

that the current-user is not an admin nor the node author
that updated node status is published
that the corresponding form field is not empty

THen the action is set to remove user role of current-user from [desire_role]


When a user login fails, is it possible to say "Password incorrect" or "Username does not exist" instead of the default message? When a user types an incorrect user name or password, by default Drupal gives this message: "Sorry, unrecognized username or password."

To help my sometimes clueless users (and my clueless self), I'd like to provide more helpful messages to specify exactly what is wrong.

In other words:

Incorrect password= "The password you provided is incorrect."
Account does not exist= "No account is registered for USERNAME."

How could I go about doing this?

This message is set in user.module in the user_login_final_validate() function.  It's set as a bog-standard form_set_error() so can't really be over-ridden.  Looking at it, it also doesn't differentiate between whether or not the username or password is incorrect, so you wouldn't really be able to do anything useful.

As Clive mentioned, it's much better practice to keep a degree of ambiguity in certain error messages, and seeing as how this isn't wrapped in any kind of theme function and doesn't have separate behaviours for whether the username exists or password was incorrect, you're probably better off leaving it as is.

One last option you have is to user a hook_form_alter() on user_form to set an extra validation callback, and then check for the user name yourself.

Example:

(I can't remember the $form_state for the user form, so you'll have to die() or dpm() that yourself)

function mymodule_check_username_exists($form, &$form_state){
  $user_exists = user_load_by_name($form_state['name']);

  if ($user_exists == FALSE ) {
   form_set_error('name', t('This username does not exist'));
  }
}


How to get in Views RESTful API non latin's letters on fields? With this guide, I do my RESTful API view (through core modules: RESTful Web Services and Serialization). Ater go to API page, I get this JSON:

[{"title":"\u0411\u044b\u0441\u0442\u0440\u044b\u0439 \u0431\u044e\u0434\u0436\u0435\u0442\u043d\u044b\u0439 \u0424\u0440\u0438\u0437 \u041c\u0430\u0433 (Freeze Mage)"}]

All \u0xxx codes — it's non english/latin letters (Russian/Ukraine in UTF-8, for example).

How to correct (readable) display in JSON response?

The Drupal 8 Rest module relies on the Serialization module to create the JSON output. This module, in turn, is using the Serializer Symfony component, which outputs escaped characters by default (it is not passing the JSON_UNESCAPED_UNICODE constant to the json_encode call).

As far as I can see, the escaped UTF8 characters are fine (they are legal in JSON) and you should be able to parse it back to UTF8 from any REST client having a JSON decoder. They are just not very readable if you try to read the JSON directly.


Why can't I delete certain content types? I have a Drupal 7 site, and under the Content Types menu, only certain types have a 'delete' link under the 'Operations' column.

All of the content types have the links for 'edit', 'manage fields', and 'manage display', but only some have 'delete', while others don't.

I checked my permissions for my user, and I do have Administer content types -- but that appears to be one global permission for all content types, so I still don't understand why some are deletable while others aren't.

Why do only certain content types have a delete operation?

Delete them by going to the url /admin/structure/types/manage/content-machine-name/delete

content-machine-name being the machine name of the content type you want to delete. Also, make sure you use dashes in the machine name rather then underscores.


How to add pagination (pager) to field collection module? How to add pager to the content created by the Field collection module?

I tried to achieve it with the Views module but Views takes the whole field collection content as single item, so it is not feasible.

I tried the Smart Paging module, but smart pager is for breaking one single content in many, so it is also not applicable.

After trial and error, I found the perfect solution to provide Paging to the content created by Field Collection module. This can be done by Views module.

You need to create the View of the your content which you have created using the field collection.

Important Part: In the Views setting as described in the following snapshot in the section of Multiple Field Setting, you need to uncheck the Display all the values in the same row. Because by default it is checked so Views considers your entire content in single row, so pager of views considers it as only one item. But if you uncheck, your each field set considered as single row and so Pager of the Views module will calculate accordingly. Hence unchecking this setting in Views and providing pager in the Views module will solve the issue.

Hope this will help others.


Logging into Drupal from an external application I am currently using the services module and some custom code to delete, login and edit drupal users from an external application. I can currently login as a user on the external application but I am only logged on in the code and not the actual browser. Meaning that I can perform actions with the authenticated account in the code but when I visit my drupal website through the browser, I am not logged in. I want my users to be logged into drupal when they log into my external application. How can I do this?

You can use the form API to write a custom function for validating authentication. Something like this (this is from Drupal 7, but for 6 you have the same logic and the API is not very different). The code here is from a module I've wrote to authenticate users from an IP.Board (a forum software) database:

<?php
/**
 * @file
 * Allow Drupal 7 to use IP.Board members table for authentication
 *
 * Some code is based on this nice tutorial http://www.touchnoc.com/node/86
 */

/**
 * Alter the user login block form
 */
function ipbridge_form_user_login_block_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Alter the user login page
 */
function ipbridge_form_user_login_alter(&$form, &$form_state) {
  _ipbridge_user_login_form_alter($form, $form_state);
}

/**
 * Change the validate callback
 */
function _ipbridge_user_login_form_alter(&$form, &$form_state) {
  $k = array_search('user_login_authenticate_validate', $form['#validate']);
  $form['#validate'][$k] = 'ipbridge_authenticate_validate';
}

/**
 * Custom validation
 */
function ipbridge_authenticate_validate($form, &$form_state) {

  // try normal validation first
  user_login_authenticate_validate($form, $form_state);
  if ($form_state['uid'] !== FALSE)
    return;

  // still here? Try to find the user in IP.Board
  $name = $form_state['values']['name'];
  $pass = $form_state['values']['pass'];

  $records = db_select('ibf_members', 'u', array('target' => 'ipb'))
  ->fields('u', array('member_id', 'name', 'members_pass_hash', 'members_pass_salt', 'email'))
  ->condition('u.name', $name, '=')
  ->execute();

  if ($records->rowCount() == 1) {

    $ipbUser = $records->fetchObject();

    // this is how IPB generates the pasword hash
    $hash = md5(md5($ipbUser->members_pass_salt) . md5($pass));

    if ($hash == $ipbUser->members_pass_hash) {

      // based on Drupal's user_external_login_register (that function doesn't set the email address)
      $account = user_external_load($name);
      if (!$account) {

        $userinfo = array(
          'name' => $name,
          'mail' => $ipbUser->email,
          'pass' => user_password(),
          'init' => $name,
          'status' => 1,
          'access' => REQUEST_TIME,
        );

        try {
          $account = user_save(drupal_anonymous_user(), $userinfo);
        } catch (Exception $e) {
          drupal_set_message(t('Are you trying to login using an IP.Board username that was previously registered in Drupal? Caught exception: ' . $e->getMessage()), 'error');
        }

        if (!$account) {
          drupal_set_message(t("Error saving IPB account."), 'error');
          $form_state['uid'] = FALSE;
          return;
        }
        user_set_authmaps($account, array("authname_ipbridge" => $name));
      }

      $form_state['uid'] = $account->uid;
    }
  }
}
?>


How to print token in webform-confirmation.html.twig? I would like to output a submitted value as a token on the confirmation page through the twig. The token works just fine when added into the message box of webform as:
[webform_submission:values:score_percentage]

But I can't seem to get the same value to output through the twig. I have tried:
{{ webform_token('webform_submission:values:score_percentage') }}
{{ webform_token('[webform_submission:values:score_percentage]') }}
{{ drupal_token('webform_submission:values:score_percentage') }}
{{ drupal_token('[webform_submission:values:score_percentage]') }}

But they all just print the token itself, like:
webform_submission:values:score_percentage
[webform_submission:values:score_percentage]
[webform_submission:values:score_percentage]
[[webform_submission:values:score_percentage]]

I saw another post about (what I think is) the same thing here? But I haven't been able to see my error...
As well as this old issue, which by the looks of it would be fixed now.
I have the latest versions of Twig Tweak (8.x-2.9) and Token (8.x-1.9) installed. Am I doing something fundamentally wrong here?

First, talking about your twig extension:

{{ webform_token(....) }}
{{ drupal_token(....) }}

I've never seen drupal_token twig ext so let it out of here. or you guys can comment to help me update this answer.
For webform_token function, the real back end function of it you can check from this file: webform/src/Twig/WebformTwigExtension.php line 102. (v5.23.0). And it said that
public function webformToken($token, EntityInterface $entity = NULL....) {
  // Allow the webform_token function to be tested during validation without
  // a valid entity.
  if (!$entity) {
    return $token;
  }
  ...bla...bla
}

Mean that, if your code not given entity, it will return a string that you inputed. and the result will be like what you did.

Back to your case
If you look into webform/templates/webform-confirmation.html.twig template file, you can see the Available variables:

progress: Progress bar.
message: Confirmation message.
back_url: URL to the previous webform submission.

And the others Available variables can found at template_preprocess_webform_confirmation() of this file: webform/includes/webform.theme.template.inc. And they are

webform,
webform_submission,
source_entity.

So, it mean that you can use {{ webform_submission.data.field_name }} in webform-confirmation.html.twig template file; instead of using token like the way you did above.
*Note: Try to avoid using twig extension in twig template would make you easier in debugging and maintenance.


Display count of nodes from the parent terms of a taxonomy where dummy nodes are based on the child terms of the parent terms of taxonomy 'State' is the vocabulary of my taxonomy where North, South, East & West are parent terms with child terms like Montana, Texas, New York, Washington respectively which are states of USA.

I've created some dummy nodes on based of the child terms from taxonomy, is there any way to display the count of nodes from the parent terms of that taxonomy, so that the result would be something like North 10, South 5 and so on

Try creating a Taxonomy View with the following settings.

field: taxonomy term/id
filter: taxonomy vocabulary; states vocabulary
contextual filter: taxonomy term parent; display summary, show link w/ count, set a base url for link

I have done something similar with a contextual filter of Taxonomy Term/ID and it works fine.  Should work with Term Parent.  you might have to add a relationship to content as well, not too sure but that should get you started.  Good luck!


Render fields in node template with different view mode I have some fields for nodes. I hide the content and render fields separately as below.

hide($content);
print render($content['field_01']);
print render($content['field_02']);
print render($content['field_03']);
print render($content['field_04']);
print render($content['field_05']);

I set different field formats in content type at Manage Display" like field_01 is an image and i set large image in Full Content and Thumb image in Teaser view mode. field_02 is a taxonomy reference field which i set Link in Full Content and Plain Text in Teaser view mode.

When i render fields in node template, all fields render as view mode "Full".
Now i want render all fields from default view mode "Full". Only I want to render field_01 & field_02 from Teaser view mode.

Let me give you an example. I have one date field into my content type. Now I want to render that field twice. For getting that that i will print the output as Birthdate : Feb 22, 2006 for first instance and for second I want to print Age : 7 yrs old. In manage display I have format
   to date as well as Time ago and I want to use both format.

The easiest way to do this would be to create a second variable in your theme_preprocess_node() function, pull out the value that you want to format a second time, format it differently, and then print the variable where you want to see it a second time in your template.  Dates are particularly easy to format using the format_date() function, so you don't need to use a different views mode to achieve this.

In your theme's template.php file add something like;

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node']; // Nice shorthand.
  $lang = $node->language; // Shorthand again.
  $variables['new_date'] = format_date($node->field_date[$lang][0], 'medium');
}

Then in your node--whatever.tpl.php file print it out like;

<?php print $new_date; ?>


How do you add captions to each image of Flexslider? (already tried Google!) First of all, I tried to search the answer in Google, there weren't many results and those who were weren't very informative, clear, stepped, or guiding. I've also checked Youtube, and I found something that seem too general and too long for this purpose.

What I look for is the simplest way to add overlay captions to Flexslider images. The captions should be different per image and I need these captions to contain both a headline and a body texts (That's why I've guessed that the image title field won't be enough by itself and that the solution should come from another place).

Please give me some guidance, for example, where do I even start to get this, what is the logical place to put the text in per image? (I guess it wouldn't be CSS content), what are the ways to do it, etc... And I hope that your good and didactic guidance will endure for all users to come.

Well, after investigating for a short solution, and one that involves the minimal number of modules, it seems that as of 2/1/2015 there are 2 main ways to give per-images captions, to the images of the slider. It's good to Install Flexslider and creating a working slider-View of images, and right afterwards, implement one of these ways below.

The first way:

Install the module Image Field Caption. It's install is simple but you might have to do about 10 minutes of CSS:

After you have installed the module your images will now have (besides the potential ALT\Title attributes) a third attribute named Caption. You can easily edit it and it can also integrate with CKeditor.

After you have printed the captions you could add some CSS. as of 2/1/2015, the captions appear naturally under the picture, but if you want it to be over the picture (not above, but flying over, in it's bottom for example) with some nice transparent background, just edit the CSS property "Blockquoute" and make sure you give it:

"Position: Absolute; right: 0; left: 0; bottom: 0; rgba(#,#,#,0.#); width: #%; height: auto;. The rest is rather simple...

The second way:

2 CSS guys I spoke seem to would have preferred this option, though bear in mind that it contains 2 modules instead of 1, in the first solution:

Make the images of the Slider appear as CSS backgrounds. This could be achieved via the module CSS Injector. After the images been presented as backgrounds, a way must be found to print a caption attribute below or on the Image. one way to print it is via the module mentioned above - Image Field Caption. The other is to print the image's very own Title attribute via the module image caption formatter.

All luck, Ben.


Drush Make removes .git folders After a silly feeling with drush make and github I found out that all the .git folders (used by git to record history, config, origin location etc ) were removed by drush make and I have heard about this before but didn't come across myself as I was not maintaining the make files.

Specifically drush make removes the .git folder and u can see that if u run it with --debug option

Executing: rm -rf '/tmp/drush_make_tmp_1305733094/__git__/__build__/.git'

In my make file I am fetching 4 things from git repo because I wish to track development on them, 2 of them are my custom components ( 1 custom module and 1 feature which records all the config) and the other drupal core and media module due to high volume of fixes they receive. The whole purpose seems defeated if I can't have respective .git folders but I am also sure there is a way as others are using drush make with git but couldn't find in my quick search.

Thanks for your time!

Pass the "--working-copy" switch to Drush Make.

drush make --working-copy site.make


how to alter block subject html tag? I am trying to change the <h2> tags that block.tpl.php uses to wrap <?php print $block->subject ?> to <h3> tags so that I can target them with jQuery UI Accordion. I've got the following code:

<?php
    function MYTHEME_block_view_alter(&$data, $block) {
        if($block->module == 'block' && $block->region == 'sidebar') {
            $data['subject']['#tag'] = 'h3';
        }
    }
?>

This doesn't work...I assume I'm screwing up the reference to the render element. Does $data['subject'] contain an array where the HTML tag is stored? What is the correct way to target it?

Alternatively, should I look for a way to re-write block markup so that, in the sidebar region, it renders only the <h3> and <div> required by jQuery UI Accordion? Unless there's a fantastic module for turning blocks into Accordion-ready HTML already out there, I'd rather not install another module.

Many thanks for any help!

You can override the block template for a particular block and can modify the html for block subject.

You can check theme suggestions for more reference.


PDF version is different from Printer frendly version - using dompdf Using the Print module, I managed to get dompdf working to some degree.
However, there are differences between the 'printer friendly version' and the 'PDF version' generated, specifically with regard to rotated text.
My concern is specifically about the rotated text, which rotation works for both printer version and PDF versions, but the PDF version has not positioned the text in the right place.
See below the differences:

When looking at the Printer friendly version's HTML, I see this:

I thought it might have to do with the float: I edited the dompdf_config.inc.php file:
def("DOMPDF_ENABLE_CSS_FLOAT", true);
However, that did make no difference in the output.

Instead of using that module, I prefer to use PrintFriendly where you don't need to install additional scripts. And it's customizable too.


Anyway to clone the shipping services at: admin/commerce/config/shipping Is there any way to clone Flat Rates shipping services at: 'admin/commerce/config/shipping' ?

The Flat Rates are generated by these modules: commerce_shipping
and commerce_flat_rate

I need this because I need to create 50 shipping services (for the 50 Spain provinces/states).

I would do this programmatically. As you will need this to be done only once, you can just run this from devel/php or in a custom module.

Zones are just there as an example; prepare an array with two letter zone codes / some other identifier and run the same code:

$zones = range(2, 10);
foreach ($zones as $zone) {
  $shipping_service = array(
    'name'            => 'flat_rate_for_zone_' . $zone,
    'title'           => 'Title for zone ' . $zone,
    'display_title'   => 'Display title for zone ' . $zone,
    'description'     => 'Description for zone ' . $zone,
    'rules_component' => TRUE,
    'data'            => array(),
    'is_new'          => TRUE,
    'amount'          => 900,
    'currency_code'   => commerce_default_currency(),
  );
  commerce_flat_rate_service_save($shipping_service);
}

Hope this helps.


How to add content of nested terms to Taxonomy term View By default Drupal 8 taxonomy view doesn't show the nodes of child taxonomy terms. I need to include them but don't know to to modify the view Taxonomy term (Content).

I have the following vocabulary:

- Europe
  - Portugal
    - Lisbon
    - Porto
  - Spain
    - Barcelona
    - Madrid

Showing all the content related to cities works fine (for example Barcelona). But now I want to show a list of content for countries (for example Spain) which should include content tagged as city (Barcelona and Madrid). And the same with continents, a list for Europe should include content tagged as Lisbon, Porto, Barcelona, Madrid, etc.

Finally found the answer and it is almost the same than for D7:

Edit the existing view Taxonomy Term (admin/structure/views/view/taxonomy_term/edit)
In Advanced, add the field Content: Has taxonomy term ID (with depth) using all the settings from already added Content: Has taxonomy term ID using the same settings. You can limit the depth by setting the depth parameter.
Remove old field Content: Has taxonomy term ID using the same settings
Set Use aggregation to yes to avoid duplicates


Profile2 and profile fields by user role I have some profile fields created with the Profile2 module, which creates a main profile containing all the fields.
In the user/%/edit/main path, I see a new tab which displays a form to edit profile fields.

I have also three user roles, ( e.g. role A, B and C), and I want to remove that menu path for the role C. Alternatively, I want to restrict the access to those profile fields by user role.

Can I use the module Profile2 Privacy to achieve the goal?

I've done with hook_process_page() and removed the variable secondary_local_tasks before rendering to the template if the logged-in user is role C. No need additional module.

function mymodule_process_page(&$vars, $hooks){
    global $user;
    if(array_key_exists(6, $user->roles) && arg(0) == 'user' && arg(2) == 'edit'){
        # if user role C, hide profile tab
        $vars['tabs']['#secondary'] = array();
        if(isset($vars['secondary_local_tasks'])){
            $vars['secondary_local_tasks'] = array();
        }
    }
}

I have also tried this from hook_preprocess_page(), but it did not work on the sky theme.
Related question is here : Menu local tasks and hook preprocess


Connect two webforms? I have 2 webforms: survey webform and task webform.
The entry point is task webform and it requires user to login.
There is a controller or something to check if user has previously filled in a survey webform, if he/she did, go straight to task webform. Otherwise, need to go to survey form.
I know how to create webforms, but not sure how to make such controller.

I am not sure about your control here, whether to move from survey webform to task webform or the vice versa. But this is what I would do.,

On login query the "webform_submissions" table with the logged in user's id and see whether he/she has submitted the webform before.
If he/she has not submitted it before load the webform say task webform.
If he has submitted this before, load the survey webform page.

You can make use of "hook_user_login" to redirect on login, also this can be used to query the "webform_submissions" table.


How do I restrict the date popup to 12 months from start date? I have a custom module where I set two date pop-ups.

$form['set_start_date'] = array(
  '#type' => 'date',
  '#title' => t('set start date'),
  '#required' => TRUE,
);

$form['set_end_date'] = array(
  '#type' => 'date',
  '#title' => t('set end date'),
  '#required' => TRUE,
);

If I select 2017-04-12 as start date, the accepted end date should not be after 2018-04-12.

How can I achieve this?

Following Method i used to restrict the date Pop-up to 12 months

$form['set_start_date'] = [
      '#title' => $this->t('START DATE '),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

 $form['set_end_date'] = [
      '#title' => $this->t('END DATE'),
      '#type' => 'date',
      '#attributes' => array('type'=> 'date', 'min'=> '-12 months', 'max' => 'now' ),
      '#date_date_format' => 'd/m/Y',
    ];

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

 return $form;
}


How do I theme (add extra markup to) menu links in Drupal 7? I have a secondary menu that displays like:

PAGE

...

I would like to change that so it displays a  on the links like:

PAGE

...

According to the Drupal 7 theme_menu_link documentation and this answer on theming Drupal 7 menu links, I should just be able to declare a hook like THEMENAME_menu_link__MENUNAME($variables).

I've declared the following two functions in my template.php, but neither of them is being called:

function MYTEMPLATE_menu_link__system_secondary_menu(array $variables) {die;}
function MYTEMPLATE_menu_link__secondary_menu(array $variables) {die;}

I'm using Framework, and there's a section like:

if (isset($vars['secondary_menu'])) {
    $vars['secondary_menu'] = theme('links__system_secondary_menu', array(
        'links' => $vars['secondary_menu'],
        'attributes' => array(
        'class' => array('secondaryNavigation'),
    )
    ));
}

What's the cleanest / best practice-y way of printing an extra  in the menu links for this menu only?

I can write a function to theme the entire menu at once with function MYTEMPLATE_links__system_secondary_menu(array $variables), but theming the entire menu  just to get a  in each link seems like overkill.

It calls theme('links__system_secondary_menu'). By default, there is no theme_links__system_secondary_menu, so I guess it is calling theme_links. Looking at the function, all you have to do is copy it to your theme as THEMENAME_links__system_secondary_menu, then change the call to l() to something like:

$link['html'] = TRUE;
$output .= l('' . $link['title'] . '', $link['href'], $link);

The html => true is required or l() will strip the html out of its first parameter.


How can I create a new field with a line break in it? I created a few fields which always stick together with no free space at all.
Then I created a new field between them which I named linebrake, chose the "long text and summary" (which is the only type where I can add html-code) and wrote
 (

 doesn't work) and now I have like 3 line breaks at once.

Is there any way to get only 1 line break?

Thanks in advance

Maybe the "p" tag doesn't work, because has been escaped and the Text format chosen is "Filtered HTML", see the "Allowed HTML tags" below to be sure that the "p" tag is allow.

Choose "Full HTML" for not escape.

Greetings.


How do I attach new images to a node? Will try to be brief.

I have a node with "n" images asigned to it, now i want to add new images (and keep the currents) to the node, i've  tried this but no success until now. The next code does nothing:

$node = Node::load($node_id);
$node->field_car_picture[] = $new_images;
$node->save();

Also tried this and removes the current pictures and leave only the new images:

$node = Node::load($node_id);
$node->field_car_picture->setValue($new_images);
$node->save();

Any help will be appreciated

You can try to merge the existing field items array and the new one, but I would use a loop to add one image at a time:

$node = Node::load($node_id);
foreach ($new_images as $new_image) {
  $node->field_car_picture[] = $new_image;
}
$node->save();

If you want to merge the arrays get the existing one

$existing_images = $node->field_car_picture->getValue();

combine it with the new array and replace the fields content with it.


In which file to add the cache_clear_all function In my situation I would like a certain block on my page with real time information to not be cached for anonymous users. Literature listed below:

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

https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
suggests using the

cache_clear_all('modulename', 'cache')

I added this on my module inside the hook_block_view() function. This does not work though. Any directions on where I can use this function.
Here is the function information:
Clearing specific entries in cache tables
The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code.
cache_clear_all('content:' . $MYNID, 'cache_content', TRUE);

The example above clears all items from cache that start with 'content:$MYNID*'. To ONLY remove one specific row, drop the $wildcard parameter (the "TRUE" statement in the function call) and change the format of the first parameter to omit the asterisk, which functions as a wildcard.
cache_clear_all('content:' . $MYNID . ':' . $MYNID, 'cache_content');

You can set the block's caching in hook_block_info, like so:

function MODULE_block_info()
{
    $blocks = array();

    $blocks["BLOCK_NAME"] = array(
        "info"  => "BLOCK TITLE",
        "cache" => DRUPAL_NO_CACHE,
    );

    return $blocks;
}


Different slide intervals for Views Slideshow I've created a slideshow using Views Slideshow and the Cycle plugin. In the Slideshow settings, there are advanced transition options that allow you to set the timer delay between slides. The project I'm working on requires that the delay between slides be different for each slide, so I need a way to do something like this:

Slide 1: 3000 ms
Slide 2: 5000 ms
Slide 3: 10000 ms

I have searched and cannot find a way to accomplish this easily. Is there something I'm missing, or would this require a custom module?

You might be able to override the defaults with something like this:

$('.views-slideshow-cycle-main-frame').each(function(index) {
  var timer = 3000;
  if (index == 1) timer = 5000;
  if (index == 2) timer = 10000;
  $(this).cycle({
    timeout : timer
  });
});

This goes in an external js file or using drupal_add_js().


Beginner trying to use jQuery in a custom location, but not sure where to insert the code At the moment, I'm working on a website that requires an on-mouse over effect where the things that are going to be displayed is an image. I figure that the best way to go about this is by using jQuery.

Being a beginner at Drupal, I've noticed that all of the content in this website is generated from database calls. I was wondering if there was a module or a way to see how these calls are made so that I may be insert the correct code at the right place.

If you are customising a theme, I would add a custom jquery script you have written. In your themes template.php you can then simply call the .js file from within the theme folder.

For example you could add this to your template.php file:

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/jquery.custom.js');

in the jquery.custom.js file you could have something like this:

(function($) {

 $(document).ready(function() {

  // hover effect
  $(".hover_effect").hover(function() {
    //add effects here
  }

 });

}(jQuery));


How to add classes to a specific bean w/ display suite template On the website home page that I'm working on, we have 4 call-to-actions.

Below is the DS template file which is used when rendering each of them:

<?php

/**
* @file
* Display Suite 2 column template.
*/
?>

<<?php print $layout_wrapper; print $layout_attributes; ?> class="ds-2col <?php print $classes;?> cta-body clearfix" style="background: #<?php print $field_bg_colour[0]['value'] ?>">

<?php if (isset($title_suffix['contextual_links'])): ?>
<?php print render($title_suffix['contextual_links']); ?>
<?php endif; ?>

<?php if (isset($field_more_link)): ?>
  <a href="<?php print $field_more_link[0]['url']; ?>">
<?php endif; ?>

  <<?php print $left_wrapper ?> class="group-left<?php print $left_classes; ?>">
    <?php print $left; ?>
  </<?php print $left_wrapper ?>>

  <<?php print $right_wrapper ?> class="group-right<?php print $right_classes; ?>">

<?php print $title ?>

      <?php print $right; ?>

  </<?php print $right_wrapper ?>>

<?php if (isset($field_more_link)): ?>

<?php endif; ?>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

Currently I'm adding a margin-right to each of these, but would like to remove the margin-right on the even number call-to-actions - so my layout works.

Is there any way I can add an odd/even zebra class or a better way to do this?

Many thanks

A friend helped me solve this one. All I needed was the following PHP as a container class.

<?php print $zebra; ?>

I can now style the .odd containers!

Thanks all


Use contextual filter value in a view's header "rendered entity" I want to render a Taxonomy term in a Header for a Page view which uses the Taxonomy term as a Contextual filter. I found that I can add an Entity: Rendered entity to the Header of a View, which I can set to display a Taxonomy term, but it needs an Entity ID, and I don't know how to reference the Contextual filter value.

I suppose I can use a Global: PHP or Global: View in the header to achieve this otherwise, but I wanted to know whether I can use the Rendered entity to do this.

It looks like this isn't currently possible. There's a feature request on d.o to make this work. You can achieve it with Views PHP as you mentioned by using the following code:

<?php
$entity_type = 'taxonomy_term';
$id_arg = 1;
$view_mode = 'full';

if ($entity_id = $view->args[$id_arg - 1]) {
  $entity = entity_metadata_wrapper($entity_type, $entity_id);

  // Rendering without title ($page = TRUE).
  $render = $entity->view($view_mode, NULL, TRUE);

  // You may need to unset the title, even when rendering without it.
  $render[$entity_type][$entity_id]['#term']->name = NULL;
  print drupal_render($render);
}
?>

Note: this code requires the entity module. Shouldn't be hard to port it to native Drupal code, but entity is rather widespread.


How to import Profile2 users with taxonomy terms using Feeds? I need to migrate a user-database into a new drupal system that uses Profile2 user profiles. The Drupal user profile contains fields like "gender", which are Term references (field type). This reference points to a Vocabulary, in which the genders are stored. Now I have a CSV file containing all users from the old database, and a Feeds importer. The importer is setup straight forward and all "value"-fields (surname, lastname, etc.) are working, but the term reference fields are not filled. How do I setup the importer correctly?

I tried to use the gender name (male/female) and even tried the respective term-IDs (tid). The first try results in an error message (wrong input format something), the second one does not produce error outputs but leaves the term reference fields blank as well. I also tried the "Entity Field Query finder" tamper plugin, but without success.

Am I missing something? Or is this import to complex for the Feeds plugin?

In the feeds reference importer>mapping click the button under "Search taxonomy terms by: Term name" on the term reference mapping you're wishing to search and click the check box, then save.


Modules installed with Composer placed in wrong directory I'm trying to install modules via Composer. I've set up my composer.json file according to Drupal.org's direction. However, the installed modules are being placed inside of vendor/drupal/. I'm new to Drupal 8, so I wouldn't be surprised if this is a result of a simple mistake. I'll include my composer.json file below:

{
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },
    "require": {
        "drupal/admin_toolbar": "^1.19"
    },
    "extra": {
        "installer-paths": {
            "core": ["type:drupal-core"],
            "libraries/{$name}": ["type:drupal-library"],
            "modules/contrib/{$name}": ["type:drupal-module"],
            "profiles/contrib/{$name}": ["type:drupal-profile"],
            "themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/{$name}": ["type:drupal-drush"],
            "modules/custom/{$name}": ["type:drupal-custom-module"],
            "themes/custom/{$name}": ["type:drupal-custom-theme"]
        }
    }
}

As per what Ivan Jeros said, if you add "composer/installers": "^1.2" to your "require" array, it will add a composer extention that maps to the directories you added:

"require": {
        "composer/installers": "^1.2",

Otherwise, it puts everything in /vender/drupal


Putting subsites outside of the sites directory When number of subsites increase, is there a way to put subsites in a directory outside of sites directory or even outside of drupal base directory, like /var ?

Are symlinks the only solution?

The location of subsites is hard-wired in function conf_path().


Add counter to view with rendered entity output On my site I've a search based on Views, with an exposed filter. The style output is "rendered entity", and I've to add the "result counter" beside the title.

Is there a way to do this or I've to use "fields" output?

I should have something like:

  Title1
  Title2

Result number is a views field node has no clue about. You need to use "fields" output to add fields that are not in the node itself - that's the very reason of this output's existence.


How to create nodes using node_save? I'm trying to migrate my current html site into Drupal. I have over 80,000 pages I have to migrate so I thought instead of sitting in front of a computer for 50 years I would create a module. I was able to create a script that extracts the html from each directory and now I got to a road block where I need to create a node. I'm trying to create a new node using node_save(), but when node_save is executed, I get a PDOException error with everything I try. I'm passing in $node, which is an array which is then casted into an object.

  PDOException: in field_sql_storage_field_storage_write() (line 424 of /srv/www/htdocs/modules/field/modules/field_sql_storage/field_sql_storage.module).

This is how we are currently creating the node, but it produces an error:

$node= array(
    'uid' => $user->uid,
    'name' => $user->name,
    'type' => 'page',
    'language' => LANGUAGE_NONE,
    'title' => $html['title'],
    'status' => 1,
    'promote' => 0,
    'sticky' => 0,
    'created' => (int)REQUEST_TIME,
    'revision' => 0,
    'comment' => '1',
    'menu' => array(
        'enabled' => 0,
        'mlid' => 0,
        'module' => 'menu',
        'hidden' => 0,
        'has_children' => 0,
        'customized' => 0,
        'options' => array(),
        'expanded' => 0,
        'parent_depth_limit' => 8,
        'link_title' => '',
        'description' => '',
        'parent' => 'main-menu:0',
        'weight' => '0',
        'plid' => '0',
        'menu_name' => 'main-menu',
    ),
    'path' => array(
        'alias' => '',
        'pid' => null,
        'source' => null,
        'language' => LANGUAGE_NONE,
        'pathauto' => 1,
    ),
    'nid' => null,
    'vid' => null,
    'changed' => '',
    'additional_settings__active_tab' => 'edit-menu',
    'log' => '',
    'date' => '',
    'submit' => 'Save',
    'preview' => 'Preview',
    'private' => 0,
    'op' => 'Save',
    'body' => array(LANGUAGE_NONE => array(
        array(
            'value' => $html['html'],
            'summary' => $link,
            'format' => 'full_html',
        ),
    )),
        'validated' => true,
);

node_save((object)$node);

// Small hack to link revisions to our test user.
db_update('node_revision')
    ->fields(array('uid' => $node->uid))
    ->condition('vid', $node->vid)
    ->execute();

Instead of casting an array into a stdClass object, you could try creating a new stdClass() object and then using node_object_prepare() to prepare the object for creating a new node and then finally manually changing the values of uid, name, title, language, body, etc. Also, be sure to use node_submit() before saving the new node to the database.

Example: http://drupal.org/node/1173136


How do I recalculate the price based on a given address? I have a basic commerce shop setup and I need to recalculate the price based on the delivery region within the country.

The first approach I tried was to add a list field for the customer profile type and defined various regions. The idea was to recalculate the price based on the selected region and the current total price with the price resolver, the problem was I couldn't access the custom added field value, after the information had been entered in the order information form.

I should note that all purchases would be make by guest accounts.

Is it possible to access this information that way?

I'm currently looking at the shipping module but it seems it doesn't really support this approach because it's more oriented towards characteristics such as weight and dimensions.

Any advice on how to tackle this issue?

I'm using Drupal 8.

Price resolver might be the thing you need. Here's the example: https://www.drupal.org/project/commerce/issues/2931445#comment-12391622


qTips and removing inline styles Okay, I am using the qTip (Stylish jQuery Tooltips) module to add tooltips to my page that has been laid out using inline styles (due to a consistency across browsers issue with the original theme css).

Question:  Is there a way to apply complex html inside of qtips tooltips?

I tried inserting HTML and destroyed my page, with just text qtips works perfectly.

Okay for the noobies looking for tooltips like me...  The documentation for qTip (Stylish jQuery Tooltips) is a bit misleading and on first read you might think that must implement the tooltip via input filter.  While implementing via input filter is "quick & dirty", it doesn't allow you to enter any html in the tooltip and also inside your wysiwyg editor you see the tooltip text displayed in the textarea, which destroys the W-Y-S-I-W-Y_G experience.

From the project page if you want to see demos, you are taken to the qTip2 plugin page, which shows great demos, which are programmatically implemented are 100% NOT useful to implement qtip styled tooltips on your page.  You can implement programmtically, but then you have to CSS style the tip on your own.

My Solution:

1.) Install the qTip (Stylish jQuery Tooltips) and create an instance (style) of tooltip that you want to use.

2.)After you save your style, you will be taken back to landing page of the module, which lists the qtip instances (styles) that you have saved.

3.) right-click on this page and select "view-source". In the source code of the page find the name of your saved qtip instance (for example, "test_tip_top_left"). It should look something like this:

Sample textThis is an example of how this qTip instance will look and function throughout the website.

4.) attach the class="qtip-link" attribute to your desired page element, then immediately following the element add a div with the attributes class="qtip-tooltip" data-qtip-instance="test_tip_top_left" and add your desired html content inside the div.

5.) Via theme's style.css (assuming it is used inside your wysiwyg content editing area), create a style to hide the display of the div containing your html tooltip content (if you don't, your tooltip will work, however in your wysiwyg editor the div html tooltip content will be displayed again destroying the WYSIWYG experience), something like:

.qtip-tooltip { display: none; }

6.) Attach the tooltip to an element in your page:

Text Users See
HTML Contentinserted here

7.) BANG - cool tooltip ;-)


Composer keeps overwriting .htaccess (and other files) every time I do anything Every time I try to update anything using Composer, it overwrites a load of files. One of the files it overwrites is .htaccess, which I have customised, so I have to keep patching it all the time. Here's an example (below) of it doing this even when package I asked to update didn't need updating. I'm guessing it's because I used the "drupal/core-composer-scaffold" package to create the site. I did that because I was following these instructions: https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#composer-from-scratch.

What am I doing wrong, to make it keep scaffolding (if that's the word for it) repeatedly? Thanks.

~/sites/default$ composer update drupal/security_review
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package academicpuma/citeproc-php is abandoned, you should avoid using it. Use seboettg/citeproc-php instead.
Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.
Package technosophos/LibRIS is abandoned, you should avoid using it. No replacement was suggested.
Package zendframework/zend-diactoros is abandoned, you should avoid using it. Use laminas/laminas-diactoros instead.
Package zendframework/zend-escaper is abandoned, you should avoid using it. Use laminas/laminas-escaper instead.
Package zendframework/zend-feed is abandoned, you should avoid using it. Use laminas/laminas-feed instead.
Package zendframework/zend-stdlib is abandoned, you should avoid using it. Use laminas/laminas-stdlib instead.
Writing lock file
Generating autoload files
Scaffolding files for drupal/core:
  - Copy [project-root]/.editorconfig from assets/scaffold/files/editorconfig
  - Copy [project-root]/.gitattributes from assets/scaffold/files/gitattributes
  - Copy [web-root]/.csslintrc from assets/scaffold/files/csslintrc
  - Copy [web-root]/.eslintignore from assets/scaffold/files/eslintignore
  - Copy [web-root]/.eslintrc.json from assets/scaffold/files/eslintrc.json
  - Copy [web-root]/.ht.router.php from assets/scaffold/files/ht.router.php
  - Copy [web-root]/.htaccess from assets/scaffold/files/htaccess
  - Copy [web-root]/example.gitignore from assets/scaffold/files/example.gitignore
  - Copy [web-root]/index.php from assets/scaffold/files/index.php
  - Copy [web-root]/INSTALL.txt from assets/scaffold/files/drupal.INSTALL.txt
  - Copy [web-root]/README.txt from assets/scaffold/files/drupal.README.txt
  - Copy [web-root]/robots.txt from assets/scaffold/files/robots.txt
  - Copy [web-root]/update.php from assets/scaffold/files/update.php
  - Copy [web-root]/web.config from assets/scaffold/files/web.config
  - Copy [web-root]/sites/README.txt from assets/scaffold/files/sites.README.txt
  - Copy [web-root]/sites/development.services.yml from assets/scaffold/files/development.services.yml
  - Copy [web-root]/sites/example.settings.local.php from assets/scaffold/files/example.settings.local.php
  - Copy [web-root]/sites/example.sites.php from assets/scaffold/files/example.sites.php

That's Drupal's Composer Scaffold. Listed as "drupal/core-composer-scaffold": "^8.8.0" or a different version in your project's composer.json file.

To prevent certain scaffold files from being overwritten every time you run a Composer command you need to specify them one by one in the "extra" section of your project's composer.json. See the docs on Excluding scaffold files.

The following snippet prevents the .htaccess and the development.services.yml from being overwritten.

"drupal-scaffold": {
    "locations": {
        "web-root": "web/"
    },
    "file-mapping": {
        "[web-root]/.htaccess": false,
        "[web-root]/sites/development.services.yml": false
    }
},

But maybe you want to ensure you always get Drupal's latest .htaccess for security updates for example. For that you don't exclude this file from Drupal Scaffold but you patch it instead. See the docs on Altering scaffold files.

Create a patch of the .htaccess and maybe put it in a folder called "patches" in your project root. Then configure a "post-drupal-scaffold-cmd" in the "scripts" section of your composer.json file to have this patch applied to Drupal's core .htaccess every time Drupal scaffolding is triggered.

"scripts": {
    ...
    "post-drupal-scaffold-cmd": [
        "cd web && patch -p1 < ../patches/htaccess-ssl.patch"
    ]
}


Using EntityFieldQuery's FieldCondition on file fields (or complex fields) I see plenty of examples of using FieldCondition on basic fields but in my case I would like to query if the file field holds a specific file name.

The structure in the entity object (with language undefined) is:

$entity->field_file['und'][0]['filename']

This is what I have tried:

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', $type)
  ->propertyCondition('status', 1)
  ->fieldCondition('field_file', 'filename', $tokens[1], '=')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

Perhaps it is having trouble because of the ['und'][0] not sure? Thanks.

Here is the detailed error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_data_field_file0.field_file_filename' in 'where clause': SELECT field_data_field_file0.entity_type AS entity_type, field_data_field_file0.entity_id AS entity_id, field_data_field_file0.revision_id AS revision_id, field_data_field_file0.bundle AS bundle FROM {field_data_field_file} field_data_field_file0 INNER JOIN {eck_downloadable} eck_downloadable ON eck_downloadable.id = field_data_field_file0.entity_id WHERE (field_data_field_file0.field_file_filename = :db_condition_placeholder_0) AND (field_data_field_file0.deleted = :db_condition_placeholder_1) AND (eck_downloadable.status = :db_condition_placeholder_2) AND (field_data_field_file0.entity_type = :db_condition_placeholder_3) ; Array ( [:db_condition_placeholder_0] => rnd13_poster_pack.pdf [:db_condition_placeholder_1] => 0 [:db_condition_placeholder_2] => 1 [:db_condition_placeholder_3] => downloadable ) in field_sql_storage_field_storage_query() (line 582 of C:\www\sr14\modules\field\modules\field_sql_storage\field_sql_storage.module).

A file field only contains the fid (file ID) relating to the file. The extra data you see (filename, uri, etc.) are loaded by the file module, but are actually contained in the file_managed table, which is not a field table.

Since EntityFieldQuery doesn't support JOINs you're out of luck, unless you alter the query a bit later on, e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->addTag('customtag');

...

function MYMODULE_query_customtag_alter(QueryAlterableInterface $query) {
  $query->innerJoin('file_managed', 'file_managed', 'file_managed.fid = field_data_field_name.fid');
  $query->condition('file_managed.filename', $something);
}

That will obviously need some tweaking for your specific situation.