Adding javascript to drupal 7 is giving error i am trying to add code using drupal_add_js and separate .js file. Its giving the Jquery is not found error.

(function ($) {
 function mobilizeCustomInit() {

                 // Add new Javascript and CSS files to mobile
                 // file loading list

                 // Note: Slashdot at the beginning of the filename
                 // indicates that the file path is relative to the HTML file location.
                 // This is an internal trick of mobilize.js.

               //  mobilize.cdnOptions.javascriptBundles.push("drupal/sites/all/themes/kanji/mobilize.yoursite.js");
               /**
 * This file is executed when the site is loaded in mobile mode.
 */

/**
 * This file is executed when the site is loaded in mobile mode.
 */

mobilize.extend(mobilize, {

    constructBody : function() {
        // Map different elements to jQuery Mobile theme
        this.constructHeader();

        this.constructContent();
        this.constructNavigation();

        this.constructFooter();
    },

    /**
     * Create mobile site header name and buttons
     */
    constructHeader : function() {
        // Map title and header buttons jQuery Mobile

        // This is the mobile target element
        // which will contain the title.
        $('.mobile-header').css('display','TRUE');
        var mobileHeader = $("#mobile-body div[data-role=header]");

        // Pick the current page title from  section
        var title = $("header h1").text();

        // Set mobile header title to the same text
        var h1 = $("h1").text(title);
        mobileHeader.append(h1);

    },

    /**
     * Move content area from web site to mobile site
     */
    constructContent : function() {
        var content = $("#content");

        // Place content HTML to mobile content area container
        var mobileContent = $("#mobile-body div[data-role=content]");
        mobileContent.append(content);
    },

    /**
     * Create mobile footer
     */
    constructFooter : function() {
        var footer = $("footer").children();

        // Place content HTML to mobile content area container
        var mobileFooter = $("#mobile-body div[data-role=footer]");
        mobileFooter.append(footer);

    },

    /**
     * Use jQuery Mobile nested list to create a navigation.
     *
     */
    constructNavigation : function() {

        // Get list of items which contain links for the navigation building
        var items = $("#navss li");

        // Create navigation list
        var list = $("
");

        // Add list header
        list.prepend("
Pages
");

        // Add list items
        items.each(function () {
            var output = $("
");
            output.append($(this).find("a"));
            output.appendTo(list);
        });

        // Put list below content
        var mobileContent = $("#mobile-body div[data-role=content]");
        mobileContent.append(list);

    }

});
                 mobilize.cdnOptions.cssBundles.push("./mobile-style.css");
            }
})(jQuery);

I would try to pass the $ alias to your mobilizeCustomInit() function.

Either way, the easiest way to solve your problem would be to just use "jQuery" directly in your code instead of the $ alias if its still giving you problems!


Why does the autocomplete return incomplete words? I am working on an autocomplete feature based on the Search API Autocomplete module. Basically I almost copied the functions I needed from this module for my use case. I set up a Solr index, and I am trying to query it, so it returns back relevant suggestions.

The problem is that the words returned are not always the words I am expecting. For example, if I enter Pu, the module should return Publication because this word is present in some nodes; it returns Public, which is not even present anywhere. From where does this mysterious word come? I don't know if the problem is with Solr index or Search API module, since they are twice involved in the module.

They are a lot of errors. Here are some examples of the issue.

studi instead of studies
strategi instead of strategies
describ  instead of describe

Actually the issue was related with stemming algorithms as Clive mentioned first. By removing this line in fieldType name="text" in schema.xml file, autocomplete was repaired:

<filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>

So, after I disabled stemming everything was good with autocomplete feature (either contrib module and my custom one), but unfortunately there was a new problem with standard queries (using Search API and views module); those were no more working. Then I managed to solve all issues my changing the analyzer of fieldType name="text" to this one.

<!-- An unstemmed text field - good if one does not know the language of the field -->

<fieldType name="text_und" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="true" />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="1"
            catenateNumbers="1"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            enablePositionIncrements="true"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="0"
            catenateNumbers="0"
            catenateAll="0"
            splitOnCaseChange="0"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
  </analyzer>
</fieldType>

With this definition for my text fields, everything works perfectly. Even accented characters are correctly returned, so it fits exactly my use case, as system is indexing english and french publications.

Thanks


Form API Field Permission I am creating a custom form and storing data in custom table. I was wondering if there is any method to apply field level permission like

$form['value']['#permission'] = array('access this field');

I know I am having field permission module to apply permission on core fields but how I can achieve this?

I am already not try this but i think it will work

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

  global $user;
  if ($form_id == 'FORM_ID') {
  if (in_array('yourrole', $user->roles)) {
  $form['your_field']['#access'] = FALSE;
    }
  }
}


compare terms from userterm and node term I have users and nodes.
bith have the same term referende field:

field_area

goal is to display a message in node.tpl.php when:
- user has term 'south'
- node has term 'south'

i have used the field extract module to get id term ID from the node.
$tid_node = field_extract_value('node', $node, 'field_bedrijf', 0, array('key' => 'tid'));
term id is .e.g: 5

Now i would like to find the term id using the user->field_area field.

I would utlimately have a code like:

if $tid_node == $tid_user {
print "a custom message" ;}

Found the solution after seaching around.
node term id:

$node_tid = field_extract_value('node', $node, 'field_your_taxonomy_reference_field', 0, array('key' => 'tid'));

user term id:

//load current user
$user_info = user_load($user->uid);
$user_term_id = $user_your_taxonomy_reference_field['und'][0]['tid'];

now set logic
    if  ($node_tid == $user_term_id) {
    print "show link";
     }


Drupal 7 field widget - allowed values list I need to have a select widget but with custom allowed values per user. Since in D7 I cannot use php code, I was wondering if there is some kind of hook I could use to achieve that functionality.

Thanks

This would be hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta = 0).

The example code for the hook, reported in the documentation is the following one.

function hook_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $element += array(
    '#type' => $instance['widget']['type'],
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  );
  return $element;
}


Is it possible to make a particular column in a tablefield readonly? Since in my case I have three columns A, B and C. A and B holds a data and C stores the summation of those data. I wrote a custom javascript to do that and also tried to make column C readonly through javascript but the problem is while in a table rebuild the data in column C clears out but if I didn't apply readonly on column C then data remains. Any suggestions in this case will be highly appreciated.

How are you applying the readonly to the fields?

You need to use the FAPI '#attributes' property to set readonly like this:

'#attributes' => array(
    'readonly'=>'readonly',
);

You need to alter the form through hook_form_alter and addd the above property to the textfield you want readonly.


how to rename password label on user edit page in Drupal? I would like to change labels only on user edit page. String overrides module would not work because it would rename all labels (user register and user edit). I tried the following:

function theme_preprocess_page(&$vars, $hook) {
  if ($vars['template_files'][2] == 'page-user-edit') {
    $vars['content'] = str_replace('Password', 'New Password', $vars['content']);
    $vars['content'] = str_replace('Confirm password', 'Confirm new password', $vars['content']);
  }
}

If you're willing to do it in a module (you mentioned String Overrides module) you can easily do it with a simple hook_form_alter() in a small custom module.

function mymodule_form_user_edit_form_alter($form, &$form_state) {
  $form['desired_element']['#label'] = t('My label');
  return $form;
}

This method uses hook_form_FORM_ID_alter(). This way you'll be able to set individual labels as you see fit, though.


Same path for different domains I have Drupal 7 with Domain Access on it.
On the main domain i have an About us page with the path www.example.com/about-us

How can i get same "/about-us" path on several subdomains like domain.example.com/about-us, domain2.example.com/about-us etc. to point to different nodes?

One possible option to create a view page (/about-us) and under filter option make it available on this domain and content type (create a content type for about us and place all about us content under it).


How do I add a custom CSS file for default theme? For example - I have enabled Zircon as my default theme. I want the user menu account to appear on left.
I want to add a custom CSS file where I can write a CSS elements and add to a default theme on site.

In Drupal 8, stylesheets (CSS) and JavaScript (JS) are loaded through the same system for modules (code) and themes, for everything: asset libraries. Asset libraries can contain one or more CSS assets, one or more JS assets and one or more JS settings.

More details on
https://www.drupal.org/developing/api/8/assets


Tuning with New Relic So I've finally delved into tuning up my aging Drupal 6 site using NewRelic and like most I'm amazed at what their product has to offer. Very useful for honing in on problem areas. However, being new to this I'm not fully sure what the correct actions are to fix my particular problem.

According to NR my biggest issue right now is the _revisioning_view (Revisioning Module) function. Digging through the trace reveals A LOT (1218) of calls to the url_alias table (which currently has 75,000+ records in it) I've read a few things suggesting running memcache or some form of Path Caching. 1218 Calls to url_alias certainly seems like a lot but before I go down the road of installing more modules I'd like to get a better grasp of what's going on here. Does anything jump out to anyone?

My other big item seems to be the time it takes to Insert and Update the cache_content table. See the attached screenshots from NR and let me know where you think I should go first.

For the url_alias issue, I'd strongly recommend moving over to Pressflow which provides the path_alias_cache module along with support for it.

  Pressflow is a distribution of Drupal with integrated performance,
  scalability, availability, and testing enhancements.

I'd also recommend installing DB Tuner on your site to catch any missing indexes.


Only show first entity reference in views In my situation :
I have 2 content types content type A and B
In content type B add entity reference field of content type A
In views, I want to display some values of content type A,but I also want to show some values of the first content Type B which has entity reference field to content type A.
How can i show only its first value ?

edit:
Content Type B has an entity reference field to Content Type A.
In the view I list all of the nodes of Content Type A.
But I also want to show some field of the first node that is referenced in Content Type B.

For example:
Content Type A has fields: title and logo.
Content Type B has fields: body and entity reference to Content Type A.
Multiple entities of Content Type B can be referenced to an entity of Content Type A.

What I want to show is:
Content Type A - Title
Content Type A - Logo
Content Type B[0] - Body

Thanks in advance!

This is how i did it :

In Views, under Advanced, add Entity Reference:Referencing entity relationship via your reference field id.
In Views, under fields add the field(in this case - Body) and add the above relationship .

Note: If there are nodes of content type B that reference same nodes of content type A, those same nodes of content type A will be duplicated in the views with different values of the fields of content type B that is referencing them.

Update: To remove such duplicates, you can use Views Distinct module and then in Views under fields, select Title field(Content Type A) and under Views Distinct Settings, change to 'Filter Repeats' for Filter/Aggregate this field and save.


How to add multiple field groups to a node I have a node type "Project", and users can add multiple tasks for this Project node. e.g. There is a Project named "Building website", it contains two tasks "Design" and "Code", and every Task has another two fields: time and budget.

The Field Group module can solve part of the problem, it can mix multiple fields into one field. But this mixed field amount can only be 1. That means I can only add one Task field in a Project, however I need add unlimited Task field to Project. Do you know any modules can do this job?

Field collection Modules

Provides a field-collection field, to which any number of fields can be attached.

A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


Views Template Suggestions When There are Duplicate Filenames What does Drupal 6 / Views 2 do when there are two templates with the same filename in different directories?

I just ran into a situation where a row template was accidentally uploaded twice.  Typically, I make views subdirectory in my theme, and then a subdirectory per view inside that.  Due to a bad copy/paste, I ended up with

site/all/themes/mytheme/views/myview/views-view-unformatted--myview.tpl.php
site/all/themes/mytheme/views/myview2/views-view-unformatted--myview.tpl.php

My dev server was picking up the first template.  My live server was picking up the second template, despite being the same set of files as the dev server.  I didn't do the actual live deployment, but as far as I know, the rollout was an exact clone of the files.

I haven't been able to unravel how this actually happened, and would appreciate some insight.

Thanks.

You could look and see in your theme registry by dpm-ing in theme_registry_alter() or by turning on devel and visiting /devel/theme/registry and seeing what entry is pointing to what file.

If you don't want to do that on production you could do it locally first and then grab the production database locally.

I would imagine that the registry was rebuilt between the two sites and the first time it picked up one of the files and the second time the other since I don't know of a designed hierarchy for two files in the same level directories in a theme folder.

Don't upvote - this is a speculative answer.


How to redirect to modal? I use the module "Bootstrap Login Modal".

How to redirect

/user/login

to

all over the site ?

Edit

According to the Readme.txt,

  You should now see login and register links on the right of the main bootstrap nav bar.

Enabling the module should show a link on the nav bar by default.

According to the project page,

  You should now see login and register links on the right of the main bootstrap nav bar.

/Edit

You can update all the links on your content, or use Javascript on a page load to modify them.

If you want to go with JS. This should get you started:

  var aTags = document.getElementsByTagName("a");
  for (var i = 0; i < aTags.length; i++) {
    if(atags[i].href == "/user/login") {
      //Modify your links
    }
  }


Theming a table '#type' vs '#theme' I am dynamically rendering a table in a Drupal 8 module. While creating my renderable array I noticed that I can define my table as a '#theme' => 'table' or as '#type' => 'table'.

$variables['test_table'] = [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

vs:

$variables['test_table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

Both of these options seem to output the same thing.

My question is this: Why can I use either '#theme' => 'table' or '#type' => 'table' when defining a table renderable array and is there any difference between how Drupal will render these differently.

I believe ultimately both will do the same thing. But when you use 'type' you are referring to what drupal element to use (see https://api.drupal.org/api/drupal/elements) and when you use '#theme' you're directly telling it what twig template to use.


rendering a custom entity I have a custom entity 'sponsor'.

I want to create a custom template for that entity. But I still want to use the formatter settings that have been defined in the UI.

So

I set the viewbuilder to the default EntityViewBuilder in my annotation
I defined the theme hook 'sponsor' in my .module file

function sponsors_theme(){
$theme_hook= array(
    'sponsor'=>array(
        'variables'=>array(
            'sponsor'=>null,

        ),

        'template'=>'sponsor',
    )
);

return $theme_hook;

}
Then I created my sponsor.html.twig file

Now I can access the raw values through {{sponsor.field.value}}

But I don't want to access all fields through their raw values. I still want to use the formatters.

Is there anyone who can tell me how to do that or point me to the right docs?

Matt.

You could craft a variable that holds all entity fields with respect to their order and formatter settings.

/**
 * Implements hook_theme().
 */
function sponsor_theme() {
  return [
    'sponsor' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for sponsor templates.
 */
function template_preprocess_sponsor(&$variables) {
  // Helpful $content variable for templates.
  $variables['content'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

This approach is used by core entities (node, user, comment etc).


How can I target a webform results page to create a panel around? I'm trying to set up a panel for the submitted page for a webform in order to add a sidebar and bottom section. I need help setting up the panel, specifically with how to select the submission (results) page of the webform.

The url of the submitted page looks like this - http://site.localhost/node/2136/done?sid=8

I tried -

String: URL path : Current path is "node/2136/*"

as well as -

String: URL path : Current path is "node/*/done"

both were a no go

Any ideas?

Since webform, for showing results implements a different path than the standard node/%, you need a way to tell Panels to take over this path.

The module Page manager existing pages allows you to do this.

Install and enable the module. Go to admin/structure/pages/existing-pages/add, find the path /node/%webform_menu/done and add it to the list.

Now go to admin/structure/pages and you should see a new "task" for results, where you can customize the result page.

As pointed out by winchendonsprings, the results are available under Add Content >> Existing pages >> Existing page >> node overview.

In order to do this on a webform by webform basis, one will need to add a manual node context, where you select the webform you want by nid, and then add a selection rule that compares the current context against the manually loaded one.

Normally manually loaded contexts should be avoided as "hardcoding" node id's is rarely a good idea, but this seems like a good exception from the rule, although it will still not be properly exportable.


Create a robust permission control I am building a system in Drupal and here is one question that is blowing my mind for more than a month and I hope you guys can help me.

My user access control inside the system must work like this:

1) I have a role called partners and I have lots of permissions assigned to this role partners.

2) I have a role called clients and again, I have a bunch of permissions assigned to this role.

3) The users with a partner role can create users with role partner AND client. The users with role client can create users with role client.

So far it is simple!

4) A user with role partner can create users with role partner and client BUT they can also say that the new partner or client created MUST NOT access some specific areas. So for example: A partner is allowed to see users, create users and create clients. When the ¨partner master¨ is creating a new partner user, he can say that this new user can only see users and create users but not create partners.

Do you know any module to solve this problem? I have already tried user_permission and subrole, none of them fit :(

Hope you can help, thanks!

BTW, I am using Drupal 7

Have you checked out the role delegation module? Sounds to me like your already using it but I may be wrong. It allows users with certain roles to act like the administrator. You can limit which roles can be granted.


How to translate database field values? I cannot find information on how translate database field values. On my site I use Support Ticketing System module. If I'm trying translate interface to German (for example) everithing is ok except Status field (Status field is reffering to support ticket status - new, in progress, closed). I can see in the database all these values (new, in progress, closed) in certain table. But how to translate them?
The built-in Drupal interface translation does not recognize these values.

Can you advise the correct way for translation of these field values?

Have a look at the Field Translation module, a submodule (i18n_field) of the i18n module. Some more details about it (from the Community documentation):

  ... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (Administration > Configuration > Regional and language > Translate interface).

Especially the "list options" mentioned above seem to be what you're looking for.


Is it possible to automatically add a taxonomy term for a content type? How is it possible to automatically add a taxonomy term for a content type?

Is it possible to make the new added terms children of this automatically set term?

I have a content type intended for users, and I would like them to be only able to add terms that are children of a parent term of my wish; in this way, if they choose a term, it will become a child of my default term, but if they don't add a term, then the node will be tagged automatically with my term (the parent term).

In Drupal it is possible to associate a vocabulary to a content type: Once you created your vocabulary, and added the taxonomy terms, you go to admin/structure/types, and for the content type to which you want to associate the vocabulary, you click on manage fields; in my example, I am going to add a vocabulary to the Article content type.

In the Add new field column I fill the fields as follows (the value you use for the field name, and to the field title can be what you like better):

When you click on Save, you get the following page. (The shown error is just because I am creating a patch for Drupal 7; it's not something you should see.)

Select the vocabulary you want to associate with the content type, and click Save field settings. In the next page, you can select the default value for the taxonomy term, which by default is - None -; you can select the one that is automatically set. If the user doesn't change it, it will be the value associated with the node.

When a user will create a node of that content type, they will see something similar to what shown in the following screenshot:

In my case, I selected Overview as default taxonomy term.

When you create your vocabulary, you can set a taxonomy term that is the parent of all the other taxonomy terms, and select it as default value for the content type.

In this case, Golden apple is child of Apple, which is child of Fruits; Kaiser pear is child of Pear, which is child of Fruit.
As side note, the hierarchy of taxonomy terms that are shown in the node edit form is the one defined in the vocabulary you associated with the content type; this means that, if Apple is not child of Fruit in the vocabulary I am using, then it will not be shown as child, in the node edit form. The taxonomy term widget doesn't alter the vocabulary structure.


How to apply one AJAX to all form elements? #ajax is

  used by: button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield

Sadly, form is not on the list. But on one form, I need to apply ajax to all form elements. With possible exception of submit button, but it will be hidden if javascript works, so it is not an issue, literally all elements is OK.

Is there any neat way to do it?

Currently I'm writing something like this:

$ajax_code = array(
  'callback' => 'poll_choice_js',
  'wrapper' => 'poll-results',
  'method' => 'replace',
  'effect' => 'fade',
);

And then in each element:

  '#ajax' => $ajax_code,

But it will be easy to forget to add this line to some elements in future, so I'm looking for a way less prone to errors.

Reason: My wrapper is actually outside a form and is used for preview, I need to update preview every time anything changes. Form will never need to be submitted. Ajax will never change form elements.

I don't believe there's anything 'built in' for that, but a small recursive function would handle it:

function _MYMODULE_apply_ajax(&$element, $ajax) {
  $element['#ajax'] = $ajax;
  foreach (element_children($element) as $key) {
    _MYMODULE_apply_ajax($element[$key], $ajax);
  }
}

Where you apply this kind of depends what you need. You could add it at the end of the form function itself, but if there's a chance your form could be altered it would be best in hook_form_alter(). Either way just call

_MYMODULE_apply_ajax($form, $ajax_array);


How to allow anonymous user for checkout process? When users buy one of our offers (premium offer), the site will create a user account, send a link to his/her account to reset the password, etc.

How to achieve this?

You may need to check the permission, under Admin > People > Permissions : "Access checkout" for anonymous users.

If the user does login, their anonymous order will be added to their authenticated user cart.


How to render a media entity image (that uses a focal point image style) inside a paragraph twig file? Originally I used a typical image field in my paragraph, now with the new updates for the media module I would like to use the image library to upload and reuse media entity images. I use focal point for my image styles, in the paragraph I use, the user can choose between a couple of image styles.

preprocess code for passing image styles to twig template:

function tekst_en_afbeelding_preprocess_paragraph__tekst_en_afbeelding(&$variables) {
    if (isset($variables['elements']['field_image']['#items'])) {
      $variables['img_223_x_308'] = ImageStyle::load('223_x_308')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_326_x_450'] = ImageStyle::load('326_x_450')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_560_x_308'] = ImageStyle::load('560_x_308')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
      $variables['img_1280_x_703'] = ImageStyle::load('1280_x_703')->buildUrl($variables['elements']['field_image']['#items']->entity->uri->value);
  }
}

This code does not work anymore for the media entity image.what do I need to change for this to work?

You'll run into troubles with this technique, because Media images are entities on their own, and have their own cache settings. So if you change the image style on paragraph level, the embedded media image will not know anything of this and instead returns the first, cached size.

Instead create multiple display view modes for your media entities, and let your editors choose the view mode on paragraph level. Below is the code I'm using in my own projects

function wtfrontend_base_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_image_viewmode_image')) {
    $imageViewMode =  $paragraph->field_image_viewmode_image->value;
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
      unset($variables['content']['field_image']['0']['#cache']['keys']);
    }
  }
}

Render the image normally with {{ content.field_image }}


show the rate of tax in order I've create Tax Rate of 20% in VAT type of tax.

It is now displayed in the checkout process and in order view.

What I want now is to show the rate i have created, which is 20%, in the checkout and in order?

Any help will be greatly appreciated.

Thank you!

Not sure if this is what you want to do but could you just not rename the display name of your tax to 20%?

Go to admin/commerce/config/taxes click edit on your tax and under display title enter 20% tax or what you wish the display name to be.


Creating a Batch with multiple functions i'm trying to optimise my setup of a Drupal Batch process.

I am reading in thousands of rows of data from an Excel spreadsheet, from multiple worksheets, and creating nodes from the Rows. My import functions work fine, and I can create a Batch, but at present I am creating a batch operation for each row. This means that my batch is very slow (because I'm having to bootstrap Drupal on every row).

What I can't seem to figure out is a way to setup my batch to deal with 'chunks' rather than individual rows.

An example of my import function (of which there are 18) is:

function governbim_coordinate($value){
    module_load_include('inc','phpexcel');
    global $user;
    $project = $_SESSION['governbim']['projnid'];
//Load the required worksheet from the excel file passed to the function as $value
    $result = phpexcel_import($value,TRUE,TRUE,array('setLoadSheetsOnly' => array('Coordinate')));
//Define some common values for our entity
    $values = array(
            'type' => 'coordinate',
            'uid' => $user->uid,
            'status' => 1,
            'comment' => 0,
            'promote' => 0,
            );
//step through each row in the worksheet
    foreach($result['Coordinate'] as $coordinate){
        $title = $coordinate['Name'];
//check to see if this is a new row or if we are updating an existing entity
        $action = governbim_node_actions_node_check('assembly',$title);
        switch($action['op']){
            case 'new':
                $e = entity_create('node',$values);
                $entity = entity_metadata_wrapper('node',$e);
                break;
            case 'update':
                 $e = entity_create('node',$values);
                   $entity = entity_metadata_wrapper('node',$action['nid']);
                break;
        }
//*** Here is where we write everything to the database with the entity values and $entity->save() ****/
    }
}

My batch is setup (currently) as:

function governbim_excel_import_batch(){
    drupal_set_message("Importing Data...");
    $path = 'public://imports/';
    $file = 'COBie-UK-2012-example1.xls';
    $datafile = $path.$file;

       $operations[]=array('governbim_coordinate',array($datafile));

        //another 17 $operations[] defined as above

    $batch = array(
        'operations' => $operations,
        'init_message' => t('Constructing batch operation...'),
        'progress_message' => t('Importing Excel data'),
        'finished' => 'governbim_excel_import_batch_finished',
        'error_message' => t('Importing of Excel data encountered an error.'),
        );
    return $batch;
}

I realise I need to get some $context stuff into the import function, but I can't seem to figure out how to setup that aspect properly.

Is anyone able to assist me in re-tuning things so that I can get the batch (with 18 function calls) to display progress of the overall batch and get the batch to execute (say) groups of iterations (as in $limit = 10)?

I do one batch operation but with multiple entry.

/**
 * Batch start function.
 */
function mymodule_batch_start() {
  $batch = array(
    'title' => t('Importing Excel data'),
    'operations' => array(
      array('_mymodule_import', array()),
    ),
    'progress_message' => t('Importing Excel data. Operation @current out of @total.'),
    'error_message' => t('Error!'),
    'finished' => 'mymodule_batch_finished',
  );
  // Run batch in background
  batch_set($batch);

Here is the pattern fot the operation:

/**
 * Import operation.
 */

function _mymodule_import(&$context) {

  // Get your import data with some custom function.
  $import_data = _mymodule_get_import_data($context);

  // Get Count of items
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($import_data);
    $context['results']['total_count'] = $context['sandbox']['max'];
  }
  // Create Iteration variable
  if (empty($context['sandbox']['iteration'])) {
    $context['sandbox']['iteration'] = 0;
  }

  // Check for the end of cycle
  if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {

    // Count of operation in one butch step
    $limit = 10;
    // Counts completed operations in one butch step
    $counter = 0;
    if ($context['sandbox']['progress'] != 0) {
      $context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
    }

    // Main loop of all import items
    for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {

      // Do smth custom here with import data item $import_data[$i].
      _mymodule_handle_import_item($import_data[$i]);

      // Update Progress
      $context['sandbox']['progress']++;
      $counter++;
      // Messages
      $context['message'] = t('Item %progress of %count', array(
        '%progress' => $context['sandbox']['progress'],
        '%count' => $context['sandbox']['max'],
      ));
      $context['results']['processed'] = $context['sandbox']['progress'];
    }
  }

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

P.S. Sometines I need to import data and then remove some old data. You can store some results of 1st operation in $context and then use it in other operation. I can do import in one batch with two operations:

'operations' => array(
  array('_mymodule_import', array()),
  array('_mymodule_remove_data_after_import', array()),
),


How do I resolve the "Argument 1 passed to drupal_attributes() must be an array" error on my system_settings_form()? I don't usually post specific questions like this, and ask for help on a specific issue but I am at the end of my rope wasting time way...

I have a simple D7 module as seen below, when I load the page (who's menu item is exactly where I want it to be) I get the following error:

  Recoverable fatal error: Argument 1 passed to drupal_attributes() must be an array, null given, called in /path/to/site/public_html/includes/form.inc on line 3106 and defined in drupal_attributes() (line 2257 of /path/to/site/public_html/includes/common.inc).

as you can see the form declaration itself is very simple, and everything runs peachy keen until the page load.

note, that I have looked at: 3106 in form.inc and the $element is populated but attributes doesn't exist - what am I missing???

<?php
/**
 * Implements hook_menu().
 */
function attach_images_menu() {

    $items['admin/structure/types/manage/%/attach/images'] = array(
        'title' => 'Attach: Images',
        'page callback' => 'attach_images_settings',
        'access arguments' => array('access administration pages'),
        'weight' => '10',
        'type' => MENU_LOCAL_TASK,
    );

    return $items;

}

function attach_images_settings() {
    //$content_type = arg(4);
    $form['attach_images_amount_'] = array(
         '#type'   => 'textfield',
         '#title'  => 'Amount',
         '#default_value' => variable_get('attach_images_amount_',1),
    );
  return system_settings_form($form);
}

?>

$items['admin/structure/types/manage/%/attach/images'] = array(
    'title' => 'Attach: Images',
    'page callback' => 'attach_images_settings',
    'access arguments' => array('access administration pages'),
    'weight' => '10',
    'type' => MENU_LOCAL_TASK,
);

This should be 'page callback' => 'drupal_get_form', 'page arguments' => array('attach_images_settings'). (don't forget to clean the cache after making the change)

Also, form callbacks in Drupal 7 have a mandatory $form argument.


Update module issue - version_major in update_calculate_project_update_status() I am building a site using Drupal 7.26.

I get this notice all the time:

  Notice: Undefined index: version_major in
  update_calculate_project_update_status() (line 628 of
  /XXX/public_html/modules/update/update.compare.inc).

Does someone knows what is the problem, and how to solve this?

Thanks!

If you put:

if(!isset($release['version_major'])) {
    die('<pre>'.print_r($project, TRUE).'</pre>');
}

On line 625 of update.compare.inc then when the version_major is not set it will print out details of the problem module and die.

Once you know what module is causing the problem then remove this code again as otherwise kittens may die.

When you know what module is causing the issue then you can raise the problem in their issue queue.


How To Wrap Multiple Content Field Items In Li Tag I've got an issue with a field called Track Listing. As the title states it is a Text(plain) type with unlimited possible values so that I can input as many as I'd like. The machine name is: track_listing

As it stands I'm outputting the label and items using: {{ content.field_track_listing }} which gives me this:

But I'd like to be able to wrap the field in an ol tag in addition to every track with a li tag to be able to get a nice ordered numbered list. Using twig templates I've wrapped it accordingly but find it only targets the first value which is in this case the label as seen here:

I feel that I should be using a for/if loop in order to get the right values since removing the label only wraps the first item as well. If anyone has an article I can check out to point myself in the right direction I would appreciate it, thank you.

You can easily theme a multiple value field in the field template.

To do this put a field twig in mytheme/templates:

field--field-track-listing.html.twig

{{ label }}

  {% for item in items %}

{{ item.attributes }}>{{ item.content }}

  {% endfor %}

Here you can change the html markup around each field item {{ item.content }} the same way as you do this in node around the complete field {{ content.field_name }}. This is the concept of nested render elements.


How do I use the Save Draft module for a particular content type only? I want to use the Save Draft module for a particular content type. When I install this module by default, it will be applied to all the content types. Please let me know how to avoid this.

I'm using version 7.x-1.4 of the module.

Currently you have to install the 7.x-1.x-dev version to get settings per content type.

Once you install that version you can configure the settings on the node type settings form (eg. admin/structure/types/manage/article).


7 - Download file and generate page I've got a form that gathers some data. The data is then modified and should be passed to the user as a file. To manage this I did the following:

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: text/out');
header('Content-Disposition: attachment; filename="file.out"');
echo $file;
module_invoke_all('exit');
exit();

What I need now is to somehow display some additional info to the user without losing the input data. In other words, when user submits a form, it should let him download the file and then, for example, print out a success message, contents of the file downloaded or another form. Is there any way to do that?

You need to isolate that code out of your form submission handler. When you set the Content-Disposition: attachment header it's going to override the browser behavior of loading a new page.

Instead, you should have your form handler save the output file & generate a success page containing a download link (in case your user doesn't have JS support) and run a JS setTimeout() function that will trigger a download after X seconds. See this SO post for an example.

The download link path can be generated with hook_menu(). Its callback function will use your code snippet above. Depending on the content of the download (e.g. sensitive personal data), you may need to protect this path. This can be done in a variety of ways.


How to change the value of site_name to "My site name" in multilingual sites using Drush? I'm trying to use this Drush command:

drush variable-set site_name "My site name"

I have no problem at all to use this command when the site has only 1 language. But it doesn't seem to work (have any effect) in a multilingual site when the "site name" is to be translated to additional languages.

Is there a way to use this Drush command to set the site-name in every of those additional languages? Either at once or in every language (in several steps)?

I understand your question as trying to use Drush for setting the site name, using Drush command like so:

drush variable-set site_name "Some name here"

And this for a multilingual site.

The equivalent of doing this via Drupal admin screens (instead of Drush), would require to first declare your site name as a "multilingual varialable". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

In this case however, in "step 4" the variable to be selected is "Site name" (not "Default front frontpage"), within "Site information". While you're at it, you probably want to double check other similar variables like Site Slogan, etc.

If you try to do this using Drush, it won't work however, as explained in the issue about set i18n variables with drush? However, if you have the Variable module enabled, then according to Comment #3 in that issue, it should be possible to use Drush to achieve the equivalent result via Drush command like so (to set the Spanish language (es) to 'Spanish site'):

variable-realm-set language es site_name "Spanish Site"

Curious to some hear if in this case this Drush command resolved the issue here.


What is the Features specific data in a Features module's .info file I'm not sure if this is a Features module question or simply a module construction question.

I have a module which was constructed with Features, which I have never used before. In the .info file of the module there are a lot of lines that read similar to features[something][] = something.

What is this and where is it used in the module?

Some of the documentation is sparse (still!?) https://drupal.org/node/1720098

The entries in your .info file tell Features that that item of your configuration is controlled by Features and not say Drupal core. You'll see stuff like ctools or views in there. In the main features.inc file the features info hook will require those API dependancies.

Based upon other lines in the info file such as:

features[ctools][] = strongarm:strongarm:1
features[ctools][] = views:views_default:3.0
features[user_permission][] = create features_test content
features[views_view][] = features_test

These lines would say, features uses Strongarm to read/write configuration of variables, and Ctools integration. Then there is some view features_test and some user permission exported create features_test content.

From the documentation page i linked these .info configuration values then:

  They are called during hook_module_enable/disable to fire the right
  stuff in the right places.

By Features itself. The info file contents tells Features what its managing. The .inc files include the dynamic configuration values needed per .info item entry (usually in terms of plain Drupal hook_info configuration definitions that'd you basically be making in code anyways).

I recommend reading the Features API and Readme:

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/API.txt

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/README.txt


Why does my background image only sometimes show? I have a background image set for #region-header-first on this page http://www.smith-howard.com/resources?type=article&sort_bef_combine=created%2BDESC

However, it only shows sometimes in Chrome (mostly not). If I clear all Drupal caches (and browser cache) it will show once, but on the first refresh and so on it doesn't show any more.

If i check web inspector in safari (where it always works), it definitely shows the background image in the CSS.

#region-header-first background:url(http://www.smith-howard.com/sites/default/files/resources-articles2_0.jpg);

But inspecting it in Chrome doesn't show that the background image is set in the CSS at all. This is just mind boggling.
Any help is greatly appreciated.

To fix it, if you want, you can check all your blocks and views and template files to see if you can find the HTML (as you can see it when you view source)

    <style type="text/css" media="all">
    .not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}
    </style>

code and remove it, OR don't worry about it and just add

.not-front #region-header-first .field-name-field-headline,.not-front #region-header-first .field-name-field-subhead{color:#ffffff !important;}

to your theme's .css file


How can I use Drush 8 command to enable the site set up bin the Acquia DevDesktop to online mode? I forgot to put the site back online when I'd finished updating the site. How can I use Drush command to enable the site to online mode?

You are talking about maintenance mode. If you had use the correct term, you would have been pointed to for example the following question which has the info you need:

drush sset system.maintenance_mode 0


Node export import into different node numbers I use node export to export my nodes from Drupal 6 and import into my new site Drupal 7.

The nodes number is not same with nodes in Drupal 6.

How do I set it same as nodes number in Drupal 6.

Node ID numbers is an auto-incremented field in the database that is global for the entire Drupal installation. Attempting to replicate the exact Node ID in Drupal can be difficult and cause serious problems if handled incorrectly.

If your issue is URLs, one option is to make a 301 alias for the old URLs to the new URLs. There are modules to easily create the redirects like the Redirect module.

If you must maintain the ID numbers then the solution will have to be custom migration code. The migration process will recreate the nodes in the new site and account for any node deletions.


Programmatically change the weight of a form element I have a user activation/registration form with different attribute like

Captcha and security questions which are coming from different modules.

I want to change the display order of form elements.

and i am using this code in my custom module

function security_question_form_user_register_form_alter(&$form, &$form_state) {
  if ($form_id == "create_account_form") {
    $form['#pre_render'][] = 'security_question_form_alter_weight';
  }
}

function security_question_form_alter_weight($elements) {
  $elements['questions']['#weight']= -47;
  return $elements;
}

It's not working. Can any one have any solution?

You can do this directly inside hook_form_alter, like this:

function security_question_form_user_register_form_alter(&$form, &$form_state) {
  $form['questions']['#weight'] = -47;
}

Then there is no need to create a custom function to do it.

Another thing, you can't implement hook_form_FORM_ID_alter and then use $form_id inside that. You must implement either hook_form_alter, and check if the form id is the one you want, or implement hook_form_FORM_ID_alter and write the form id in the function name.


when mouseover on username display popup views How to display popup ajax information of user when user mouseover on username or picture of users with views.
i want fetch information from profile user with ajax no hidden.
such as Facebook or LinkedIn

Hope this will help you

In Drupal 7, for your requirement you can use qTip (Stylish jQuery Tooltips) module with Views.

After installing and configuring qTip, go through the qtip examples(refer qtip README.txt).
For this example I have created a view with some user fields, these fields will popup on hovering user picture
Create a new view and add fields which you want to show on the popup.

For showing user information in popup, you need to give the proper structure(read qtip README.txt).
I have added the HTML structure for profile_image view field

On mouse hover of the user picture, user information will popup. And make CSS changes as per your requirement.
You can also refer BeautyTips, for example you can refer this link

Drupal 7 : Ajax load

Steps

To show user details on hover you need to add attributes to the username, it can be done using preprocess function template_preprocess_username in your active theme tempalte file.

function themeName_preprocess_username(&$variables) {
  $variables['attributes_array'] = array('class' => array("user-info"), 'data-uid' => $variables['account']->uid);//adding more attributes for your requirement
}

Create a view with the fields you want to show on popup.
Create a menu to get user details like get/user_details/%, where % is the user-id. This menu will returns user details.

function test_menu() {
...
$items['get/user_details/%'] = array(
'title' => t(''),
'type' => MENU_CALLBACK,
'page callback' => 'get_user_details_ajax_callback',
'page arguments' => array(2),
'access arguments' => array('access content'),
);
...
return $items;
}
//Implement the ajax callback to get user details
function get_user_details_ajax_callback ($uid) {
$html = '';
$html = views_embed_view('VIEWNAME','display_id', $uid);
return $html;
}

For showing the user details on hover, you need to make a ajax call using
$.ajax
Once the user hover the username get the data-uid attribute and make a ajax call to get user info.
Once you get the user details append it and show as popup.

Drupal.behaviors.getUserDetails = {
    attach: function (context, settings) {
      var replace_wrapper = 'user-'+$(this).attr('data-uid')+'details';
      //add html to show user details
      $( "a.user-info" ).each(function( index ) {
        if(!$(this).closest('div').hasClass('user-details-wrapper')){

      $(this).append("

");
    }
  });
  $('a.user-info').mouseenter(function(){
    if($(replace_wrapper).is(':empty')){//if empty then make ajax call and
      var url = Drupal.settings.basePath + 'get/user_info/'+ $(this).attr('data-uid');
      $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
          //create html and append to replace_wrapper
          var user_detail_html = '';
          //code to get user html here
          $(replace_wrapper).each(function( index ) {
            $(this).html(user_detail_html);
          });
        }
      });
    }else{
      //show popup here
      $('user-details-wrapper').show();
    }
  }).mouseleave(function() {
    //hide popup here
    $('user-details-wrapper').hide();
  });
 }
}

Make changes as per your requirement

Note : views_embed_view


Stuck. Installing Drush via Composer not working It looks like I installed Drush, following the directions in the documentation.

Here's what I did.

Jens-MacBook-Air:~ jensimmons$ composer --version
Composer version 1.0.0-alpha8 2014-01-06 18:39:59
Jens-MacBook-Air:~ jensimmons$ composer global require drush/drush:dev-master
Changed current directory to /Users/jensimmons/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing pear/console_table (1.1.5)
    Downloading: 100%

  - Installing symfony/yaml (v2.2.1)
    Downloading: 100%

  - Installing d11wtq/boris (v1.0.8)
    Downloading: 100%

  - Installing drush/drush (dev-master a2c7030)
    Cloning a2c703071e2c3374e1b3855e24d29468b9069b5c

pear/console_table suggests installing pear/Console_Color (>=0.0.4)
d11wtq/boris suggests installing ext-pcntl (*)
Writing lock file
Generating autoload files
Jens-MacBook-Air:~ jensimmons$ drush help
-bash: drush: command not found

When I change directories, to inside a Drupal installation, I get the same result. drush: command not found.

What am I missing??

Try adding the following to the end of your /Users/jensimmons/.bashrc file:

export PATH="$HOME/.composer/vendor/bin:$PATH"

and then run

source $HOME/.bashrc

Edit:

I just noticed there was a section in the Install/Update - Composer section of the Drush README.md file that mentions this:

https://github.com/drush-ops/drush#installupdate---composer

It's the second point "Make sure Composer's global bin directory is on the system PATH (recommended)"

Hope that helps.


Using same pictures twice in one node (media module) I've been using the EPSA crop module for a while now without any complaints. But I've run into a small problem, which I can't fix. I use the media module in combination with the EPSA crop module. When I add a picture twice in one node then only one cutout will be saved and all the same pictures will be cut the same way. So a cutout isn't unique. Does someone have an idea?

Using Media 7.x-2.0-beta1 and EPSA crop 7.x-2.3.

No solution right now, because all the cropping modules stores their information using fid, without entity id or something else which can give information where it will be used. As a workaround on this problem, I altered some crop forms and created a new image per each crop.


Views with exposed filters WITHOUT `Use Ajax`? Is there a way to use exposed filters, but not require Use Ajax ? I want exposed filters but I want it to submit the form and refresh the page.

I believe you need to use the Page Display. That behavior doesn't work when the view is rendered as a block.


Prevent caching of ajax loaded forms Trying to make a custom page to add taxonomy terms. The page contains one drop-down menu that lists all enabled vocabularies. Full taxonomy add form loaded after I select some from that menu.

This is menu callback:

    function add_term_form_callback($form, $form_state) {

      module_load_include('inc', 'taxonomy', 'taxonomy.admin');
      $vid = $form_state['values']['vocabulary'];
      $vocabulary = taxonomy_vocabulary_load($vid);

      $form_state['values'] = array();
      $form_state['build_info']['args'] = array(array(), $vocabulary);

      $form_state['rebuild'] = TRUE;
      $form_state['no_cache'] = TRUE;
      $form = drupal_build_form('taxonomy_form_term', $form_state);

      return $form;

    }

...and form

    function add_term_form($form, &$form_state) {

      $options = array();
      $options[0] = t('- Select -');
      $vocabularies = taxonomy_get_vocabularies();
      foreach ($vocabularies as $vocabulary) {
        $options[$vocabulary->vid] = $vocabulary->name;
      }

     $form['vocabulary'] = array(
       '#type' => 'select',
       '#title' => t('Select vocabulary'),
       '#options' => $options,
       '#default_value' => $selected,
       '#ajax' => array(
         'callback' => 'add_term_form_callback',
         'wrapper' => 'container',
         'event' => 'change',
       ),
     );

      $form['container'] = array(
       '#type' => 'container',
       '#prefix' => '
',
       '#suffix' => '
',
      );

      return $form;
    }

So the problem is that the form remains in the same state after first load. How to refresh the form properly?

According to the documentation:

  Changes to the form must only be made in the form builder function (ajax_example_autocheckboxes() in the example here), or validation will fail. The callback function must not alter the form or any other state.

You have been changing the form_state and the form in the callback.

Based on how I understood the documentation, you should be just returning the whole form in your ajax callback and then do the change in your form in the form builder function. You can just check the form_state value of the drop down to know which form to render. I imagine it'll be something like this:

function add_term_form_callback($form, $form_state) {
  return $form;
}

 function add_term_form($form, &$form_state) {

 // If vocabulary has value
      // do stuff
      // $form = drupal_get_form('taxonomy_form_term');
 // else :
  $options = array();
  $options[0] = t('- Select -');
  $vocabularies = taxonomy_get_vocabularies();
  foreach ($vocabularies as $vocabulary) {
    $options[$vocabulary->vid] = $vocabulary->name;
  }

 $form['vocabulary'] = array(
   '#type' => 'select',
   '#title' => t('Select vocabulary'),
   '#options' => $options,
   '#default_value' => $selected,
   '#ajax' => array(
     'callback' => 'add_term_form_callback',
     'wrapper' => 'container',
     'event' => 'change',
   ),
 );

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';
  );
  // endif;

  return $form;
}

EDIT: I just noticed that you weren't wrapping the form but a container in the form. you would have to wrap the form if you want the whole form to be reloaded.


Products discount pinned at the top of the lists I would like that when a product at a discount, it is "Pinned to the top of the lists" automatically.

And when a product does not have a discount, it is no longer "Pinned to the top of the lists".

How to do this with a rule?

Unfortunately you cannot do this with a rule. Whether or not something is sticky depends on how Views sorts a list of products, and there is no sort handler that I'm aware of that would show discounted products first. The closest you could come to would be an extra field on your products that you set when you enable the discount to identify a discounted product. You would then be able to sort by that field value.


How to clear export_module for a view I am unable to export a particular view via Features UI because this view is supposedly default by a different module. In features.ctools.inc line 164 - 172:

// If this object is provided as a default by a different module, don't
      // export and add that module as a dependency instead.
      if (!empty($object->export_module) && $object->export_module !== $module_name) {
        $export['dependencies'][$object->export_module] = $object->export_module;
        if (isset($export['features'][$component][$object_name])) {
          unset($export['features'][$component][$object_name]);
        }
      }
      // Otherwise, add the component.
      else {
        $export['features'][$component][$object_name] = $object_name;
      }

As you see from the code, my view is not being exported because it has different 'export_module'. How to clear 'export_module' for a particular view to enable it export via features.
This is what i did:

ensure that the other feature doesn't export this view.
Ensured that the setting 'Allow conflicts to be added' is selected.
I have cleared cache,
Deleted the tables cache, cache_view.

No result, the view i like to export via feature continue to come up with 'export_module' different making impossible to export. Any help much appriciated

After removing MODULE-Name_views_default_views() in file MODULE-Name.views_default.inc, the view was exporting in another feature/module just fine.

My learning is that if you rename views that are part of some feature/module say X then these views become impossible to export from any another feature/module Y unless you manually delete them from the MODULE-X-Name_views_default_views() in MODULE-X.views_default.inc file


Bulk deletion of node which are unpublished and which are in between the given dates I unpublished all the nodes which are created between January 1, 2012 and January 1, 2015. Then, I published 800 nodes.

Now I want to delete all the nodes I first unpublished. I have almost 28,000 nodes. How do I bulk delete them?

I also want to delete the images uploaded along with the nodes.

I suggest to use the Rules module for that.
Bulk deletion is explained in one of the first tutorial video's in this series:
https://drupalize.me/videos/introduction-rules?p=1157

What you should do:

enable Rules and Rules UI
create a new Component of type "action set"
actions to add: a loop thru the nodes and if the date matches, the node should be deleted

The Views Rules module might be usefull to use views to send the nid's of the nodes to delete to the rules component.
I learned a lot about this via the accepted answer to "How to pass arguments to a view from Rules?".

An alternative could be the Views bulk operations (VBO) module, which has a "bulk deletion" out of the box. You add a VBO-field in your view and select the "delete" as the action. Maybe this is even better than the Rules (in the way that it will take less time to understand and implement).


I need to load DB configuration dynamically in Drupal 7 Can I put variable_get in settings.php to load DB settings dynamically or there is a better way.

Drupal allows you to override settings using the $conf[] array in settings.php. They will be then available via variable_get('key', 'default') in any module.

See 'defining site variables'
and variable_get()

The pattern we use is that any defaults go into install.php. starts with:

function hottopicsnotify_install() {
  variable_set(HOTTOPICSNOTIFY_CONTENT_TYPES_VAR, 'hottopics_node_form');

Override the variables with an admin form where needed. e.g.

function hottopics_settings($form, &$form_state) {

Read using variable_get. e.g.:

'#default_value' => variable_get(HOTTOPICSNOTIFY_EDITORIAL_CRON_KEY, ''),


How to Add rel="nofollow" in "Add new comment" link in teaser? Is there a code to add rel="nofollow" in the "Add new comment" link under teaser?

This is the code in the teaser as generated by D7:

Add new comment

So how I do I add rel="nofollow" in that line?

You could do this by implementing hook_node_view_alter in your custom module or theme.

//replace MODULENAME below with your custom module's name
function MODULENAME_node_view_alter(&$build) {
  if ($build['#node']->type == 'book') {
    $build['links']['comment']['#links']['comment-add'] = "rel=\"nofollow\"";
  }
}

This is for node type book, you could replace it by the content type you are using.

Here is the Module developer's guide, which should get you started.


Google Maps directions link icon I would like to know how to embed a Google map on a page, so that the the "directions" icon is showing. I had previously used the Simple Gmap module, but it doesn't provide the icon which I need.

You could create a custom region in your theme, then include a block with unaltered text that directly makes a call to the Google Maps API. This allows you the most flexibility since you work directly with the API - however this is only practical with a static location. If you are using something like a geo location module to assign destination parameters or other, you will need to adjust this.

EDIT:

in hindsight, depending on your needs, you probably don't need to create a dedicated region in your theme.

To create an unaltered text area (D7):

1) goto admin/config/content/formats

2) 'add text format'

3) Name: unaltered, Roles: Administrator ONLY! - giving others access to this has MAJOR security issues, so make sure it is admin only.

4) Save, and move it to the bottom of the list, Save Changes (this makes sure it's not the default

Get the google maps API address:

1) go here: https://developers.google.com/maps/web/

2) setup a google developer account (all google api's require this - its free).

3) goto Google Maps Embed API on that page

4) read the page, and setup your api call as you want.

5) copy the code

In admin/structure/blocks:

1) 'Add block'

2) title: < none > (with spaces removed) or as desired

3) Body: paste code from google API - adjust the dimensions as desired (width and height as given by the API call)

4) Text format: unaltered

5) save

6) put the block in the appropriate region


Display content referring other content in a mapping table I have the following problem I can't figure out how to solve - note I am a Drupal newbie...

I have two content types; TypeA and TypeB. TypeA includes an entity reference field of TypeB to create a static relationship, similar to a "related work" or "is part of" use case.

This relationship displays fine in the full display mode for TypeA and all is well on that front.

I fail, however, to display this relationship as a mapping table in a third content type, where all TypeB nodes represents columns, and all TypeA nodes are displayed in individual rows like the following example:

Example:

Consider we have the following three nodes of TypeB: NodeA, NodeB, and NodeC.

We also have 5 nodes of TypeA, all along with the following relationships to TypeB nodes as follows:

Node1 (NodeA, NodeC)
Node2 (NodeA)
Node3 (NodeB, NodeC)
Node4 ()
Node5 (NodeA, NodeB, NodeC)

The mapping table then would look like this:

      | NodeA | NodeB | NodeC
------|-------|-------|------
Node1 |   X   |       |   X
------|-------|-------|------
Node2 |   X   |       |
------|-------|-------|------
Node3 |       |   X   |   X
------|-------|-------|------
Node4 |       |       |
------|-------|-------|------
Node5 |   X   |   X   |   X

Obviously, I do not want to maintain this table manually, but be built depending on the actual dynamic content of the site.

EDIT

The following constraints also apply (forgot to mention them in the first place):

When I unpublish or delete a node of content type TypeB, the entire column of this mapping table needs to disappear
The view (anticipating that I can implement this through crafty Views configuration) should not be cached, or cache-cleared upon change (is that even possible?)
The "X" in the example table would ideally be replaceable with other code or content I control (e.g. a little image, or glyph or so)

Thanks a lot,

Michel

I don't think you can build that with views or another UI tool just by clicking it together.

It should however not be too complicated to build with a but of custom code.

You need to build an entity query that gets all TypeA nodes, another one that gets all TypeB nodes, loop over Type, and for the columns, loop over the Type B and check if you have a reference for them in your field.

IMHO writing out the full code is too much for a single question, I suggest you get started and if you have problems, ask specific questions.

Obviously that table will get huge if you have a lot of nodes of either type or even both.


How to implement a hook? I've been told I should implement this hook thing, what does that mean?

The details for how to implement a hook varies from one hook to another.

One of the easiest examples though, is hook_init(). Hook init is a generic way of saying "Do something on every un-cached page load". The _un_cached part is important, if you are logged out when testing this, probably nothing will happen.

In a module file named "my_module.module", one would implement hook_init like this

<?php
my_module_init() {
}

To make something actually happen, we can add a call to drupal_set_message().

<?php
my_module_init() {
  drupal_set_message('Hello Drupal!');
}

If you have Devel installed, a common way to do debugging could look something like this:

<?php
my_module_init() {
  dpm(menu_get_item());
}

For more details and examples, see What is the basic concept behind hooks?


Wich template to override for user account form I am building a theme for my Drupal 8 site and I want to create a custom profile page with user information like this: http://bootsnipp.com/snippets/featured/profile-card but I can't find the correct template to override where I can have access to all the information needed like username, name, picture and for example his address. Also I can't find where is the user-edit form to change the HTML so I can display it as I want.

I am new to Drupal 8 theming and that's why my question may look kind of no sense.
Thank you

EDIT (add more information)

So, I want to make my user's profile edit page to a two column layout where I can have the user base information like name and picture on left and on the right having the form to change the rest of the information like user and password.
What is the best way to achieve that?

use the native interface to add fields and change display

/admin/config/people/accounts/fields

/admin/config/people/accounts/display/full

if the html structure need to be changed , the template

  user.html.twig

can be override in the theme child templates folder.

As an exmaple for custom added individual fields, with fundation classes :

  {% if content %}

        {{ content.field_user_photo }}

        {{ content.field_user_name }}
        {{ content.field_user_status }}
        {{ content.field_user_email }}
        {{ content.field_user_phone }}

  {% endif %}


Pseudo-fields and custom entity properties from additional schema I'm trying to add property information to an entity which uses the entity API. Working from the commerce_product module I am trying to manage additional information outside of fields and in my own database that ends up attributed with the resulting product object when the entity is loaded. I've been looking into the hook_entity_property_info_alter and hook_entity_load functions to get the additional custom or "pseudo-fields" loaded. I'm having issues when saving/creating the new entity (product) and information submitted from the form is not accessible. Am I supposed to alter the form and tack on an additional form submit handler? During a call to hook_commerce_product_insert I was expecting the $product object to have form field values included that I could work with. What would be the recommended way to approach this? I want to end up with data from my own database schema added to the entity and be editable through the entity's creation/edit forms.

I found this relevant solution but that approach deals with editing the original schema which is definitely something I want to avoid.

You may have to override the form submit handler, or at a minimum add you're own submit handler in addition to the default. As long as the submit handler starts with an entity passed through the $form_state, you could add your own handler to fire before the final handler that saves the entity and set your properties there.

While I don't have a ton of experience working with entities and hook_entity_load etc, you may get more milage from extending and overriding the default entity controller for product and overriding the load, save, and delete methods.


Where to export i18n mode for menus in features? I'm using a combination of Entity Translation and Node Translation for a site and when I go and set up the menu, I need to edit each menu and select Translate and Localize.

Where is the feature to export this?

This is stored in the menu itself. Menu_links aside, the menu features wil be stored in some custom.inc file.


Displaying alternate text for a taxonomy term in node I have a taxonomy term called 'price'. I'd like it to display on the node page if it exists. But I don't want the taxonomy value to appear on the node page, I want the label to appear 'Price:' followed by hard-coded text that says 'see website.'.

Is this possible, and if so, how?

I don't want to use String Overrides because I'm using the value for the taxonomy term elsewhere. Perhaps some sort of code-based method (no pun intended) would work better :)

You can override the display your theme node.tpl.php template. Place something like this in your template.php...

function MYTHEME_preprocess_node(&$variables) {
   $variables['price_display'] = '';
   if(isset($variables['node']->field_terms[LANGUAGE_NONE]) && is_array(($variables['node']->field_terms[LANGUAGE_NONE]))) {
     foreach($variables['node']->field_terms[LANGUAGE_NONE] as $tag) {
        if(isset($tag['taxonomy_term']) && $tag['taxonomy_term']->name == 'price') {
          $variables['price_display'] = 'see website';
          break;
        }
      }
    }
  }
}

At this point you should have the variable $price_display available to print out in node.tpl.php.


How to make the module Node Embed work for any content type? I have installed Node Embed and created a content type called Text Page, and it works very well to embed nodes of all kind.

But I also have a content type called Article and there, no kind of node will be embedded.....I only get the [[(nid:number)]]. Both content types have the text field called: body; which is the long text and summary.

SOLVED!!! The body text was rendered through a view, and therefore it did not show the node embed content! So I changed it to "Node being viewed" Body....and there it was :)


How to find out whether or not a page is cached? I have some serious problems with the performance of my Drupal website and I think that the problem may caused by the fact, that the pages are not cached. How can I find out whether or not a page was cached and if not, how can I find out why the page is not cached?

I am using varnish for my page.

Whether a page is cached

You can enable logging and use varnishlog, varnishstat, etc. See Debugging Varnish for a bit more information. There's also a lot of information on Pantheon's Working with Varnish, I'd highly recommend reading that.

Why it is not cached

That's a much bigger, harder question to answer. It's entirely down to your server/application logic. Your server's VCL files, in conjunction with response headers sent from your Drupal application, will determine whether or not a page is cached.

There may be other environmental factors affecting things, but again those would be specific to your server and your sysadmin (or whoever installed/set up the server) should be able to tell you about them.

There's a pretty decent tutorial available that walks through setting up Varnish with Drupal, I'd recommend reading through that and comparing your own set up to that known-to-be-working one.


Which module creates the "Article" and "Basic page" content types? By Default we have two content types: Article and Basic page.

Which module creates those content types?

@Wim Mostrey was right.

In Drupal 7, the default configuration for modules (e.g. content types, field configuration, views) required custom PHP code to install and keep updated. In Drupal 8, these are stored with the configuration system in plain text YAML files, for example core/profiles/standard/config/install/node.type.article.yml.

References

Include default configuration in your Drupal 8 module


What to do for "Login attempt failed for admin." and "Access denied" to path admin? In Watchdog, I started seeing several entries like this:

  Login attempt failed for admin.

And

  access denied 2016/04/04 - 15:06  admin

These are generating a fair number of log entries.  The IP address is different for each request; they all geolocate to Russia.

Obviously, this is not me, and there doesn't appear to be any particular danger to my site, but is there a way to minimize such requests?

As an option you can rename path to login page, you can try Rename Admin Paths module to do it.


Ajax form content security policy Conversation around: how to set content-security-policy header read and noted

https://www.drupal.org/project/csp (Drupal 8 only) mentioned unsafe-inline is mandatory for WYSIWYG edits to work.

My question is that when I use a standard Ajax form with CSP enabled to default, I get the following upon clicking the submit button.

"Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'" Either the 'unsafe-inline' keyword, a hash ([redacted]), or a nonce ('nonce-...') is required to enable inline execution."

How can I add either a hash or a nonce to Ajax forms?

Do all Drupal 7 websites require unsafe-inline for any WYSIWYG fields to work? Is that likely to be fixable?

script-src 'unsafe-inline' is required by CKEditor 4 included in Drupal 8 core, so a newer WYSIWYG editor may not require it.  Drupal 9 will hopefully include CKEditor 5, which will not require 'unsafe-inline'.
CSP Level 3 also introduces the script-src-attr and script-src-elem directives, which can be used to allow only scripts in element attributes and not <script> elements, which will enable CKEditor 4 to work and reduce risk.

Drupal 7 also requires inline scripts be allowed for drupalSettings, though there is a patch available.

Hashes and nonces have some downsides and challenges

CSP Level 2 only allows hashes on inline <script> elements, not element attributes like onclick.  CSP Level 3 introduces 'unsafe-hashes' to allow hashes for attributes, but it can't really be used at this time because of a lack of browser support.
CKEditor 4 would require a 1.5KB CSP header for all of the hashes it would require.
Nonces are only applicable to <script> elements.
Nonces must be regenerated on each page load, preventing the page cache or other front-end caches from being able to cache the page.


views contextual filter based on NID that is selected from a list I have a slideshow in front page build by with Views and placed by Panels.

Currently i'm using contextual filter based on Nid and end user should enter Nids in Panels pane setting like "6,14,54,98" but it's not user friendly.

I need a list of nodes that end user can select nodes and the list automatically returns Nids.

You can use Nodequeue module for this. Quote from its project page:

The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

A block listing teasers for the five top news stories on a site
A user’s favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.


Form Alter Foreach Loop changes not sticking I'm trying to modify my exposed filter block to put each of the controls inside fieldsets, and make other modifications to them.

However, when I try to utilize a foreach loop to do this, none of my changes are 'sticking'.

foreach($form_state['input'] as $delta => $input) {
    $collapsed = (empty($input) ? TRUE : FALSE);

    $form[$delta . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $delta]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$delta . '_fieldset'][$delta] = $form[$delta];
    unset($form[$delta]);
    unset($form['#info']['filter-' . $delta]);

}

This wont work, but this will:

$delta = 'field_resource_type_tid';
$collapsed = (empty($form_state[$input][$delta]) ? TRUE : FALSE);

$form[$delta . '_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t($form['#info']['filter-' . $delta]['label']),
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
);

$form[$delta . '_fieldset'][$delta] = $form[$delta];
unset($form[$delta]);
unset($form['#info']['filter-' . $delta]);

I've been trying to find out why this wont work, but I can't for the life of my figure out what the form modifications wont stick when done inside this foreach loop.

I've finally managed to resolve my issue, but I'm not sure why. I decided to change what array I was using to iterate through the filter fields on my form. By switching to iterating through the form array instead of form_state, any changes I make to it now are sticking.

foreach($form['#info'] as $delta => $input) {
    $filtername = $input['value'];
    $collapsed = (empty($form_state['input'][$filtername]) ? TRUE : FALSE);

    $form[$filtername . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $filtername]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$filtername . '_fieldset']['' . $filtername] = $form[$filtername];
    unset($form[$filtername]);
    unset($form['#info']['filter-' . $filtername]);

}


Error 404 when upload image in profile installation I am installing a custom distribution, I have created a form:

my_distribution.install:

/**
 * Implements hook_install_tasks().
 */
function my_distribution_install_tasks(&$install_state) {
  $tasks = [
    "extra_configs" => [
      "display_name" => t("Extra configurations"),
      "type" => "form",
      "function" => "Drupal\my_distribution\Form\ExtraConfigsForm",
    ]
  ];

  return $tasks;
}

Drupal\my_distribution\Form\ExtraConfigsForm.php:

// more code ...

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#title'] = $this->t('Extra configurations');

    $form['logo'] = [
        '#type' => 'managed_file',
        '#title' => t('Load logo'),
        '#upload_location' => 'public://logo/',
        '#upload_validators' => [
          'file_validate_extensions' => [
            'png jpg jpeg',
          ],
        ],
        '#required' => TRUE,
      ];

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

    return $form;
}

// more code ...

Everything works fine but, when I get to that form and load an image I get an error in the javascript console, and i can't continue:

AjaxError:
An AJAX HTTP error occurred.
HTTP Result Code: 404
Debugging information follows.
Path: /core/install.php/%3Cnone%3E?element_parents=logo&langcode=es&profile=my_distribution&ajax_form=1
StatusText: Not Found
ResponseText: {"message":"No route found for \u0022POST \/core\/install.php\/%3Cnone%3E\u0022 (from \u0022http:\/\/my-distribution.local\/core\/install.php?langcode=es\u0026profile=my_distribution\u0022)"}

In watchdog i only see:

ID  Date          Type      Severity  Message
79  08/Oct 13:15  page not  warning   /core/install.php/%3Cnone%3E?element_parents=logo&langcode=es&profile=my_distribution&ajax_form=1&_wrapper_format=drupal_ajax

Drupal version: 8.5.7

What could be the issue?

Try add:

rewrite ^/core/install.php/(.*)$ /core/install.php$1;

to the config/nginx/drupal8.conf about line 16.

Adapting from:

https://github.com/kalabox/kalabox/issues/1767


Filter after Custom Field Type in Custom Filter I'm facing a problem with a custom field type in a custom filter. The field type isn't showing up in my filter-criterias in views. Do I have to tell the fieldtype somehow that it is filterable? Or is this a problem with my filter? I suppose the error is somewhere here:

function options_form(&$form, &$form_state) {
    parent::options_form($form, $form_state);
    $this->view->init_style();

    // Allow to choose all fields as possible.
    if ($this->view->style_plugin->uses_fields()) {
      $options = array();
      foreach ($this->view->display_handler->get_handlers('field') as $name => $field) {
        $options[$name] = $field->ui_name(TRUE);
      }
      if ($options) {
        $form['fields'] = array(
          '#type' => 'select',
          '#title' => t('Choose fields to combine for filtering'),
          '#description' => t("This filter doesn't work for very special field handlers."),
          '#multiple' => TRUE,
          '#options' => $options,
          '#default_value' => $this->options['fields'],
        );
      }
      else {
        form_set_error('', t('You have to add some fields to be able to use this filter.'));
      }
    }
  }

This is from my filter where it should show all fields, but does show only a few.

If you create a new field type, you need to tell Views about it. The hook in question is  https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7

Through entries in this hook you tell views how to build its SQL queries and render the results. Once you have implemented the hook you'll need to clear cache and hopefully you'll see your fields appearing in the list of filters. If the query/render requirements are not addressed by Views' existing handlers, you'll need to write your own. https://api.drupal.org/api/views/views.api.php/group/views_handlers/7


Cron issue with Drush 8 My Drupal 6 sites are hosted on a Linux server with Apache 2.2, PHP 5.5, MySQL 5.6 installed. I use Drush 8 which I installed via composer.
I set a cron job via cPanel which runs every day this script:

#!/bin/bash
# Script to execute all the cron jobs with drush
echo '**************** French site *******************'
cd /home/myuser/public_html/fr/sites/fr.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** English site ******************'
cd /home/myuser/public_html/en/sites/en.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Spanish site ******************'
cd /home/myuser/public_html/es/sites/es.mysite.com
/home/myuser/.composer/vendor/bin/drush -v core-cron
echo '**************** Completed **********************'

But it fails and ends with:

**************** French site *******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** English site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** Spanish site ******************
X-Powered-By: PHP/5.5.33
Content-type: text/html

Warning:  proc_open(): Descriptor item must be either an array or a File-Handle in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 434

Warning:  proc_get_status() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 435

Warning:  proc_close() expects parameter 1 to be resource, boolean given in /home/myuser/.composer/vendor/drush/drush/includes/startup.inc on line 436

**************** Completed **********************

The strange thing is that when I manually run drush -v core-cron on any site, the cron run ends successfully. I really don't know where the problem comes from.

I would suggest that instead of calling cd within your script, you either set up drush aliases or pass the --root and --uri parameters to the cron request.

/home/myuser/.composer/vendor/bin/drush -v --root=/home/myuser/public_html --uri=fr.mysite.com core-cron

That should make sure that drush is running in the right context.

You can also make sure that drush is running with the php that you would like by setting the DRUSH_PHP environment variable.


7 - Posting www links without http prefix I have a simple body field that uses an input format with only "Limit allowed HTML tags".

If I enter a link ... say Test
The node will transform the link's href to read http://www.mydomain.com/www.google.com

If I enter Test, it will work as expected.

Is there a reason why not including http:// causes this? Is there a way around it?

I was hoping Pathologic would solve this but it doesn't seem to have.

Thanks!

The issue is href="www.google.com" really is http://yourdomainandpath/www.google.com just as href="hello.htm" would be as well.


Multiple Values does not work when field widget is "Autocomplete term widget (tagging)" In Drupal 7, multiple values does not show for fields which are "Autocomplete term widget (tagging)"

Please look at the attached screenshot.

I'm trying to make 3 separate tags,
and want it to appear as the following:

Payment accepted:
Interac, cash, Watcard

But I'm not able to do so using commas. It works as plain text but I need it to be linked separate tags. Is there an easy solution to this? I'm new to drupal and don't really know much about coding.

Thanks for your help!

Change the field widget to "Check boxes/ Radio buttons"

For letting user select multiple values, go to Administration » Structure » Taxonomy » Your-Term » Manage fields, set Number of Values in Field Settings to "Unlimited"


No calendar showing on Rooms bookable unit - when clicking manage availability I am not sure what I have missed. I first installed BAT module,but later decided to instead use Rooms module. I am under the impression that Rooms will make use BAT FullCalendar , I could be wrong. Unless if there are some configurations needed. Or must I uninstall BAT completely and only use Rooms module with a normal fullcaleder module? I have checked permissions but could not see anything funny. See attached.
Thanking you in advance.

Rooms and BAT are separate modules, you should fully un-install BAT and then follow the Rooms installation instructions. Rooms depends on the fullcalendar library, but not the full calendar module.

  Within the Rooms module there is a rooms.make file which will download the library if using Drush or you can visit https://github.com/arshaw/fullcalendar/releases/download/v2.6.1/fullcalendar-2.6.1.zip to download it. The FullCalendar library should be placed in sites/all/libraries so that you end up with the file located here: sites/all/libraries/fullcalendar/fullcalendar.js

(quoted from http://docs.roomify.us/rooms/installation.html)


Is it possible to invoke cron within a hook or route class? I'm using the Deploy suite, which requires cron to be run after a deployment is created. However, when I try to execute \Drupal\Core\Cron::run(); from hook_entity_create() or from a route Class, it doesn't work. It dies after hitting $this->accountSwitcher->switchTo(new AnonymousUserSession());, throwing the error Using $this when not in object context in Drupal\Core\Cron::run().

Is this just simply not possible? Is there a way around these errors?

The reason why you get that error is because run is not expected to be called statically. \Drupal\Core\Cron is a service class managed by Drupal, registered in core.services.yml. To get a reference to the instance of this service, you'll need to inject the dependency to your controller.

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\CronInterface;

class MyController extends ControllerBase {

  protected $cron;

  public function __construct(CronInterface $cron) {
    $this->cron = $cron;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cron')
    );
  }

  public function myPage() {
    $this->cron->run();
  }

To call it from a hook, if you'll need to use \Drupal::service() to get a reference to the instance:

$cron = \Drupal::service('cron');
$cron->run();

A full example of how to manually run cron can be found in the implementation of the Cron settings page (Configure -> System -> Cron). In that page, you have a button to manually run the cron. See the runCron method, which is attached as the submit handler of the "Run cron" button.


UbertCart Cart does not follow my cart count I customized my cart link using Views to show the cart product count. It's not updating the count. However, the normal cart block that came with drupal 7 and ubercart (in blocks) shows the correct count of my products in cart.

The view FIELDS list contains:

FIELDS
Cart product: qty

then use the replacement pattern: Your cart contains [qty] item(s) within the views Rewrite Output of this field.

Not that my custom cart link does not update but it's erratic. Clearing the cache does not seem to also affect my custom cart link. While the normal view cart block is working fine.

I just needed to be able to customize the cart link to say something like 'Your cart contains 2 item(s)  VIEW CART on top of my website. and it seems it does not work though...

Anyone knows this issue?

The Ubercart block probably defaults to having DRUPAL_NO_CACHE set, while the view may have a different cache setting per default. Check the cache settings on the view?

May help for you to say whether this behaviour differs for logged-in and anonymous users.


Using a view to attach fields from a content type to another one I am a bit new to this, but I do have a programming background, and I have been working with Drupal for a while.

I am putting together a site for our Yoga Studio and I have a content type (scheduled class)  that has a field (field scheduled_class) that is a node reference to a content type (class description). The Scheduled Class content type has as field for date which is used in a calendar, and there are multiple classes using the same class description.

I am trying to use a view to attach fields from the class description to the scheduled class content type and I cannot get it to work. I have been banging my head against the wall for months now.

                               --> fields
Scheduled class --> Class Type --> fields
                               --> fields

I have not been able to get the contextual filter and relationship set up properly to allow this to work. I have tried every single combination I can think of. I am pretty sure the source of the problem is trying to get the right default value of the Class Type, but I am not sure.

What I would do:

Enable the query preview under Views settings.

Create a new View.
Make sure "Title" is a selected field, and that the titles of both "Scheduled classes" and "Class type" is available in the list.
Add a new relationship, pick the one representing your node-reference. Make it required.
Change the title-fields configuration to select the newly added the relationship.
You should now only have titles from "Class type".

From there on, you likely want to add a contextual filter on a nid so you can pick out "Class type" from a specific "Scheduled class".

I haven't used references in a while. If you get stuck already here, give the same thing a try with entity reference instead, just to see if it plays better together with Views.

Also see Learn Views with NodeOne, episode 11 is specifically about relationships.


Getting Views to use custom aliases I have the following custom URL aliases that point to specific Views paths:

/california/los-angeles maps to /locations/los-angeles
/username/listing/post maps to /item/post

Views still uses the older, pre-defined aliases. Is there any way to get Views to respect the custom aliases I've set? I'd need to do this at a global level, as there are too many paths to be changed in Views.

The Global Redirect module will fix this right out of the box.

Once enabled, it'll make sure there is only one canonical path available: your custom one. So all mentions of locations/los-angeles created by Drupal will be replaced with california/los-angeles, so that if you try to access locations/los-angeles it'll redirect to california/los-angeles.