Displaying multiple referenced nodes' fields through Views, using Views Slideshow I'm trying to build some image carousel functionality. To accomplish this, I've created two content types: Slideshow, and Slide. The Slide content type is what you would expect--a few fields that hold the content of the slide. The Slideshow content type's only purpose is to hold an ordered collection of slides in an Entity Reference field.

The advantage to this approach is that the use of an Entity Reference field means that the content administrator gets a drag'n'droppable UI for the ordering of slides, which is much nicer than some clunky integer weight fields.

So, having got that part set up, I scoot off to Views to work some magic with Views Slideshow. I create a view which calls up my Slideshow node and uses a relationship based on that Entity Reference field to get to the Slide nodes. With that, I can set up the fields of the slides how I like.

The last step would've been switching to the Slideshow view format and configuring the thing, but it was here that I ran into a problem. After I got things set up the way I thought they should be, I found that only the first slide's node was being displayed.

I did my Googling, and I found another question here on Drupal Answers that was similar to mine, which you'll need to read to understand the rest of my question. Reading through it, I tried out the solution that one kind soul provided, and it worked. But it required that I switch from the Slideshow view format to the Unformatted List view format.

So now it appears that I have a choice: I show all the slides as an unformatted list, which is not a slideshow. Or, I can show one of slides as a slideshow, which is not a slideshow.

This bums me out, because I thought I found an almost perfect setup. A content-manageable slideshow with an easy-to-use UI that didn't require the client to understand weight numbers and struggle through the tedium of setting them up. Can anyone help me jump over this roadblock?

I don't know if it's possible to do this with views_slideshow but I just created a patch for the field_slideshow module. It will be committed once I have tested it a little more or there is some feedback.

The Field Slideshow module page.

The issue with the patch.

And the documentation page: drupal.org/node/1495622

So once you have installed the dependancies and libraries here is how to download and apply the patch:

git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/field_slideshow.git
cd field_slideshow
wget http://drupal.org/files/entity_reference_support-1634412-3.patch
git apply entity_reference_support-1634412-3.patch

Then enable the module and go to your content type display setting page ( something like admin/structure/types/manage/article/display ). Here you should be able to define the format of the reference field to be a slideshow.


OR condition in Views Contextual Filters I have a Content Type named "Match" which has a local and visitor. Both are node references to a Content Type named "Team".

In Views I need to ask for matches of a specific team, no matter if that team is the local or the visitor. In contextual filters I can set a value for "local" and for the "visitor" each one in particular. So I guess I need an OR condition in this case.

Does anyone know how to solve that problem?

Edit: I found Views Contextual Filters OR module already but that's the problem, my website is too big and currently in production so we don't want to have problems because of bugs or something.

Drupal 7:

If using D7, then consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

A few issues on Drupal.org that may be of some help:

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

There is also this comment in the support forum.

StackOverflow.com contains yet another approach to consider as an alternative.

Maybe you should look at Alter a Views query to use "OR" through the user interface also (it might help to change change your mind about the Views Contextual Filters OR module anyway). Because 3,855 reports installs of that module is not nothing, right?

Drupal 6:

If you're still using D6, then maybe module Views OR is what you are looking for? Excerpt from its project page:

  By default, each record in a view must match all filters. Sometimes records need to be included if they match one or more filters in a list of alternatives. Views has the ability to combine filters only with AND. If one filter is false, the combined list will be false. Views Or adds the ability to combine blocks of filters with OR. If one of the filters in the block is true, the combined block will be true.

Note about the "my website is too big" ...

That's perfectly understandable. But that also implies that you should really invest in setting up some kind of testing / staging environment where you have like a mirror of your production environment. So that in THAT environment you can safely experiment / review / finetune what's needed, without impacting your production environment. And after you found the fix in that environment, you should have a process in place to actually MIGRATE it to the production environment ...

A pretty forward (simplistic) approach to this is to transform your existing production site into a multi site setup, whereas you do not change anything to the production site version, but you just add 1 (or more) sites like 'test', 'QA', 'User Acceptance Testing'. These extra sites mostly use the same code base (as production), but with their own copy of the Drupal database. And code changes (or extra modules to be added), first go in site specific subdirs. After they get approved, they are "promoted" to the "all" subdir.


Importing pre-built content into the site There are frequent installs of Drupal 7 that I do. All of them are almost the same, except, some need to have additional content types and modules on top of the default setup.
I'd like to ask if there is a way to modularize the deployment to save time on manually creating content types and installing modules.

Example:

(Required) I download and install Drupal 7 (possibly Drupal 8 in the future) with minimal profile
(Optional) I import a "magic package" (prebuilt) that would import all the custom content types I made, menu items, views and extra modules into the site created in step 1.
(Optional) I import a second "magic package" (also prebuilt) that would give site more capabilities with additional modules, menu items, views and content types.

some of the imported stuff is linked to Drupal users via Entity Reference fields.

What is the best way to accomplish something like this?
Is there a module that can help me build these "Magic Packages"?

Thank you.

Creating a feature could be what you need. Have a look at its project page. https://www.drupal.org/project/features


How to set up Apache Solr with facets so that it uses a front page search form? So I am working on my first mid sized D7 projects and it needs some rather advanced searching capabilities (at least advanced for me). I've installed Solr, created a server and an index with the Search API, and created a search page.
So far so good... everything works according to what you'd expect, and it even has facets, which is something I really wanted for this site. The problem is that this seems to be pretty much my ceiling... and I would like to change some things. For instance:

I would like to be able to search through my indexed taxonomies. Right now I can only search the node titles and descriptions and I have a bunch of taxonomies which is what I really want to search through.
I would like the users to be able to search from a search form in my home. Right now the core search is all I have in my front page, and if I want to use the Solr server I have to go to my search page. Ideally I want the user to enter a search term in the search form, to be redirected to the results page, and just there for him to see all the facets to further filter the results... linkedin style.

How would you guys accomplish something like that?

Edit:

Seems it seems I haven't stated clearly what I intend to do I'll try to upload some pics regarding point 1:

admin/config/search/search_api/index/node_search/fields

These are the fields I choose to be indexed!

admin/config/search/search_api/page/search/edit

If you see I can only choose "Title" and "description" from the fields to search from... so if I search for a taxonomy term which is not in any title or description, I get nothing. I would like to make the taxonomies in the first picture searchable... which is why I indexed them in the first place.

Edit 2:

I've finally managed to get the core search form to work with Solr following this tut(http://web3us.com/drupal6/how-create-web-site-handbook/apache-solr-drupal/apache-solr-3-drupal-7-turtorial-screen-shots) but I still don't know how to display the fields I want in the search results. Right now the results look like this:

And I would like each of them to look as the Teasers I've configured in my "Restaurant" content type (which are the nodes that I've set Solr to index)

Question #1:
Go to admin/config/search/apachesolr/settings and select 'Bias'.  There you can set up the weights next to the terms you want to search through.  Perhaps they're on 'Omit' or something like that...

Question #2: Go to the search settings page and make Apache solr search be your default search.  That way, when users type in keywords in your regular search form, they will automatically use your apachesolr search.
admin/config/search/settings

Let us know if that worked for you!


Content type creation with table of fields I want to be able to create a content type with a number of fields (naturally). One section of the content type needs to be like the attached image with the ability to:
 - group items together (e.g. an 'ingredient' in a recipe' - "2 cups flour, sifted"
 - link (via autocomplete) to existing nodes [INGREDIENT NAME field below]
 - add multiple items with a "more" button

Below is a screenshot from the 'Recipe' module. Is it possible to create this structure with CCK and can this be then added in a feature?

Use field collection to make a group of fields, then set that group to unlimited entries, simple.


Add html code to a content block I need to insert an html code into a content block.
As the html code has some javascript links and css, I've done a module to include all the references in the .info file.
The problem is that I don't know how to insert the html code in the .module file.

This is the html code:

    <link rel="icon" type="image/png" href="favicon.ico">
    <title>Aldizkari Elektronikoa</title>

  <meta charset="UTF-8" />

  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no">
  <meta http-equiv="cleartype" content="on">
  <meta name="description" content="Aldizkari Elektronikoa"/>
  <meta name="keywords" content="" />
  <meta name="author" content="" />

  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="assets/stylesheets/style.css">
  <link rel="stylesheet" href="assets/stylesheets/secciones.css">
  <link rel="stylesheet" href="assets/stylesheets/mediaQuery.css">

As you can see most of the code are references to javascripts and css. But what I need is to include the  to the module, because this is the part that shows what I need form my page.

Do you know if the is any hook for this? Or can I do in an other way to add this html structure to the content block?

I hope you can help me,

Thanks

You can always create a block in your module. You'll need hook_block_info, hook_block_view.

Example:

function hook_block_info() {
// This example comes from node.module.
$blocks['syndicate'] = array(
'info' => t('Syndicate'),
'cache' => DRUPAL_NO_CACHE,
);

return $blocks;
}

Then in hook_block_view:

function hook_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
  case 'syndicate':
    $block['subject'] = t('Syndicate');
    $block['content'] = myfunction();
    );
    break;
 }
  return $block;
 }

Then you just need to return what ever out put you want in myfunction, and you should be set. Check out the links for more info, full block api is also here.


Module with multiple Blocks in multiple files I've created a module which creates 2 blocks.

function my_module_block_info() {

  $blocks['blockA'] = array(
    'info' => t('blockA'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  $blocks['blockB'] = array(
    'info' => t('blockB'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );
  return $blocks;
}

function my_module_block_view($delta = '') {
  switch ($delta) {
    case 'blockA':
      $block['subject'] = t('subjectA');
      if (user_access('access content')) {
          $block['content'] = 'HelloA';
      }
      return $block;
      break;

    case 'blockB':
      $block['subject'] = t('subjectB');
      if (user_access('access content')) {
          $block['content'] = 'HelloB';
      }
      return $block;
      break;
}

Everything good so far. Here is my question:

I would like developers to create blocks using the same module (20 more blocks). How can I add a new block with its view without modifying the my_module.module? Is there a way to extend and include .php files that declare other blocks? So, instead of having a huge my_module.module file, I can have multiples .php files (one for each block).

Thank you in advance

* Method 1 - all blocks in separate file *

You can implement hook_hook_info() in your .modules file like this:

function hook_hook_info()
{
  $hooks['block_info']['group'] = 'block';
  $hooks['block_view']['group'] = 'block';

  return $hooks;
}

This tells the system that when hook_block_info() and/or hook_block_view() are invoked, any [MODULE].block.inc files should be loaded. So you can then put these two hooks into [MODULE].block.inc, keeping your block code in a separate file altogether.

* Method 2 - different file for each block *

You can add module_load_include() to include files for each block. To do this, in hook_block_view() you can do the following:

function hook_block_view($delta = '')
{
  if($delta == 'block1')
  {
    module_load_include('inc', 'MODULENAME', 'MODULENAME.block1');
  }
  elseif($delta == 'block2')
  {
    module_load_include('inc', 'MODULENAME', 'MODULENAME.block2');
  }
}

With this code, you can now put block1 in MODULENAME.block1.inc and block2 in MODULENAME.block2.inc. Note that MODULNAME should be the actual name of your module, though technically the module name isn't required, it's just a good practice.


drupal 7: how to add a field that displays a message when user is not logged in? I need a way to set up a field available only for logged in users. When anonymous user reach the page that contains this field, drupal must display a message that request to hte user to login or register to display this field. This is the same that appens for comments. There is a module that impelments this for single fields?

You can try the following 2 modules: Field Permissions and Markup.

Define the field.
Directly behind, define the markup field that shows the message to log in.
Use field permissions to allow access to the target field for authenticated users only.
Use field permissions to allow access to the markup field for anonymous users only.

That workaround should solve you issue.


How to use date_date_callbacks In Datetime.php from Core\Datetime\Element, I read:

#date_date_callbacks: Array of optional callbacks for the date element.
    Can be used to add a jQuery datepicker.

What does it mean? How am I supposed to add a jQuery datepicker from a PHP function? Right now I am doing from a JS file included as a library, but I'd like to keep my custom widget more self contained (I am developing a custom widget to select weeks using jQuery datepicker).

The first argument those callbacks get is $element which, essentially, is a render array as described in Render API overview. This means, for example, that a #date_date_callbacks callback could use code similar to the following one.

function mymodule_date_callback($element, $form_state, $date) {
  $element['date']['#attached']['library'][] = 'mymodule/mylibrary';
  // Optionally, the callback can pass values to the JavaScript code.
  $element['date']['#attached']['drupalSettings']['foo'] = 'bar';
}


How do I make a block that pulls the current node content? Ok, so I know blocks in Drupal 8 have these things called "contexts" which allow Core to clear cache on a fine-grained basis. I can't find any decent explanation  of how they work, or how to get page variables from them or whatever.

My goal is to have a block type that renders fields or a display mode of the current node into the block content. I have seen elsewhere how one would get the current node, but I don't entirely understand how it's supposed to feed back into cache contexts. I know #cache on render arrays exist, but there's also a bunch of methods from ContextAwarePluginInterface that I'm not sure what they do. Is there some documentation I'm missing?

There are two completely different kinds of contexts.

Cache contexts, which have nothing to do with this. They're not used to invalidate something, but vary by something (e.g. cache differently for different user permisisons). Cache tags are for invalidation.

What you mean are plugin contexts. And yes, blocks are able to use them since a short while (They always could, but the block.module didn't support it properly). As @larowlan said, core uses them mostly for visibility conditions but it works the same for blocks.

One such example that you can look at is the NodeType condition. What you need to do is add the context annotation and then you can use it as $this->getContextValue('node'). The advantage of this is that your block is more flexible and doesn't need to know where the node is coming from exactly, that's up to the user configuring it.

Note that this is not visible in the UI currently unless there is actually more than one node to chose from.


How to set defined image weight in Drupal I just now noticed this:

My uploaded image for article has more weight in kb as my uploaded original image;

I have set my GD toolkit image quality to 100% because I am compressing images myself as I wish (in IrfanView) ...

So, my original image is of dimensions: 549 X 803 58.1 kb

In webpage I see image of dimensions: 328 X 480 and 113.73 kb !!!

I expect the image to be of my defined weight ; or even smaller , if the size is smaller; but not larger....

If you've set the quality to 100% it's likely that that is why it's resulting in a larger file size. You may be setting it to a higher quality compression than the original photo had. You should try to find a balance between compression quality and image size that results in page load speeds you find preferable. However, if there aren't multiple images on this page, that might be an okay file size.


Add a twig variable to a certain href url menu item when it is being created I have a Drupal 8 install that I am trying to add a variable to a href  URL when it equals #blog but I can't get it to work. Can anyone see what I am doing wrong?

This is my menu template file:

{{item.url}}
{% if item.url == '#blog'  %}
    {{ item.title }}  /Tksksks iss
{% else %}
    {{ link(item.title, item.url) }}
{% endif %}

I just ran into this and have a late answer for you.  Your twig template's if statement does not work because your string comparison is against the Drupal Core URL object. You can, however, create a variable in twig and use that for your comparison.

{% set menuUri %}{{ item.url }}{% endset %}
{% if menuUri == '#blog'  %}
    {{ item.title }}  /Tksksks iss
{% else %}
    {{ link(item.title, item.url) }}
{% endif %}

This will let your comparison to the URL "#blog" work just fine.


how to create a view that filters on different fields depending on the content type How can I create a view that contains events and news and filters on the event date if the content is event, and the expiration date if the content is news?

I dont see where to choose both simultaneously in the filter criteria.

You can go to 'Filter Criteria' and hit the triangle next to 'Add'. Select 'and/or, rearange'  and you can change to OR instead of AND as well as add groups.


JCarousel Views - Multiple Rows My problem is related to Drupal and the use of the JCarousel module for my views. I'm having a few problems with this, namely in getting a jcarousel like view style but with 2 rows instead of one. With the following jcarousel-view.tpl.php in my theme folder, I was able to somewhat get further:

<?php
  /**
   * @file jcarousel-view.tpl.php
   * View template to display a list as a carousel.
   */
?>
<ul class="<?php print $jcarousel_classes; ?>">
  <?php $i=0; $rows_number=2; //you can change the number of rows ?>
  <?php foreach ($rows as $id => $row): ?>
    <?php if ($i % $rows_number == 0): ?>
      <li class="<?php print $classes[$id]; ?>">
    <?php endif; ?>
    <?php print $row; ?>
    <?php if ($i % $rows_number == ($rows_number - 1)): ?>

    <?php endif; ?>
    <?php $i++; ?>
  <?php endforeach; ?>
  <?php if ($i % $rows_number != 0): ?>

  <?php endif; ?>

Here is the end result:

As you can see, it groups each set of fields for each item into a common column and not separated, so I cannot create a full border for each individual item.

How can I resolve this?

1) Hide all your fields (check mark exclude from display)

2) Add a Custom Field

3) In your custom field, put everything there using the tokens. (click on relacement patters, it will show you the tokes u can use).

For Example:

[logo]

[off]

[download cupon]

[expires]

Then go to the jcarusel module folder and look for the css file and strip the css that you don't want (like the current borders) and use your "whatever" div to create your own borders.


How to output Get Locations coordinates as a separate field? I have Get Locations module enabled, and I would like to output the coordinates of a given location as a separate field (longitude, latitude) when displaying a given node.

Somehow like this:
GPS: 45° 59' 45.24" N, 18° 40' 47.28" E

What's the best solution to do this?
Should I use Display Suite + "Add a code field" or is there a better solution?

Check out the geofield module. Even the Get Locations module supports it.


How to clone a content type? I want to clone a node type and add a few fields in it. I think the simplest will be to duplicate it and start working on it.

It seems there is no official way to clone a content type in Drupal 7. Features may allow it but there is no written procedure as to how it could be done.

I've even tried Bundle Copy module.

What'll be best way to clone any content type in Drupal 7?

The easiest way is to use the Bundle copy module, but if you can't get that to work I'd recommend the Configuration Management module.

  The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.

It's basically features with the stuff you don't need. Its sole purpose is to move configuration from one site to another.


Master page and details page for Views I have created a new content type and I called it Opinion. Then using views, I have created a page with path /opinion to be a view for all nodes of type Opinion listing i.e. a master page.

The problem is that I could not able to access a the details something like /opinion/the-node-title. however, It accesed like content/the-node-title

I tried to create a new page from the regarded view with contextal filter Content title it works fine using direct access from the browsers address bar. I tried to rewrite the content on the linked title field but I could not able to find a suitable token:

[title]---

i.e I could not find any way to convert title into a slug.

Another thing for SEO, I don't want the same content to be accessed from more than one resource i.e in my case content/the-node-title and opinion/the-node-title

You need to use pathauto module and configure URL alias >> patterns >> content paths set opinion/[node:title] path alias for opinion content type. All content path for opinion now change as your requirement.


Image style don't create thumb image and it get error "Division by zero" My site is Drupal 7.36
Image style cann't create all images and it get 2 error messages

Division by zero in theme_image_style_preview() (line 804 of /Users/snappy/Sites/betterpack/modules/image/image.admin.inc)
array_intersect_key(): Argument #1 is not an array in theme_image_style_preview() (line 806 of /Users/snappy/Sites/betterpack/modules/image/image.admin.inc)

and I did:

sudo chmod -R 777 sites/default/files/styles

It not work
Help me please.
Thank you everyone and sorry I write weak in English but I can read good English.

ls command in sites/default/files/styles

ls -l
total 0
drwxrwxrwx  3 _www  staff  102 Jun  7  2014 cover_article
drwxrwxrwx  3 _www  staff  102 Mar 28 19:47 cover_product
drwxrwxrwx  3 _www  staff  102 May  9  2014 large
drwxrwxrwx  3 _www  staff  102 Jun  5  2014 medium
drwxrwxrwx  3 _www  staff  102 Jun  6  2014 node_porduct
drwxrwxrwx  3 _www  staff  102 Jun  6  2014 related_product
drwxrwxrwx  3 _www  staff  102 Jun  7  2014 thumb_gallery_article
drwxrwxrwx  3 _www  staff  102 May  9  2014 thumbnail

It would appear that your image toolkit is not working properly. On the status page (admin/reports/status) are there any errors, etc.?


How do I use inline CSS in "Global: Custom text"? My scenario:

a field (color_field) to enter a color code (ie: #fafafa)
in Global: Custom text in Views use the token of color_field to generate a border color (is: style="border-color: [color_field]")

Then, I must display for each row a different border-color and the color code is generated with a color picker in color_field when add a new node.

Unfortunately the inline CSS is stripped from Global: Custom text in Views.

How I can use inline css in Global: Custom text in Views?

Or have I to change approach to my scenario?

I've solved overriding view-view-field--field-myfield.tpl.php and in template file I've used color from $row variable.

<?php
$title = $row->field_field_myfield[0]['rendered']['#markup'];
$color = $row->field_field_myfield_color[0]['rendered']['#markup'];
?>
<h3 style="border-color: <?php print $color ?>"><?php print $title ?>


When is the filter value available to a context filter in a view? There is very odd negative grammer for setting up Context filters in views.

I set a context filter to take a value from the URL (perhaps context filters are primarily for something else?)

However when I go to set it up I need to put my details into the field labelled

WHEN THE FILTER VALUE IS NOT AVAILABLE

This seems very odd to me, could someone explain to me When the filter is available?

I may not be making any sense but then again neither does that page!

At the very top of the contextual filter configuration window you have:

  This display does not have a source for contextual filters, so no
  contextual filter value will be available unless you select 'Provide
  default'.

The answer to your question When the filter is available? is short:

The filter is available only if has been provided.

Let say, you want to show a block with the content that depend on node id. Obviously you don't want to provide the node id by yourself on each node to see what the block content is. You don't need to provide it, because the node id is in the URL, so it's available. Of course the node id is not always in the URL, for example if you're viewing a user profile or a list of recently added articles. That's why this fieldset has been labeled:

WHEN THE FILTER VALUE IS NOT AVAILABLE

In this fieldset you can decide what to do when the filter hasn't been provided (display all results? provide default? .. many options there..)


Drupal 7 use custom layouts created by Panels module I have recently installed the Panels module. It allows me to create custom layouts for my contents. I now want to choose these template layouts while creating/editing a certain type of component so that when viewed that content appears in the selected layout.

I am a newbie in Drupal and more so in the Panels module. So not really sure if my requirement is feasible in the first place.

You are probably looking for Panelizer; use it along with the panels in-place editing tool

From the module's project page:

  The panelizer module allows you to attach panels to any node in the system. It is similar to the panels_node module that ships with Panels, which provides a single node type that is a panel. Panelizer, however, allows this to work for many entity types. It works by using the Page Manager template to take over the page rendering of the node. In Panelizer 7.x-3.0, you can also panelize view modes. The old-style "Page Manager" implementation is treated as a specialized view mode.


Disable taxonomy terms in certain contexts or split into different vocabularies? I have created a taxonomy of regions, with the intent of multiple uses:

Users select their region in their profile
Events include a region field.

This should make it rather easy to show users events in their region.

Each of these use cases requires one or two extra terms:

Users might be from "outside New Zealand".
Events might be "Nationwide", "Worldwide" or indeed "online".

But we don't want events outside NZ submitted, and the latter three terms are not appropriate for users to choose as their location. So I want to disable them from the listed options in each case.

I thought there might be a CSS solution as there are ample distinctive selectors available in the parent elements, but Drupal does not assign any classes to option elements - they only have a value, and the numeric id of the taxonomy term at that.

Is there a way to do this using Rules or Context?

Alternative 1
Create two different taxonomy vocabularies:

Events
Users

since the use cases for each are different.
To create another taxonomy vocabulary easy and fast, you could export your existing terms and then import them into a new vocabulary. This could be done with some taxonomy bulk import/export module, maybe with https://www.drupal.org/project/taxonomy_csv or with https://www.drupal.org/project/taxonomy_manager
Alternative 2
Added to this answer after OP's first comment.

Keep the Events and Users together in one vocabulary, EventsUsers.

Create another vocabulary, EventUserType. Add two terms:
Events and Users.

Add a Term reference field with Check boxes/radio buttons to the EventsUsers, save. In the next
configuration pages choose vocabulary EventUserType. Also change the Number of values
from 1 to Unlimited.

Now all the terms in the main vocabulary can be tagged as Event, User or both.

The filtering could be done using the Views module, but I guess that would be a separate question here on Drupal Answers.


why does commerce pricing rule increase price before decreasing price? I created this simple rule to give authenticated users 50% discount.  The individual line items are not being changed as I would expect, only the order total.  And before the order total is discounted 50% it's actually doubled in price, so the order total does not actually change from what it would be without the rule.

Subtotal, discount, and total are all double what they should should be.  I have no idea why.

Here's there rule:

{ "rules_wholesale_discount" : {
    "LABEL" : "Wholesale Discount",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2", "3" : "3" } },
          "operation" : "OR"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_multiply" : {
          "commerce_line_item" : [ "commerce-line-item" ],
          "amount" : "0.5",
          "component_name" : "discount",
          "round_mode" : "1"
        }
      }
    ]
  }
}

Answer: It doesn't.  The checkout page just makes it look like that because all those line items have already had the discount applied to them and the view does not show that.

So my new questions are:

How to display original price on the product display? (Because only the discounted price is shown to authenticated users)
How to display the original price in the cart and checkout forms?

But original question answered.


How to limit the terms of the view to the terms used? On the product I created a "tags" taxonomy terms field. I have created a hundred "tags".
My products use around 10 "tags".
I created a pageview of my products with an exposed filter criterion "tags".
My problem :
The filter displayed on the product page displays all the terms. I only want to display the terms used by my products. How to do this ?

If doing it manually is acceptable you can do it on the Exposed Filter Settings by ticking the Limit list to selected items and then selecting only the 10 tags from the list above (hold Ctrl key to add to the selection). This works if you'll always or for long periods of time need only those 10 tags.

If you want Views to filter automatically and only show what's within the results without you having to choose the tags manually you have to use the Contextual filter instead of the Exposed regular Filter. Contextual filters are under Advanced options.
Add the Contextual filter for the same field "Tags" and configure it:
When the filter value is NOT available
Display a summary
Format List
Base path (you must enter the Page path if this isn't the first Page Display in your Views)
Display record count with link
More
Transform spaces to dashes in URL
Adjust the options for when the value is not available to your needs (Tags Taxonomy term etc.).
This way you get a list of term IDs that link through to a list of nodes tagged with those terms. That is because the Tags field only stores the TID information, not the term name. When you first load the page you only see the Summary, no results, you have to click through to see the results. But if you create the Summary as Attachment on a Page Display you can get it both ways, the Summary and the Results at the same time (keep the path the same).
But you probably want the term name to be displayed instead of the term ID. In that case remove that Contextual filter, and add the one for Taxonomy term Name, but you need a Relationship first for that information to become available.
Add a Relationship Taxonomy term referenced from field_tags (or whatever the field is called in your case), require it becasue you don't want summary results without tags!
Then add a Contextual filter Name from Taxonomy term Category, it will use the Relationship we created, and configure it like the above Contextual settings.

Alternatively you can use an additional module, this one did it in D7 but not yet ported to D8: Views Selective Filters.
Facets module provides an easy filtering interface from what's in the results.


How can I limit users to one account each? (Or, how can I detect users who have multiple accounts?) For various reasons I would like to limit each individual user to registering/using only one account.  I realize that there is no perfect way to do this, but what can I do within Drupal to detect cases where users have registered and are using multiple accounts?

I plan to set up a view using uiplog to check whether the same IP address is logging out and then immediately logging in to another account, but what else can I do?

Additional information: The site I am working on requires users to complete a fairly lengthy registration form and then additional information on the first time they log in.  As such, I'm primarily concerned about users with multiple accounts trying to game the ratings system within the site.  (Abusive users will be handled through an abuse reporting system.)

You can not. Only limitation is Useraccount with one Emailadress. But if the same User Logs in with a different name and a disposable email adress, you can not verify if it is the same User. Something like undisposable will help. But it's not the solution.

Also if 200 Users use the same Proxy/same IP, you will limit them.


Add html widget programmatically to the list “Add fields” in views in Drupal 7 I'm trying to create a html widget that will be available in all views. I would like to have the widget available in the list "Add fields" in views.

The module Easy social have this functionality, but I can't figure out how they did that.

So how can I from my module programmatically add fields to the list "Add fields" for views?

Any help appreciated.

This documentation will help you, just add a field handler then you are done! Click here


How to fetch views field label in hook_views_pre_render? How to fetch views field label to modify in hook_views_pre_render ?

  function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'mytype'){
    // Here I want to fetch the field label but I am not getting how to fetch field label
  }
}

Try $view->field[{field machine name}]->options['label']

The $view object has a property 'field', which is an array of all fields set in your view. You need to select the one labeled 'Name'.

Each field is listed using its machine name as key, hence {field machine name} as a placeholder. You need to replace that with the actual machine name.

The field in that list again is an object, with a property 'options'. This is an array of all options, including alterations, whether the field is excluded or not, etc. In those options is also an index called 'label', which contains the field's label.


Is it possible to use mixed LDAP and local Drupal authenticated users on the same site I have a site in which site editors and administrator need to login using LDAP authentication.  However, the site also will have regular authenticated users, who can register for an account directly through the standard new user registration form.  I was wondering if it is possible to configure a Drupal site so that regular users can use the standard Drupal authentication process, but site editors and administrators can LDAP authentication?

I see that the LDAP module has a mixed mode setting in which it will use LDAP authentication if local authentication fails.  I would assume in such a situation, any users that registered for an account through the standard create new account form would have a local account and thus would be authenticated locally.  But how would it work with creating a new editor or administrator account?  Is it the case that I just need to add them to the LDAP server, after which they be automatically added to the Drupal system?

Any accounts created through LDAP will have access to the site. Alternatively you can create local Drupal users that also have access when using mixed mode.

For instance I work with sites where I have LDAP credentials that allow me access to all the sites. I also had a local Drupal user for one or two that have different credentials and I can log in with either (same email).

Depending on what modules you are using to facilitate this process they may even create a local user for each LDAP user (not sure if they all do this or not). This comes in handy when experiencing LDAP issues as you still have access to your site/s.


Creating Routes to deal with a form So I have created a block in which I've added a form, build with the form API. It contains a textfield and a submit button. My next step is to create a route that calls a method in a controller in my Module.

I am wondering how to do this. The form itself part of the main menu, so visible on any page. I'm not sure how to define this route. I've read there are form routes, but I don't think that's what I am looking for.

The Drupal Form API documentation says something like this:

module_search.form:
  path: '/'
  defaults:
    _title: 'Search form'
    _form: 'Drupal\module_search\Form\SearchForm'
  requirements:
    _permission: 'access content'

But I have no clue how to handle the request itself to do something with the data this form provides.

If you want a form in the main menu of every page, you don't need a route for it.  You can just create a block, either for just the search form or for the main menu, and load the form in as a variable into that block.

namespace Drupal\module_search\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Header Search Block Form' block.
 *
 * @Block(
 *  id = "header_search_block",
 *  admin_label = @Translation("Header Search Form Block"),
 * )
 */
class HeaderSearchFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
    return [
      $form,
      '#cache' => [
        'contexts' => ['url.path', 'url.query_args']
      ],
    ];
  }
}

What you're returning is a render array, so you might want caching settings on there, otherwise, you can just return the form itself.  If you want to prefill the search term on every page, you'd want a cache context that includes page arguments, like above.  If you want the fields empty, such as if your form only contains a textfield for searching, then you don't need a separate cached version on every page and you can just return the form in your build() function:

  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
  }

Another option, you can preprocess your main menu block to add the form as a variable as well.

function mymodule_preprocess_block__system_menu_block__header_menu(&$variables) {
  $variables['search_form'] = \Drupal::formBuilder()->getForm('Drupal\module_search\Form\SearchForm');
}

then in your block template (such as block--system-menu-block--header-menu.html.twig)

add

{{ search_form }}

As far as redirecting to search, my preferred method is with javascript, as you don't need to hit the backend.  You can just redirect to your search page from the javascript.

Just attach the javascript library to your form

$form['#attached']['library'][] = 'mymodule/mymodule.header_search';

(etc.  there are many tutorials on this)

and then in the javascript do something like:

 $('#' + formID).submit(function(e) {
   e.preventDefault();
   var filters = self.gatherFilters();
   var url = searchURL + '?' + $.param(filters);
   window.location.href = url;
 });

If for some reason, you need backend processing, your form can have a submitForm method that then sets the redirect on the $form_state object:

$query = ['keyword' => $search_term];
$form_state->setRedirect($route_name, [], ['query' => $query]);

with $query being an array of query arguments.

For your search results page, I would recommend you create a different search form.  As a small textfield in the header is different than filters on a form.

Without custom coding, you could use a Drupal view page, and set a contextual filter set to keyword, or you could create a controller in your custom module that returns a different search form with filters as well as the results from Elastisearch.


Some pages hide content unless "Read more" is clicked If I have multiple pages on Drupal, some show the full page, and others say "Read more" and will only show the whole page when it is clicked. It doesn't seem to have anything to do with the size of the content of the page or how long it is. What's up with that?

What you're probably looking at is a "View". This view is probably showing a list of "Content" (nodes).
Now each node is probably being set to render in "Teaser" view mode. But since some of your node types (article for example) doesn't have a "teaser" view mode configured, it shows the "Full" (or "Default") view mode, which renders the "whole" thing.
What you need to do is find the View Mode that your content listing View is using, the Node Type of the content that's showing up as Full, (for example 'Basic Page'), then go to:
Structure > Content Types > [Content Type you want to configure] > Manage Display
And configure the view mode that your View is using to display the Read More link, show the body text as "Summary or Trimmed" etc.


Is there an Authcache load event for fragments? I would like to create a callback javascript function to fire when one of my Authcache fragments is loaded via AJAX. Is there a way to hook into this event?

Thanks.

If you register your JavaScript as a behavior, then it is executed whenever the DOM changes, also when a fragment was loaded by authcache (see Managing JavaScript in Drupal 7). For example, the proper way to process any view - regardless of whether it is loaded via Authcache or not works something like this:

(function ($, Drupal) {
  "use strict";
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.view', context).once(function () {
        var view = $(this);
        // do something with view.
      });
    }
  };
}(jQuery, Drupal));


How do you add validation (constraints?) on a paragraph? Compare two fields How does one go about adding validation (contraints?) on a paragraph?

I need to compare two entity reference fields on submission. If one field has a certain entity referenced, the other cannot have certain entity references.

I'd be interested in restricting the autocomplete options as well, but that simply won't be enough as I need to ensure that they user doesn't manually enter another entity value.

You simply inherit from the the default EntityReferenceWidget and you will call it like MyParagraphEntityReference widget. You can here both change the way how the autocomplation works and also how you validate the entered data.

This is page may help you.


How can I detect a "page's" content type? I have begun work on a Drupal website and unfortunately I did not have an opportunity to have them walk me through the website as is.

I'm now trying to replicate content from a development site to a live site, but there is a page which I cannot identify as a particular content type, though I know it is content, because it says on the page "Clone Content."

How can I figure out this page's content type so that I can replicate it? Is this the right question to be asking?

I apologize if this is an ambiguous question, I will clarify any detail needed.

As a side note: Is there any way to clone content between Drupal websites? Like exporting and importing? Perhaps a tutorial I should check out?

Thanks so much in advance.

A few quick answers to your questions:

If you view source on any page, you should see a class name on the body element, something like: node-type-article. This is one way to see the content type. Also, if you edit a page, you'll see that the edit title will look something like this: Edit [content type] [title]
Alternatively, navigate to: [domain]/admin/content to see a list of all content, which includes the 'type' column
The "clone content" link content comes from a module called "node clone" https://www.drupal.org/project/node_clone, designed to allow in-place duplication of content (fields that should not be duplicated are reset to safe values)
There is another module that will allow you to export/import nodes between drupal installs: https://www.drupal.org/project/node_export It's probably not worth it to get into this unless you have quite a lot of content to move.


Editable webform submissions Requirements for user submissions are:

anonymous user is able to submit form data
admin can delete any submission
admin can edit any field of any submission
form can contains fields which are not displayed to user, but admin can edit them
admin can sort and filter the submissions according to one field (date type)

There is webform module, but I do not know if it can solve all those requirements (the first one is OK, ofc ;)

Webform is not necessary for the tasks you've outlined.

Simply create a content type, and grant the Anonymous user role access to create content of that type.

To have 'hidden' fields which the admin can still edit, you can either hide those fields with CSS, deny access to them via the #access property through a hook_form_alter(), or use the Field Permissions module to restrict access to those specific fields. Note that the Field Permissions module has some performance implications.


add three triptych side by side i have made a custom theme "Custom_stark" and
made changes into .info file and added the triptychs

regions[triptych_first] = Triptych first
regions[triptych_middle] = Triptych middle
regions[triptych_last] = Triptych last

in Custom_stark.info.

But when I see with block " Demonstrate block regions (Custom_stark) "

i can see only in this default format.

And how can i get the triptych in desired format mention in below image

And below is the code for page.tpl.php

<?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

      <?php print render($page['triptych_first']); ?>
  <?php print render($page['triptych_middle']); ?>
  <?php print render($page['triptych_last']); ?>

Try this

 <?php if ($page['triptych_first'] || $page['triptych_middle'] || $page['triptych_last']): ?>

            <?php print render($page['triptych_first']); ?>

            <?php print render($page['triptych_middle']); ?>

            <?php print render($page['triptych_last']); ?>


LESS could not create a directory in public: I am creating a site with drupal 7.15 with bootstrap and using less. But when i reload the page i found the following errors. (dope is my sub-theme name)

LESS could not create a directory in public://less/51761ea74e5068.61766466/sites/all/themes/dope/less
Warning: Invalid argument supplied for foreach() in drupal_pre_render_styles() (line 3311 of /home/seat3/public_html/DOPE/drupal/includes/common.inc).
Warning: Invalid argument supplied for foreach() in element_children() (line 6300 of /home/seat3/public_html/DOPE/drupal/includes/common.inc).

Your drupal site files directory has to be writable by your webserver.


Ajax field in products page I have downloaded the Commerce Kickstart distro. In the product page there is a quantity field which you can use to enter your custom value; I want to display the total cost of current product in AJAX. Is it possible?

There is no such default functionality in drupal commerce.

Commerce Cart Ajax

This module will ajaxify your cart page. If you need this in product detail page then you can build a custom module for that with Ajax Api in Drupal 7


jQuery Star Rating Plugin in drupal 7 Our customer wants to have this plugin within drupal: http://www.fyneworks.com/jquery/star-rating/#tab-Testing and I cannot get it to work.

The basic code works, I can create stars and have them display a stored value.
However, I want to use the callback functionality and this is not working, not even when I copy the test code from the site above to a blank page.

There are no stars (just radiobuttons), when I add star as a class I can see the stars again but then the callback will not work (as mentioned on several pages).

I figured it might have something to do with the version of jQuery so I installed the jQuery Multi module and the most recent jQuery (1.7.2) and enabled that for the star rating plugin, but this did not help. Any tips on how to proceed/debug?

I am no jQuery expert, I tried looking at the plugin code to see if something was missing, but could not understand it and nobody else complains about this not working (except if they did something wrong with the callback functionality).

edit:
I failed to mention that the entire page is constructed from php ignoring drupal things like blocks or nodes, this makes it hard to use the 5-star module. This was not my choice and a very bad way to use drupal, but that is what I have to work with, unfortunately.

With help from Lennert at gettingsocial.nl I was able to solve this. The trick was to not use the drupal method to load the jquery.rating.pack.js as the script needs to be loaded after the checkboxes have been added. (the drupal_add_js() function will put it in the header).


How to update the current page to show new content? I am currently displaying a list of MySQL database table names, such as table1, table2, table3.

Each table name will be a link; if users click on it, it will display them the data contained in that table.

One way I know I can do this is to create a Drupal page that contains the content of "table1", so that when a user clicks on "table1", they are taken to this page and can see the data of "table1".

However, this soon becomes un-manageable if I have a large databases with many tables.

I'm not quite sure if Drupal can work in this way, but I would like it so that when a user clicks on a table link (either table1 or table2 and so on), the current or a generic page will then be updated with the content of the table chosen and be updated with its content.

I am not sure what functionality you are trying to build and if adding PHP code inside a Drupal node is the right way to do it. But assuming that is what you would like to do, here are the steps to achieve what you want:

Create a Drupal node (say the nid of it is NID) and add the following PHP code inside it

$table_name = arg(2); // This grabs the 3rd argument of the page menu path (note: the 1st argument is indexed 0)
print $table_name; // Replace this with PHP code to fetch and print data in the table represented by $table_name

When you are making table1, table2 etc links make sure the URL that they point to is node/NID/<table_name> where <table_name> is table1, table2 respectively.


How do I pass variables to a view builder's renderer? I'm creating a module that will render a few nodes before getting back the result and print it as PDF. (I can't use wkhtmltopdf; I wish I could.)

So far, I managed to make my controller/action use the template I wanted, and anything I write in the template file is showed with die($html). However, I can't find any example of how to pass variables to the view; I tried a few things, but I got nothing, excepted 500 errors.

This is the code I am using.

public function nodeAction(NodeInterface $node) {
  // Here, I define a variable named $responses that contains a lot of datas as arrays
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
  $build = $view_builder->view($node, 'cnas_pdf');
  $html = \Drupal::service('renderer')->renderPlain($build, ['var' => $response]);

  // No error in this configuration, but "var" is nowhere to be found
  die($html);
}

This is not possible to add parameters to renderPlain(). What you can do depends. If you want to use a variable inside of the node, then do this in a node preprocess hook. But more likely you want to add additional elements to the build array before you render it, for example:

$build = [];
$build['top'] = ['#markup' => 'abc'];
$build['node'] = $view_builder->view($node, 'cnas_pdf');
$build['footer'] = ['#markup' => 'xyz'];


What is the replacement for menu_link_load()? Drupal 7 has menu_link_load() to load a single menu item. What is the Drupal 8 equivalent?

Drupal 8 menu links are now content entities. The equivalent to loading a D7 menu link object would be loading a MenuLinkContent entity. This can be done via the static Drupal\menu_link_content\Entity\MenuLinkContent::load() method.


Commerce Feeds failing to import due to missing bundle property I have a fresh install of Commerce Kickstart, and using the Commerce Feeds module to import my list of products from a CSV.  I mapped my fields (sku, title_field, commerce_price:amount, field_commerce_saleprice:amount, and product_id) to the fields in my csv.  I am using a CSV parser, File upload, and attaching it to a standalone form.  When I process the import of either 1 item, or my full list (474 items), none of them import due to the following error:

Missing bundle property on entity of type commerce_product

Here is the entity from the log:

Entity

(object) array(
  'type' => 'product',
  'product_id' => '588',
  'is_new' => FALSE,
  'sku' => '052-001-014588',
  'uid' => '1',
  'status' => 1,
  'created' => 1447383612,
  'changed' => 1447383612,
  'log' => 'Created by FeedsCommerceProductProcessor',
  'revision_timestamp' => 1447383612,
  'revision_uid' => '1',
  'original' => FALSE,
  'title_original' => '',
)

I can't seem to figure out why they won't process and import.  Can anyone help?  Let me know what information you'd like to see.

So, apparently this may be an issue inside of the importer, but what is happening was I was trying to map product_id on to product_id when there was no such field within the product itself that was mappable.


Adding Additional login security Considering login security for user logins, I would like an additional option such as a PIN option for all aspects of user login. This seems quite common now across a number of portals out there such as personal banking, social security/gov. tax sites and I would like possibly to offer this as an option to those who do not want to use Facebook, Twitter etc logins which I use on my projects. I appreciate it could simply be an additional field in the system config, but I would be keen to hear any comments on such features, or possibily a popular D7 module which most people use which for me as a Drupal 'plumber' can just drop in for easy of setup, or a generalistic 'how-to'.

Thanks in advance.

Is there an existing "pin" login module?

I'm not aware of any module that does this itself. There are some pin-related modules, but most of them are related to using 2-factor authentication authentication.

Is a pin field actually useful to improve security?

My sense is that adding a pin would not be worth it.

First, pins are easily guessed: this article on commonly used pins shows how only 20 pins would break over 26% of accounts!

Second, if you were to just require the pin to be on the end of the password that actually makes it harder to break than making it a separate field because they would both need to be cracked at the same time rather than serially. That is in addition to the problem above of pins not being well distributed among the 10^4 potential combinations.

Third, you would have to build, audit, and then maintain this additional code for managing per user pins. That's a new database table, some form fields, and at least a few hundred lines of code that can be buggy that overall adds very little extra security.

Alternate improvements to login security

So, I have some other suggestions on how to improve login security in general:

Security Review offers brute force detection.
You could use one of the 2-factor authentication modules. My favorite way to do that is the tfa module which is the module deployed on drupal.org.
You could use a module to improve true password strength (vs. password policies that usually promote nonsense).


view of unformatted list invalidating cache issues I have a view that shows the title of a single content type as an unformatted list. I have an argument for a nid-contextual filter that I pass to the view in

function modulename_views_pre_view($view, $display_id, array &$args) {
 ....
 $args[0] = $filter_value;
 }

The value for the contextual filter is a value the user can select and is set in \Drupal::service('user.private_tempstore'). Every time the user selects a different value from a select form element, the view should show different results. However, it caches the output and only if I clear all caches it shows the correct output. But if I format the view output as a table, then everything works totally fine and the new results are shown immediately.

The cache tags for this view are given as follows:

print_r($view->getCacheTags());
Array ( [0] => config:views.view.users_in_class [1] => node_list )

Do I have to specifically invalidate something here or am I missing something else ? I thought that the cache tag node_list would already be enough. And why are results being cached when having the format as an unformatted list?

The cache tag node_list only works for database changes in the node table, but this is not happening when the user selects a filter value.

This is from the point of the View a cache context. So if you don't find a way to configure the View to handle this correctly, you could assign a custom cache context for the filter value.

The whole picture, which the View can't know because you provide only the filter value to it, is a mix of tag and context. You would need a cache tag for the private tempstore and a context for the current user to get the caching right:

function modulename_views_pre_view($view, $display_id, array &$args) {
  ...
  $uid = \Drupal::currentUser()->id();
  $view->element['#cache']['tags'][] = 'users_in_class.' . $uid;
  $view->element['#cache']['contexts'][] = 'user';
}

and then invalidate the tag when changing the private tempstore of a user $uid:

Cache::invalidateTags(['users_in_class.' . $uid']);


Block overriding with template file doesn't work The Drupal version I'm using is v7.34. I'm using sub-theme created from Bootstrap as base theme.
My problem is, I want to override the "User Login Block" and put it in the header region (top bar), so I create these file in templates folder in my sub-theme:

page.tpl.php

//this simply do
print render($page['header']);
region--header.tpl.php

$search_block = module_invoke('search', 'block_view', 'search');
$login_block = module_invoke('user', 'block_view', 'login');
print render($search_block);
print render($login_block);
search-block-form.tpl.php

//this copied from base theme and only modified some html tag
block--user--login.tpl.php

//this simply print out some simple text
print ("blahhhhhhhhhhhhhh");

The result is, only search block is rendered as override, and the login block is rendered as default block, not rendered as the one I override.
I did some search but nothing matches my fault.

To Alter User login block

Find the template.php file for the theme you're working on. Should be in the root of the theme folder for your theme
Assuming the "yourthemename_hook" function does NOT exist, at the bottom of your template.php file insert the following code:

function yourthemenamehere_theme(&$existing, $type, $theme, $path) {
   $hooks['user_login_block'] = array(
     'template' => 'templates/user-login-block',
     'render element' => 'form',
   );
   return $hooks;
 }
function yourthemenamehere_preprocess_user_login_block(&$vars) {
  $vars['name'] = render($vars['form']['name']);
  $vars['pass'] = render($vars['form']['pass']);
  $vars['submit'] = render($vars['form']['actions']['submit']);
  $vars['rendered'] = drupal_render_children($vars['form']);
}

Now create a directory inside your theme's directory called "templates" (assuming it doesn't exist already)
Then create a php file inside that folder called: "user-login-block.tpl.php"
Inside this file, put the following code:

    <?php print $name; // Display username field ?>
    <?php print $pass; // Display Password field ?>
    <?php print $submit; // Display submit button ?>
    <?php print $rendered; // Display hidden elements (required for successful login) ?>

    Create an Account | Forgot Password

CRITICAL STEP as an admin on your website, navigate to "admin/config/development/performance" and click "clear all caches" -- if you don't, then these changes won't display on your website
Modify the html markup inside "user-login-block.tpl.php" to your heart's content, and don't forget that you can also add those css classes to your main style.css file (AFAIK)


Override a node template and its associated translation I'm trying to understand how to override a node template in order to "catch" also all the associated node translations.

Let's say I have a node/12 in English and its translation is node/13. To override in the same way both nodes I have to create templates/node--12.tpl.php and templates/node--13.tpl.php inside my theme folder.

Is there a way to avoid this, since the customisations I plan to implement on the node and its translation are the same?

You can create a content type for the translations and use that content-type node template. node--CONTENTTYPENAME.tpl.php.
so you don't need to update it one by one with the node ID.


How to make content creation form more organized. Taxonomy Checkbox list I am preparing to allow users to edit specific fields of content. I have until now used autocomplete for myself.

I would like to start using the Check boxes, but as of right now it show my 30 terms as a one column list.

Is there a way to have these terms show in 4 columns instead of one long column. (to organize it better and utilize page space)

If you are familiar with using CSS to change the layout of your drupal site already, something like this should work:

/* Make categories field 2 columns */

div.form-item.form-type-checkboxes.form-item-field-categories-und {

    -moz-column-count: 2;
    -moz-column-gap: 20px;
    -webkit-column-count: 2;
    -webkit-column-gap: 20px;
    column-count: 2;
    column-gap: 20px;

}

If not, it will depend on what theme you are using. We are using the seven theme for our admin pages, which include the node create pages. In the seven theme, I could just add the chunk of CSS above to the style.css file. Technically however, this chunk probably shouldn't be added into a core theme because it might get wiped out when/if you upgrade drupal core.

If you want to do it properly, you should create a new stylesheet with something similar to the CSS chunk above and give it a name. Then, add that stylesheet in your theme's .info file. (You can see specific instructions on how to do that here: https://drupal.org/node/171209)

Be sure that you don't have your CSS optimized when you are updating your stylesheets. If you aren't sure how to check this setting, go to admin/config/development/performance and make sure the option to aggregate and compress CSS isn't checked.

Without knowing more about your setup, what theme you are using, etc. it's hard to make a more specific recommendation.


Custom home page not recognized by system I have set up a Drupal 8 site with a custom home page using page--front.html.twig. The content displays at domain.com/front. When I go into Administration to change to the new home page, it says that the path is invalid. I've also tried leaving the field blank.

I also noticed that when I'm on /front, the browser tab displays "Page not found".

I've cleared the cache repeatedly (and every time it sends me to /user/1).

What am I missing here?

There are two separate issues at play here, which is where you are getting confused.

1) page--front.html.twig - this is a template suggestion for the page theme hook. This can be seen by the double-hyphens that follow page. The page theme hook is used to wrap the content of every page on the site, using the page.html.twig template. Drupal's theme layer allows for creating suggestions for templates that take precedence over the base template. In this case, when on the front page, the site looks for page--front.html.twig, and if it finds this file, it uses it. You have created this file. However, you'll notice I said this template wraps the current page content. That leads to:

2) Page content. 'Pages' on Drupal show content if a page has been assigned to the given path. However, if a user goes to a path that doesn't exist, they get the 'page not found' page. This page is wrapped by page.html.twig, just like any content page.

When you go to /front, you see page not found, because you have not created a page at that path yet. You've only created a template for the front page, whatever that may be (even if that ends up being page not found).

You can test this by creating a new node, and setting the path to be /front (note - you'll need appropriate permissions for this). Then set the site front page to /front, and your template will be picked up.


Node reference: Select an exisiting node, or create a new one I am using Drupal 7, with the References module installed.

I was wondering if there is a way (or perhaps another module) so I can select an existing node from the list or create a new one on the fly (ajax or non ajax)?

So for example I have a button for create new node and automatically select the new node as a reference?

I'd like to have the node reference as a LIST only, not auto complete.


How to use Drupal Commerce subscription products? I created a site which has premium membership and want users to pay for those memberships.
I have installed commerce_sp on my site but I don't know how to configure it and use it.

When a member pay for a membership for 1 year, for example:
Subscription validity: 2014-09-25 13:45:00

but I don't know why, when I check this member again every once in a while. the Subscription validity has changed to: 2015-09-24 13:45:00.

And I check this member again tomorrow,the Subscription validity has changed again:2017-09-22 13:45:00.

I don't know why the subscription validity change again and again.

I was very confused, anybody know why?

Most probably you have got issue with your rule set. Best way to use(configure) commerce_sp or even commerce product for membership is to put proper condition & then fire the event.

Simple Config :

Create new products (using Subscription Products).
Create product displays for those products.
Go to Configuration>Rules.
Find the Rule called "Subscription Started (update)" and clone it.
Rename the cloned rule.
Make the Event "Completing the Checkout Process". Add some more like "user of type" etc.
Make the Elements "Order contains a particular product" and specify the SKUs of your subscription products.
For Actions, use "rule set: Subscription start" with parameter as "User:[commerce-order:owner] and "Schedule component evaluation" as is and added "Add user role" with Parameter: User:[commerce-order:owner] and Roles: my subscriber role.
Set the low weight for this rule set.

You can modify rule as per your requirement & it will work accordingly.


Can't programmatically fill address field on taxonomy term creation I'm creating some taxonomy terms inside of an update hook and they have a coordinates field and an address field containing only zipcode and locality.

The Vocabulary is called cities, the address field is called field_cities_zip_city and the coordinates are called field_cities_coordinates.

//the exact data that fails
$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
  'field_cities_coordinates' => [
    'lat' => $city['lat'],
    'lng' => $city['lng'],
  ],
]);
$term->save();

What happens is, the term gets created, the coordinates get filled in properly, but the address remains empty despite even being required fields.

Trying like this did not change anything:

//the exact data that fails
$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
  'field_cities_coordinates' => [
    'lat' => $city['lat'],
    'lng' => $city['lng'],
  ],
]);

//set the fields again manually, but this has no effect
$term->field_cities_zip_city->postal_code = $city['zip'];
$term->field_cities_zip_city->locality = $city['name'];

$term->save();

The address fields are still empty. What am I missing??
Thanks in advance for any help!

You need to provide the country_code to your address field.

like

$city = [
  'zip' => 1000,
  'name' => 'Lausanne',
  'lat' => '47.3879577',
  'lng' => '8.044136',
];

$term = Term::create([
  'name' => $city['zip'].' '.$city['name'],
  'vid' => 'cities',
  'field_cities_zip_city' => [
    'country_code' => 'CH',  // country code is required
    'postal_code' => $city['zip'],
    'locality' => $city['name'],
  ],
]);
$term->save();


Photos in views taking a long time to load We have  views  with  multiple  cck image  fields  http://screencast.com/t/UOGxa9Jr6  with  'Group multiple values'
And  we have a theme  function  to add the needed  classes for a script to display these photos in fancybox

function mytheme_content_view_multiple_field($items, $field, $values) {

  if($field['field_name']=='field_photos_images'){
    $output = '';
     $i = 0;
    foreach ($items as $item){
      if(!empty($item) || $item == '0')
        {
          if($i == 0) {

            $output .= '

';

          }
          else {
            $output .= '

';
          }
          $i++;
        }
    }
    return $output;
  }
}

each node has many images so it takes some time for the nodes to load, you can see each image load one by one taking about 10 seconds to complete

If you can see the images loading one by one then this doesn't have anything to do with the View rendering slowly.

Slow running PHP generally means you have to wait longer before anything displays, not that individual parts of the page render slowly.

Slow loading images means the file size is large or you have a bad internet connection between you and the server.

You've mentioned that you're using CCK so I assume you're using Drupal 6.

Might I recommend using imagecache to pre-process the images to be scaled on the server to the right dimensions before they are sent to the user.

http://drupal.org/project/imagecache

Instead of printing the image tag directly, setup an imagecache preset in Drupal then you call theme() to generate the image markup.

Example:

<?php
  print theme('imagecache', 'mypresetname', 'path/to/file.jpg');
?>

Documentation on the theme function can be found here: http://drupalcontrib.org/api/drupal/contributions!imagecache!imagecache.module/function/theme_imagecache/6


CKEDitor removes class names, even with the exception in config CKEditor seems to be stripping out class names when I toggle between HTML view and Rich Text view.

As per many suggestions across the web I have added the following to the config.js file:

config.allowedContent = true;

Uploaded, cleared cache and even gone to the JS file directly to check it is not caching on my machine, but it's still removing classes.

Is there another solution?

Go to "Admin >> Configuration >> CKEditor"; under Profiles, choose your profile (e.g. Full).

Edit that profile, and on "Advanced Options >> Custom JavaScript configuration" add config.allowedContent = true;.

Don't forget to flush the cache under "Performance tab."


Context module not triggering Delta snapshot I am using the Omega theme, and have the Delta and Context modules enabled. I created a Delta snapshot, and then created a Context to load that snapshot on the front page.

I created the context Condition -> path -> <front> and Reaction -> Delta -> Select Custom theme settings template. However, when I load the front page, the new snapshot doesn't load - it reverts back to the 'standard' Omega layout that I created.

I've tried deleting and recreating both context and snapshot, and clearing cache. I can't figure out what I'm missing.

Thanks for the help

ok...so I'm dumb. I guess this is for anyone else who is going too fast, like I was - I created the delta module for another theme. I didn't realize that the delta snapshots are per theme, which makes sense.


Programmatically find out what fieldset a field belongs to, if any There doesn't seem to be a way to join the fieldset table in the database to a fields table, nor any function that can be used to get fieldset info by field name. Is there a way to get fieldset info starting from a single field's information (as well as bundle and such)?

If you call field_group_info_groups with the entity type and bundle, it will return all the field groups on the bundle, the fields should be in the children array under ['form'][YOUR_FIELDGROUP] e.g.

     $fieldgroups = field_group_info_groups('node', "YOUR_NODETYPE");
     $field_names = $fieldgroups['form']['YOUR_FIELDGROUP']->children;

$fieldnames should now contain a list of all the fields that pertain to YOUR_FIELDGROUP. Which you can now parse through using a foreach loop.

     $node = node_load(2);
     foreach ($field_names as $key => $field_name) {
      $field_items = field_get_items('node', $node, $field_name);
      // Do something cool here.
     }


How to load a node by a field value? I want to load a certain node. I don't know the id of the node but I do know that it has a certain hash field that is unique and I know that hash.

I want to load the node via the hash field. How can I do that?

The quickest way to load a specific node by field value is to use the method loadByProperties().

You specify one or more field values and returned is an array containing the nodes matching the field values:

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['title' => $title]);

Normally you loop over the nodes. In your case you are looking for one specific node. A single node is also returned in array, so apply reset() and this returns either the node or NULL if nothing was found:

if ($node = reset($nodes)) {
  // found $node that matches the title
}


Site map module assigns random frequencies to content I just created an XML sitemap in Drupal 7. As I click on the 'rebuilt links' button, all my content pages are assigned random frequencies and the module does not give me an option to edit content frequencies.

For eg: I have 15 content pages and all these pages share the same content type. I assigned priority of 0.9 to this content type. As I hit 'rebuilt links', few pages were randomly assigned daily frequency, where as rest of the pages were given monthly frequency.

Is there a way I can assign uniform frequency to all my content pages? or edit individual page frequencies? What exactly is making the XML site map module assign two different sets of frequencies to the same content type?

Is there a way I can assign uniform frequency to all my content pages? or edit individual page frequencies?

Not through the UI as far as I know, but it's possible in code using hook_xmlsitemap_link_alter():

function MYMODULE_xmlsitemap_link_alter(&$link) {
  if ($link['type'] == 'node' && $link['subtype'] == 'article') {
    $link['changefreq'] = 86400;
  }
}

$link also has a loc field which contains the router path for the node (e.g. "node/1"), although it's not ideal you can use that quite reliably to determine what specific node is being dealt with.

  What exactly is making the XML site map module assign two different sets of frequencies to the same content type?

It's intentional - the change frequency for each link is calculated dynamically by the module. I assume the idea is that giving Google an accurate change frequency is better than setting something static and then ultimately struggling or failing to live up to it in the mighty engine's eyes. Doesn't always work like that in practice, of course.


Registration message after saving password for first time I am using standard way of user registration. User enters default fields + some extra text fields, gets email, clicks link in email.
Back to website, he clicks one time login in button and enters password.
After saving password message pops up, which makes no sense.

"You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password. The changes have been saved."

Why is message "Please change your password" here ?

You can use "String Overrides" module to achieve this. As this message sets using drupal_set_message function and this function stores these messages in session. So the best way to change this message is use of string overrides module. This module can easily replace anything that's passed through t() function. So you just need to put whole string that you want to replace with your own string.


how to reinitiate a default field value every time the content edition is loaded? i have a field that , if opt-in, send notifications.
I would like that when editing the content , the value is always reinitiated to opt-out, sitll leaving the possibility for the editor to opt-in again

this code below does it but then it is not possible to save an opt-in nomore

use Drupal\node\NodeInterface;

function mymod_entity_load(array $entities, $entity_type_id)    {

  foreach ($entities as $entity) {
    if ($entity instanceof NodeInterface) {
      if($entity->bundle()=='evenement'){
         $entity->field_notif=0;
      }
    }
  }
}

You need to use hook_form_alter

    use Drupal\Core\Form\FormStateInterface;

    /*
     * Implementation of hook_form_alter()
     */
    function mymod_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if($form_id == 'node_evenement_edit_form'){ // target a specific form
        $form['field_notif']['widget']['#default_value'] = 0;
      }
    }


Categories and brands I have a product catalog that I would like to categorise into different categories (and subcategories).
I would also like to have a grouping of the products by brands (which of course are orthogonal to the categories).

The ideal thing is that a customer can search for products belonging to a category, and/or to some brand.

Until now I have only managed to create the main categories.
I created also subcategories, but they do not get displayed in the products page, i.e. having something like

CatA

Sub1
Sub2

CatB

If I try to show all the products in CatA only those belonging directly to it (and not to Sub1 or 2) get displayed.

Of course I do not have any idea on how to implements the brands.

EDIT:

I've tried some options in the mean time.
Regarding the brands, I understood it is a completely different taxonomy.
I created it, and associated it with the products and I added a new search facet in the All Products page. Probably I'll need some more advanced stuff in the future, but for now it is ok.

Instead, I'm still struggling with the sub-categories problem.
I watched the following discussion & video: https://drupalcommerce.org/discussions/9017/product-catalog-terms-and-nodes
They do something similar to what I need, but I need to put some modifications.
I do not need multiple pages to navigate the categories.
I simply want that if a user navigates a page like products/CatA all the products in Sub1 and Sub2 are shown.

Commerce Kickstart is a 'canned' solution, so you're limited by what's been 'hard-coded' already. This is fine, you just need to make some leaps of faith to use their product for your purposes.

You can't use the hierarchical structure of 'indented' sub categories of a Drupal taxonomy as an expected subcategory in Commerce Kickstart. It just doesn't understand it (yet). Unfortunately, you can only use a single level of category for each taxonomy category term. In Kickstart 2 - that's called the 'Collection' taxonomy. So don't add subcategories there and expect them to be shown. In some ways, this saves you some headaches.

You need to make a separate (again, single level of depth) taxonomy term for subcategory. You also need to set it to be a taxonomy of product classification (the checkbox thing in the Edit of the taxonomy).

With both separate, single level of depth, taxonomies, you then need to add these term reference selection boxes to your 'Product Variation' (and NOT Content Type).

You then need to put your brand, set up the same way as the other two, mentioned above, in your 'Content Type' (NOT product variation).

You then need to set up all of your Display Views, in both Content Type (CT) and Product Variations (PV). Look at the 'Tops' CT/PV set up to match that setup for guidance.

In this way, the 'All Products' view will work to allow you to filter by all terms of category, subcategory, and brand... or what ever other classification you can think up.


In Rules, how can I use a set the value of a taxonomy term reference field to multiple values? How can I set a taxonomy term reference field to two values using Rules?  The "Number of values" for the field is already set to two.

I set up a workflow in rules that works for setting a single value.  I tested this several times and encountered no problems.  However, when I changed the "Number of values" for the field from "1" to "2" and then edited the action to add two terms instead of just one, I got the following error message:

  Warning: Missing argument 2 for taxonomy_options_list() in
  taxonomy_options_list() (line 1375 of
  /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).
  Warning: Missing argument 3 for taxonomy_options_list() in
  taxonomy_options_list() (line 1375 of
  /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).
  Warning: Missing argument 4 for taxonomy_options_list() in
  taxonomy_options_list() (line 1375 of
  /srv/bindings/e87a1e62cfd24fea9dd67cfd074d146c/code/modules/taxonomy/taxonomy.module).

When I attempt to set a value by triggering the rule, it fails and the rules debug log has the following output:

  3.235 ms Unable to get a data value. Error: Invalid data value given. Be sure it matches the required data type and format.
  4.254 ms Unable to evaluate action data_set.

What is the correct way to assign two terms at once to a single taxonomy term reference field?

As it turns out, this is actually fairly easy to do in Rules.  By updating to the latest version of the Entity API (rc3-- I was stuck on rc1 due to a different bug that I resolved earlier today) with Rules 2.1, I was able to do this in the following way:

Choose the action "Set a data value".
Choose the taxonomy term reference field to set.
Control-click to select the taxonomy terms to add.

That's all there is to it, but there is one potential gotcha: these values didn't always save correctly for me.  This may be because I opened multiple tabs in Firefox and tried to save many different rules at once; for whatever reason, sometimes only one of the two values got saved.  I fixed this by simply checking all the values again manually and re-saving them until the values stuck.


PDOException does not show my sql table Hello Every body I have an SQL Query to DB

function darkSiteContent($delta){
     switch ($delta) {
     //SQL Query to find the title , nid of the node and its body
     case 'popup_dark_screen':
      $result = db_query("
        SELECT n.title , n.nid , b.body_value
        FROM {dot_node} as n , {dot_field_revision_body} as b , {dot_node_type} as t
        WHERE t.type = 'dark_sit' AND n.type = t.type and b.bundle = t.type
        order by n.title desc LIMIT 1
        ");
        $items = array();
        foreach ($result as $row) {
        print_r($row);
        $items[] = l(t($row->title, 'node/' . $row->nid )).''.$row->body_value;
        }
      return array('#markup' => theme('item_list', array('items' => $items)));
      break;
    }

}

But it show this error

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'APIG01JO2012039.dot_dot_node' doesn't exist: SELECT n.title , n.nid , b.body_value FROM {dot_node} as n , {dot_field_revision_body} as b , {dot_node_type} as t WHERE t.type = 'dark_sit' AND n.type = t.type and b.bundle = t.type order by n.title desc LIMIT 1 ; Array ( ) in darkSiteContent() (line 71 of C:\AppServ\www\APIG01JO2012039\sites\all\modules\darksite\darksite.module).

I am sure of my table name but it still show this error

When using database with in {} you don't need to add the prefix of the table it is automatically added by drupal in your case since you have placed it between {} it is adding another dot_ so the table name is becoming dot_dot_node instead of dot_node.

Note the relevant section from Drupal Database API documentation

  Prefixing

  In static queries, all table names must be wrapped in {}. That flags
  them so that the database system can attach a prefix string to them if
  appropriate. Prefixing allows for running multiple sites from the same
  database or, in limited cases, for sharing selected tables between
  sites.


OG: Only allow certain Drupal roles to join a group I think this might be a very simple setting I am missing somewhere, but I want to prevent people from joining an 'Organic Groups' group unless they have a particular Drupal role. The 'subscribe to group' permission in the group obviously only applies to OG roles, not Drupal's core roles.

I can't see any permission in Drupal's core for 'join group type', which I would have expected.

Any ideas?

I don't think that functionality is packaged with OG on its own.

Are you looking to map certain Drupal roles to certain groups or only have the ability to apply to a group available to certain roles?

I would think this hook is a place to start:
http://www.drupalcontrib.org/api/drupal/contributions%21og%21og.api.php/function/hook_og_permission/7

But here is a list of all hooks you can use with OG:
http://www.drupalcontrib.org/api/drupal/contributions!og!og.api.php/7


Add taxonomy terms to search autocomplete I have a Drupal 8 website with default search bar in my homepage. I have installed the Search Autocomplete extension to extend its functionality. Everything works great, except it does not suggest taxonomy terms. Can you give me an idea to add taxonomy terms to its suggestions?

Update:

I'm sorry that this is not the question I suppose to ask, as I have mistaken the issue. The default search block, does not search taxonomies, but search for the content which belongs to that taxonomy. Let me show you an example:

Here the Vancouver is a taxonomy term, and the things that listed(ZHR DEL, Gas Town, etc.) are content which belongs to this term. If you type the same thing in autocomplete, it does not suggest above content nor taxonomy term.

What I want is to suggest the taxonomy in autocomplete, and show the taxonomy term in the search result. Any help is truly appreciated.

Default search can either display users or content. Apart from this it won't show you any results.


How do I merge this code? In Drupal 7.
I have the following code in my template.php file:

function mytheme_theme($existing, $type, $theme, $path) {
   return array(
   'comment_form' => array(
   'render element' => 'form',
   ),
 );
}

I also would like to use the following code to theme the Register page:

function mytheme_theme() {
  $items = array();
    $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
       'mytheme_preprocess_user_register_form'
    ),
   );
 return $items;
}

How do I merge the two snippets of code?

Any help on this is greatly appreciated. :)

Just merge like:

function mytheme_theme($existing, $type, $theme, $path) {
  $items = array();
    $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
       'mytheme_preprocess_user_register_form'
    ),
   );
   $items['comment_form'] = array(
    'render element' => 'form',
    ),
   );
 return $items;
}


How to prevent CKEditor trim plain text in source view I'm using Drupal 8,

In source view when I paste some plain text like this:

Hello sir.

Hello  sir.

And submit node form, without toggling back to rich-text mode, text above is removed.

If I toggle back in rich-text mode before submitting, CKEditor automatically wraps my text in p tag, like this:

Hello sir.

Hello sir.

Hello sir.

Hello sir.

So is it possible to make CKEditor wrap plain text in p without toggling back to rich-text view?

I have tried several things and failed in all of them, I have written custom CKEditor plugin which listens to submit button click and execute this editor.execCommand( 'source' ); but it isn't working, somehow data is submitted before I switch to rich-text mode.

Is there any solution to this?

CKEditor distinguishes Output formatting from Source Code formatting.

You're essentially wanting to do output formatting inside the source code formatting. It seems this is currently not possible.

From the documentation:

  Configuring Source Code Format

  At the moment the only aspect of the source code view that you can configure is the tab-size CSS property of the source editing area. Use the CKEDITOR.config.sourceAreaTabSize option to set the width of the tab character. Enter an integer to denote the number of spaces that the tab will contain.

  http://docs.ckeditor.com/#!/guide/dev_sourcearea

You might play with using the popup source editor instead of the inline editor, I don't know if this would give you any more possibilities to plug into and alter the HTML in source-editing mode or not.


403 Error on AJAX Request I defined the following menu item on my module:

function visita_virtual_menu(){
$items = array();
$items['visita_virtual/marker_selected_handler'] = array(
        'title' => t('Marker Selected Handler'),
        'description' => t('Ajax handler for selected markers'),
        'type' => MENU_CALLBACK,
        'access arguments' => array('access panoramas'),
        'callback' => 'marker_selected_handler');
return $items;

}

And even created an special permission for my module:

function visita_virtual_permission(){
return array('access panoramas' => array(
        'title' => t('Configurar Panoramas'),
        'description' => t('Configurar la visita virtual'),
        )
);

}

Obviously the access panoramas permission appeared on the People Permissions configuration tab on Drupal. I assigned it for anonymous users, logged users, and administrator users (Just for testing purposes).

Now my javascript function does the following:

alert('Callback URL: '+url);

    $.ajax({
        type : "POST",
        url : url,
        data : {
          'marker_latitude' : location.lat,
          'marker_longitude' : location.lng,
        },
        success : function(data){
            alert('Entro a la funcion success');
        },
        error: function(xmlhttp) {
            alert('An error ocurred: '+xmlhttp.status);
        }
    });

The alert('Callback URL: '+url); line shows the following info:

/drupal/visita_virtual/marker_selected_handler

However I'm always getting 403 access forbidden error. Why?? What I'm doing wrong???

I have been debugging the server's code, and the problem seems to be at this piece of code on menu.inc.

function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
// Check if site is offline.
$page_callback_result = _menu_site_is_offline() ? MENU_SITE_OFFLINE : MENU_SITE_ONLINE;

// Allow other modules to change the site status but not the path because that
// would not change the global variable. hook_url_inbound_alter() can be used
// to change the path. Code later will not use the $read_only_path variable.
$read_only_path = !empty($path) ? $path : $_GET['q'];
drupal_alter('menu_site_status', $page_callback_result, $read_only_path);

// Only continue if the site status is not set.
if ($page_callback_result == MENU_SITE_ONLINE) {
if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['include_file']) {
      require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
    }
    $page_callback_result = call_user_func_array($router_item['page_callback'],   $router_item['page_arguments']);
  }
  else {
    $page_callback_result = MENU_ACCESS_DENIED;
  }

The $path parameter is getting it's default value. NULL, and then the $read_only_path is obtained from the q $_GET value, for this case the $read_only_path has it's value set on: visita_virtual/marker_selected_handler Is that ok?? shouldn't it be /drupal/visita_virtual/marker_selected_handler?

At this point $router_item = menu_get_item($path) I'm getting a $router_item that has an 'access' value of false. So that's the reason I'm receiving 403. Still I'm lost, I don't know what I'm configuring wrong for the menu...

The reason you get an Access denied is because your menu item doesn't have a page callback attribute specified. (You have used callback instead). You can check the documentation of hook_menu() here.

On the same page, you'd notice that it says - when the page callback attribute is omitted for a menu item, the page callback of its parent will be taken.

However, when a parent doesn't exist for the menu item in question, it returns an Access denied. This happens even before the current user's access to your menu item is resolved; so the access callback doesn't really matter. (explains why changing that hasn't helped)


How can I view my log files via ssh? I currently cannot access http://example.com/admin/reports/dblog as I cannot authenticate as an admin as my page is getting a 500 error.

I wonder if there is an actual location on my production server where Drupal errors are logged.

If you have drush set up, you can use drush watchdog-list to look at the items logged to watchdog.

If you don't have access to drush, but your DB is up and running fine, you can always query the watchdog table with Select * from watchdog;

From personal experience, you might want to check your apache error logs as well to see if those hold anything that can help.