How do I dynamically change the $GLOBAL['base_path'] variable? Example scenario:

All authenticated users should see /members/ at the beginning of each URL path, and all anonymous users should see /guests/ at the beginning of each URL path.

So if an anonymous user were to visit example.com/node they'd be redirected to example.com/guests/node, and once they logged in they'd be redirected to example.com/members/node.

I'm sure this is not impossible because using a multilingual site allows for paths to be negotiated by prefix only, but I can't seem to figure out how to go about it.

Here are some of the things I've tried (some of which have been out of desparation):

Example 1:

function mymodule_init() {
  if (user_is_logged_in()) {
    $GLOBALS['base_path'] = '/members/';
  }
  else {
    $GLOBALS['base_path'] = '/guests/';
  }
}

Example 2:

function mymodule_init() {
  $prefix_default = 'guests/';
  if (user_is_logged_in()) {
    $prefix_default = 'members/';
  }
  $get_q = isset($_GET['q']) ? $prefix_default . $_GET['q'] : $prefix_default;
  $args = explode('/', $get_q);
  $prefix = array_shift($args);
  $args_new = array();
  if (!empty($args)) {
    foreach ($args as $arg) {
      if ($arg != $prefix) {
        $args_new[] = $arg;
      }
    }
  }
  $GLOBALS['base_path'] = '/' . $prefix_default;
  $_GET['q'] = implode('/', $args_new);
}

Example 3:

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  global $user;
  if (!$user->uid || !isset($user->status) || empty($user->status)) {
    // Allow access to front page only, or guests/* paths, or even user/* paths
    if (($path != 'node') && ((!preg_match('|^guests([/]?.*)|', $path)) && (!preg_match('|^user([/]?.*)|', $path)))) {
      $result = 'user';
    }
  }
}

Any input would be most appreciated. Thanks!

I don't think base path is what you need here.
Once the user's page is loading it is too late to change their URL, unless you redirect them them to the /members or /guests url with drupal_goto().

Base path is also not what you need because base path is telling drupal where your files are in the web root, so changing the $base_path global is likely just going to break your site unless your files are in /var/www/yoursite/members and /var/www/yoursite/guests (I'm assuming your web server setup here for the paths).

The main thing here is that you need to make sure your users are actually hitting the paths www.example.com/members/path and www.example.com/guests/path and then you have to make drupal handle those paths appropriately or you will just get page not found errors.

This is how the drupal multilingual (locale) system works.
It rewrites urls that appear on the page to point to www.example.com/langcode/path so the user is actually navigating to those pages. If there is no langcode part drupal just assumes the default language.

In drupal 6 this is ingrained into the url() function, which calls language_url_rewrite().
In drupal 7 the local module has an implementation of hook_url_outbound_ater() (local_url_outbound_alter()).

You could replicate this by implementing custom_url_rewrite_outbound() (read the docs for that, it is not a normal hook).
Or use the url alter module and implement its hook_url_outbound_alter() hook.

That's not all though, because users are going to paths like www.example.com/langcode/path those paths have to be valid drupal menu system paths or else drupal won't know that functions to call for that given page.

For the multilingual system drupal core handles this in the bootstrap phase, before any menu handling has happened.

See _drupal_bootstrap(), which for the DRUPAL_BOOTSTRAP_LANGUAGE phase calls drupal_init_language(), which in turn calls language_initialize().

language_initialize() has code in it that detects the language from the url and then removes that language portion of the url from the $_GET['q'] variable so everything from then on just sees www.example.com/path and the page loads as normal.

If you were to use this same approach for your path then the system would try to load the menu item for www.example.com/members/path and it would likely not exist and you would get page not found errors.

However you could the also add an implementation of hook_boot() that does something similar to language_initialize() and save a global variable of your user type (member or guest) and then removes that part of the url from $_GET['q'] before the menu handler runs.

From then the $_GET['q'] variable doesn't have your user type anymore but you will be able to use the user type global you created from your other custom code if you need to.

This system relies on there being a default user type for when guests or members are not present (which can easily happen, for example the user can just type in the url manually instead of clicking one of your altered links).

So your system would have to assume the user type or work it out in some other way (easy because you have user_is_logged_in() or global $user to determine the user type). It just means in these cases the user doesn't get to see that url scheme you want with the user type in it.

As you can see this is a complex requirement and the solution doesn't have 100% coverage so i it was me I would reconsider doing this at all.

Alternatively you may be able to just have a members area, full of pages like views and nodes that do really have urls like /members/something, but not change the url for the whole site (although I'm just making assumptions on your requirements now).


Unsubscribe Newsletter I was implemented "simplenews_register" module in my drupal project. so, Whenever user want to register in this site He has to enter his user name,email address,password and at the same time he want to subscribe any existing newsletter  then he check the related newsletter  check box. Then, automatically user will receive one mail regarding to subscribe link . So, he want to subscribe then he will click that link .

Here my requirement is if user has been subscribed any newsletter then automatically he has to receive "Unsubscribe" link . So, for this requirement what I have to do please guide me.

Unsubscribe links are automatically included when emails are sent via simplenews.

By the way, if you're using simplenews-2.x, you don't need the simplenews_register module; that functionality is included.


Date Filter in drupal Can anyone help me how to expose the date filter in a view in drupal 7.

I have added post date filter with in FILTER CRITERIA but it is not working

Can anyone help me

Here is how I used exposed filter to filter content with date (assumed you have the Date Views module enabled).

I just create a view with all fields and the in the "Advanced > CONTEXTUAL FILTERS" section, I add a new contextual filter and I select Date : Date (node). In the next box, I can select the date field to filter (publication date or any date field). I can also give a default value if no date parameters is passed through the url : for example, the current date.

And that's it, I just pass the date as URL parameter : I have something like

http://mydomain.com/agenda/all/2012-03

where /all is my first parameter, I us it to match a country for my posts, and the second parameter is the month of the post.

I hope that helps.


Need to filter events from the current week only I am using drupal 7 & views for a simple event agenda website. I need to display content for the current week only. How do I filter those with views? For example, I need to be able to set an event that will show only through week number 36.
thanks!

Views can do this.

Add a contextual filter for the date field you're trying to filter. In the "Preview with contextual filters" box, you will be able to specify something like "2012-W34" (Edit: or any other valid date format for that matter) to say year 2012 on week 34. Use PHP's date() function to retrieve the current week and pass that as an argument to your view. This will give you your current week while avoiding current day +/- 7 days.

Edit: When passing the argument to your view, be sure it's a string in the date format and not just a week number.


Routing and path aliases I have created a module with its routing.yml file.

mymodule.dossier:
  path: '/dossiers/{node}/dossier'
  defaults:
    _entity_view: 'node.dossier_dossier'
  requirements:
    _permission: 'access content'

I have created a custom view mode (node.dossier_dossier) and the corresponding Twig template. If I go to dossiers/1/dossier, it works, and it displays the node with the dossier_dossier view mode and appropriate template.

node/1 has /dossiers/my-custom-path as its path alias, which is automatically set from the Pathauto module. If I try to access /dossiers/my-custom-path/dossier, it returns a Page not found error.

How can I make this route work for my nodes for both (default and path aliases) URLs?

Edit: I should maybe mention why I need that:

/dossiers/my-custom-path should display the node using the default view mode
/dossiers/my-custom-path/dossier should display the node using the dossier_dossier view mode
/dossiers/my-custom-path/abstract should display the node using yet another view mode (I'd create another route for that one presumably)

Pathauto can't do this, it can only generate aliases to the default view mode.

You can write your own Pathauto module, which generates for each view mode a separate aliases. For a single purpose module there is not much work to do, you only need to generate the aliases and use

\Drupal::service('path.alias_storage')->save($source, $alias);

to save them.

The problem is, you get a very large url_alias table.

Or use route_callbacks: in *.routing.yml, then define in this callback for each view mode a different route, which calls a Controller, which then in case you have a hit on the route will look up the middle part of the alias and return a redirect to the node in the requested view mode. This is without the static alias table, but may take longer for each request.


How can I send an HTML email from an Ajax callback? I want to send an email to the user who forget username.
I created a functionality that handle with Ajax like send request to controller where I using a query to check whether user exist or not. if user exist I want to send email to used with his user name.
Is there any module that i can use to send email in this way
public function ForgotUsername() {
  $mail = \Drupal::request()->query->get('mail');
  $database = \Drupal::database();
  $username = $database->query("SELECT name from users_field_data where mail='$mail'")->fetchField();

  if (!empty($username)) {
    $module = 'modulename';
    $key = 'forgotusernamerecovery';
    $to = 'example@example.com';
    $langcode = '';
    $params = ['username' => 'Abc'];
    drupal_mail($module, $key, $to, $langcode, $params = [], $reply = NULL, $send = TRUE);

    $message = "
Successs
";
  }
  else {
    $message = "
notmatched
";
  }
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('.selector', $message));
  return $response;
}

I recommend the Easy Email module. It combines with Swiftmailer and Mailsystem, allowing for creating and sending HTML emails, using templates you can build with a ckeditor right in the interface. Then you can send mails from your module using the standard Drupal mail service, and it will take care of turning it into an HTML email. The video on the top page of the module page is very informative and explains it all. It's by far the best HTML email solution I've found in Drupal over the years.


Drupal 6 & Custom query sanitization Reading through Drupal 6 docs, it appears that db_query and db_query_range take the entire query.

This is different from Drupal 7, which can separately take user input as an argument, effectively sanitizing it.

What is the proper way to deal with custom queries, that contain unsafe input in Drupal 6?

The Drupal 6 version of db_query supports placeholders.  The best explantion of these is probably the Writing secure code article.

A (contrived) example would be

$query = "
  SELECT node.nid FROM {node} node
  INNER JOIN {content_type_foo} content_type_foo ON content_type_foo.nid = node.nid
  WHERE content_type_foo.field_foo_value = '%s'
";

$foo = $_GET["foo"];
$nid = db_result(db_query($query, $foo));

The referenced article also shows how to use placeholder arrays for handling a variable number of arguments, like for WHERE IN queries.

The second edition of Pro Drupal Development, which covers Drupal 6, is also a good reference for using the database abstraction later.


Crumbs module won't display correct current page. Displays 'Anchor' I am using the crumbs module to create a breadcrumb for my website. I have the 'Show the current page at the end of the breadcrumb trail.' setting enabled however on one of my pages the current page is getting replaced with the word 'Anchor', instead of of Home>Products>'Lambswool Dusters'

Does anyone know where this is coming from? The name of the page is correct and all of my other breadcrumbs are being generated properly.

I might also add I am generating the urls using taxonomy terms and I do have page anchors on the page.

Output I am getting.

I found the answer to my issue after using the crumbs debug tool. I had stupidly named a link 'Anchor' when I was creating a menu and forgotten about this. This menu item was overriding the output I was looking for.

Here is my debug results if it helps anyone. Thanks to donquixote for pointing me in the right direction to use the debug tool.


I have no fields available for sorting with Search API sorts module This question is similar to another question I had, but now in a different context.  My previous question was: Search text box for Search API + Database + Search Views + Facets API + Facets Bonus

That option worked, except I can't use Current Search to reset the search box.  I can reset the filters, but not search box.  I also can't find an option to allow the user to sort the fields.  I installed the Search API Sort module, but was unable to get any fields to be available.  I kept hosing my index trying to enable/disable fields, and couldn't figure it out.

My question is how can I use a search form box with Search API + Views that will let me reset the search box with Current Search box, and, how can I have a sort box that will let the visitor select the field to sort by?

My view is rendering nodes via Display Suite view modes.  Right now, I am using exposed search and sort filters, but of course, they are grouped in one block.  The whole point of my having to use the Search API was to provide filters and decouple my search and sort filters from each other.  My sort option will be placed at the top right of the UI, and the sort in the left sidebar.

EDIT: Using Search API Sorts, per giga's advice below, I went back and tried to get my fields sortable.  I stripped down fields and still no luck getting them sortable.  It's a Commerce site, and I'm using the Commerce Search API, which gives me a Product Display index.  I originally move fields of content out of the index, so I'm only left with my product display and product fields.

My indexed fields right now are (field, type, boost):

Content type -- String -- 1.0
 Title -- String -- 1.0
 Date created -- Date -- 1.0
 Date changed -- Date -- 1.0
 Product Tags -- Taxonomy term
 Product Ref -- Commerce Product
 Item Type -- Taxonomy term
 Weight Sort -- Integer -- 1.0
 Product Ref >> Price >> Amount (decimal)(Min) -- Decimal -- 1.0
 Product Ref >> Price >> Amount (decimal)(Max) -- Decimal -- 1.0
 Title (Fulltext)  [search_api_aggregation_1] -- Fulltext -- 1.0
 Product Tags (Fulltext) [search_api_aggregation_4] -- Fulltext - 1.0
 Item Type name (Fulltext) [search_api_aggregation_5] -- Fulltext - 1.0
 Product tags >> Name -- String -- 1.0
 Proudct Ref >> Serving Size -- String -- 1.0
 Product Ref >> Portion Size -- Fulltext -- 1.0
 Item Type >> Name -- String -- 1.0
 Product Ref >> Price >> Amount (decimal) -- Decimal -- 1.0

The only fields I'm trying to index are Title, Min and Max price, and the Weight Sort as the initial default sort.  None of them are showing up in my table of sortable fields under the Sorts tab.

Search API Sorts only lists the fields of supported types. Make sure the fields you want to sort on are single value strings or numbers.

If the fields are mutli-value you can use Search API Ranges to give you max/min value fields that you can use.

If a field is full-text, one trick is to create an aggregated field containing just that field and assign it a string type.


Is there a module provides UI to create field index? My views are quite slow in some cases, needs create indexes on field tables. Is there a module for that?

Because views does not create tables but rather builds queries, you cannot add indexes to views but what you can do is insert Mysql Index hints via the Views Index Hint module.

If this module is not flexible enough for you, you can manually add the index hint after the sql query is constructed by using the hook_views_query_alter hook.


How to allow users to unsubscribe from organic groups? In D6, more often than not users change their mind and want to unsubscribe from groups that the have subscribed. How can they do so?

Use this link:
http://sitename.com/og/unsubscribe/gid/uid

gid = group id
uid = user id

====== second option =======

Go to "Manage membership" or "My membership". click on "Leave this group"


How do I show related content? Using Drupal 7 and Views 3 I am trying to setup a block to show related content based on taxonomy terms.I have read numerous articles and threads on how to do this but none seem to work, this might be due to using a view and custom path rather than displaying the node directly.I have done the following.

Created nodes and added Taxonomy terms to each.
Created a view for each node, the views have a custom path.
Created a block view, added contextual filter on "Has Taxonomy Term ID". I have set default value "Taxonomy term ID from URL" and clicked the LOad Default from node page checkbox.
Added the block to sidebar.

My URL are of the format www/example.com/name , there is only 1 argument, I am struggling to understand how the filter can pick up the term from that URL and would like to know if there is a simple way around this. The problem seems to either lie with my URL or that I'm displaying the  node through a view, I would have thought these were both common scenarios that wouldnt require any coding, any help on how to workaround this would be much appreciated. I am leaning towards using mini panels but having spent some hours with them would rather just use views if possible.
Thanks

EDIT
I think this is very likely view/path related, going to the content page directly displays the block with the related content, its on the View pages with their own paths this is not working. My views are simply Page views with normal filters on the content type and on a taxonomy term (which is different to the term on the contextual filter).

Creating a related content view in Drupal 7:

Show related content based on shared Term-pages (from any given vocabularies).

Each term page will be recognized by the term ID (TID) hidden in the pages’ URL.

The process:

Basic stages:

Create a “Content” view-block.
Add a contextual filter: “Has taxonomy term ID”.
Choose “provide a fixed value”.
(From type): “Taxonomy term ID from URL“.

Checking:

•   Uncheck “Load default filter from the term page”.
•   Check “Load default filter from node page, that’s good for related taxonomy blocks”.

•   Check “Limit terms by a vocabulary”.
•   Check your desired vocabulary.

Select “Filter to items that share any term”.
Go down and check “Reduce duplicates”: This will several terms that relate to the same page – To appear. Only one will of them will.

https://www.daymuse.com/blogs/drupal-guide-related-content-term-views

Optional:

If you would like that the current node won’t appear in the list:

Go to the view and add another, extra Contexutal filter.
Give it content: NID.
Select “Provide default value”.
Set the “Type” to “Content ID from URL”.
Go down in that window, click on “More”, and there check “Exclude”.

Note that this will exclude the current node in which the related is shown – From that very list.

It will do so by using the content ID which is a (hidden) part of the URL.


Show access denied in custom page without permissions I have a requirement where based on user ID displaying the page. If not show Access Denied.
Drupal 7 we have drupal_access_denied().
What is it in Drupal 8?

As a replacement for drupal_access_denied() this in Drupal 8 you can use :

if(empty($userId)){

throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();

}

This shows the access denied page in the browser.


How to add html to title output of taxonomy terms in Drupal 7? I just cant figure it out. How can change the title output of a term?
I have a content type which displays the selected terms. The term is displayed as a link. How can I change this:

    FE-Sub

to something like this:

        FE-Sub

Edit: I tried it out with mymodule_preprocess_field(&$variables) but you may not enter html, it will print "-Element

function proposals_preprocess_field(&$variables) {
    if (isset($variables) && isset($variables['items']['0']['#options']['entity_type']) && $variables['items']['0']['#options']['entity_type'] == 'taxonomy_term') {
        $variables['items']['0']['#title'] = ''.$variables['items']['0']['#title'].'';
    }
}

renders link text:

term title instead of term title

EDIT: here is how i made it work:
in your template.php:

function yourtheme_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '
' : '
';

  foreach ($variables['items'] as $delta => $item) {
    // allow html
    $item['#options']['html'] = TRUE;
    // set html
    $item['#title'] = ''.$item['#title'].'';

    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}

To make changes to the taxonomy term out put you can use the below function. This is taken from the batrik theme so you would use the function mytheme_field__taxonomy_term_reference

To change the markup of the term change #markup the defualt value would be

term name

change that to

 $item[#markup] = 'term name'

function batrik_field__taxonomy_term_reference($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '
' . $variables['label'] . ':
';
  }

  // Render the items.
  $output .= ($variables['element']['#label_display'] == 'inline') ? '
' : '
';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '
' . drupal_render($item) . '
';
  }
  $output .= '
';

  // Render the top-level DIV.
  $output = '
' . $output . '
';

  return $output;
}


list of supported value in entity baseFieldDefinitions setDisplayOptions type(field widget) I'm new in Drupal, I create my first entity and use baseFieldDefinitions to set fields and in fields I use setDisplayOptions to set form like this:

$fields['piece'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('piece'))
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'string',
    'weight' => 2,
  ])
  ->setDisplayOptions('form', [
    'label' => 'inline',
    'type' => 'string',/////// what is supported value list of type key
    'weight' => 2,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

what is supported value list of type key in display option?

I only found options_buttons and string

What you are looking for are the field widget plugins, these depend on what modules you have installed.

Use Drupal Console to run this command:

drupal debug:plugin field.widget

This is what I have on a local site with some contrib modules:

 -------------------------------------------- ---------------------------------------------------------------------------------------
  Plugin ID                                    Plugin class
 -------------------------------------------- ---------------------------------------------------------------------------------------
  boolean_checkbox                             Drupal\Core\Field\Plugin\Field\FieldWidget\BooleanCheckboxWidget
  datetime_datelist                            Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget
  datetime_default                             Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDefaultWidget
  datetime_timestamp                           Drupal\Core\Datetime\Plugin\Field\FieldWidget\TimestampDatetimeWidget
  email_default                                Drupal\Core\Field\Plugin\Field\FieldWidget\EmailDefaultWidget
  entity_reference_autocomplete                Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
  entity_reference_autocomplete_tags           Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteTagsWidget
  field_example_3text                          Drupal\field_example\Plugin\Field\FieldWidget\Text3Widget
  field_example_colorpicker                    Drupal\field_example\Plugin\Field\FieldWidget\ColorPickerWidget
  field_example_text                           Drupal\field_example\Plugin\Field\FieldWidget\TextWidget
  field_permission_example_widget              Drupal\field_permission_example\Plugin\Field\FieldWidget\TextWidget
  file_generic                                 Drupal\file\Plugin\Field\FieldWidget\FileWidget
  image_image                                  Drupal\image\Plugin\Field\FieldWidget\ImageWidget
  language_select                              Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget
  link_default                                 Drupal\link\Plugin\Field\FieldWidget\LinkWidget
  menu_item_extras_view_mode_selector_select   Drupal\menu_item_extras\Plugin\Field\FieldWidget\MenuItemExtrasViewModeSelectorSelect
  moderation_state_default                     Drupal\content_moderation\Plugin\Field\FieldWidget\ModerationStateWidget
  number                                       Drupal\Core\Field\Plugin\Field\FieldWidget\NumberWidget
  oembed_textfield                             Drupal\media\Plugin\Field\FieldWidget\OEmbedWidget
  options_buttons                              Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsButtonsWidget
  options_select                               Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget
  path                                         Drupal\path\Plugin\Field\FieldWidget\PathWidget
  string_textarea                              Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget
  string_textfield                             Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget
  text_textarea                                Drupal\text\Plugin\Field\FieldWidget\TextareaWidget
  text_textarea_with_summary                   Drupal\text\Plugin\Field\FieldWidget\TextareaWithSummaryWidget
  text_textfield                               Drupal\text\Plugin\Field\FieldWidget\TextfieldWidget
  uri                                          Drupal\Core\Field\Plugin\Field\FieldWidget\UriWidget
 -------------------------------------------- ---------------------------------------------------------------------------------------


change comment form container to textarea How to remove the red section in next image (comment form)?

I have try change the type to textarea, but on submit the form a blank page appears.

function THEME_form_comment_form_alter(&$form, &$form_state) {
    $form['comment_body']['#type'] = 'textarea';
}

You can make the field plain text in the comment body field settings.

e.g:

http://example.com/admin/structure/types/manage/article/comment/fields/comment_body

  "Text processing" > "Plain text"


How do I implement two-way node references? The node-reference module (a component of CCK) provides a great way to create a reference one node from another. What is the best way to expose a two-way relationship between the two? Example below:

For instance, in a ticket tracking system with two tickets (nodes) A & B, you could create a node reference from ticket A --> B and mark B as a child. When viewing ticket A it would be trivial to display this information. However, I would also like to display this relationship when viewing ticket B and show ticket A as its parent.

This same requirement would also apply in non-hierarchical situations (tickets C & D) with a reference from C --> D, the relationship should be exposed on ticket D as well as on C.

There are many modules available, your milage may vary:

BackReference (Drupal 6 only)

NodeReferrer (Drupal 7 beta release)

Node Relationships (Drupal 6 only)

Corresponding node references (Drupal 7 stable release)

Corresponding entity references (Drupal 7 dev release)

Content Dependency (Drupal 7 stable release)


Check if a module is enabled with JavaScript How do I check if a module is enabled using JavaScript? I want to avoid unnecessary Ajax calls that cause 403 errors since the module is not enabled.

if (mymodule_exist) {
  // Make an Ajax call.
  jQuery.ajax({
    url: "/player/status",
    type: "POST",
    async: false,
    success: function(data) {
      player_value = data;
    }
  });
}

I am trying to do something like this. How do I do it efficiently?

I can think of two ways:

Send a JavaScript flag as settings, indicating the module is active:

drupal_add_js(array('my_module' => array('enabled' => TRUE)), 'setting');

If the module is enabled, modify the output in some way so the JavaScript code that makes the petition is included only when your module is enabled, or the contrary way, make sure that code is not included if your module is disabled: you will have to use another module or some kind of configuration. The exact way depends on the origin of the JavaScript code that makes the Ajax petitions.


How can I show only webform content by excluding header,footer? I wan to show only the form elements in an modal(popup), but am not able to achieve that. Along with the form elements header, footer is also showing. So how can I remove those things for specific webform?

I tried by creating a template file with the name webform-form-162101.tpl.php. But it doesn't helped me. Please share some other way to achieve this.

If your lightbox/modal behavior can target just a section of HTML markup on the page. Some modal plugins only open full webpages, others allow targeting sections of your DOM.  It sounds like you're currently using the latter.  Here's an example of a lightweight modal plugin that allows targeting html embedded on the page as opposed to an entire webpage (but if you're comfortable with javascript, you could implement this yourself too):  https://robinparisi.github.io/tingle/

If you need the webform available on multiple pages, you could set the webform to be available as a block and then target that block to load in the modal.

To enable showing the webfom as a block, go to the Form Settings subtab/page of the webform, scroll down and expand the ADVANCED section and check the checkbox (shown below).


How to render inside a paragraph template a specific view mode for that paragragh You may say that I should just change the display settings but in my use case I need to include 2 view modes inside one template as the mobile and desktop version of the output require very different HTML.

Is there a way to do this or do I require some preprocess function to do this?

Thanks

You could try using Twig Tweak module

{{ drupal_entity('paragraph', NUMERIC_ID, VIEWMODE_MACHINE_NAME) }}

Also see the cheat sheet  for Twig tweak, it really is a great module for frontend work!


How to access fields from a goal when creating a node with Rules? I'm trying to create a rule with the Rules module that posts a node when users achieve a goal (using the Goals module 7.x-1.3). I want to get fields from the goal like the goal image and other fields, but there's no data selector for the goal completed.

I can't find a way to fetch the completed goal entity. I've tried using a data comparison condition, but it'll only give "goal" data selector without any fields.

Any hints?

Have a look at this rule (in Rules export format), which is an example of how to get this to work:

{ "rules_show_a_message_after_goal_completion" : {
    "LABEL" : "Show a message after goal completion",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "goals", "rules" ],
    "ON" : { "goal_awarded" : [] },
    "IF" : [ { "goals_goal_condition" : { "goal_id" : "2" } } ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "goal", "id" : "2" },
          "PROVIDE" : { "entity_fetched" : { "goal_fetched" : "Fetched goal" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about the \u0022[goal-fetched:ftitle\u0022 goal which you just completed:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Description\u003C\/strong\u003E = [goal-fetched:field-goal-description]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Category\u003C\/strong\u003E = [goal-fetched:field-goal-category]\u003Cbr \/\u003E\r\n- \u003Cstrong\u003EGoal Level\u003C\/strong\u003E = [goal-fetched:field-goal-level]\u003Cbr \/\u003E" } }
    ]
  }
}

Some details about this rule:

Rules Event: "A goal is completed by a user", as in your question.
Rules Condition: "The goal completed by a user", a Rules Condition provided by the Goals module (disclosure: I'm its maintainer). In my case, I used the goal with goal id = "2" (replace with the goal id that matches your case).
Rules Actions:

"Fetch entity by id", whereas the entity is a goal, and the id of it is (also) "2" (replace with the goal id that matches your case).
"Show a message on the site", which is just to demo / test some of the field values related to that goal (adapt the machine names of those fields to match your field names).

So by adding the Rules Condition "The goal completed by a user", and by also adding the Rules Action to "Fetch entity by id", in any subsequent Rules Action you should have access to all fields of the goal (with the goal id that matches your case).


Rebuild all paths for a content type I want to change all paths for a given content type.

For example is would change all node of type "image" that are currently at

/[some_token]/[nid]

to

/photo/[nid]

I am using path auto and I have lots of node (70k), what would be the way to go ?

Like @alias suggested, you can Create an SQL query that will go over the url_alias table and create whatever aliases you want.

Note: for a small number of nodes, the answer is much much simpler:

Go to admin/config/search/path/patterns to define the new URL pattern for that content type.
Open the admin/content page.
Filter by a specific node type.
Check the checkbox above the content item to select all the items of the certain type.
Select the 'update URL alias' operation.
Press 'Update'.

Two other options if you have a medium number of nodes:

Temporarily change the number of nodes per page hardcoded in core. This will allow you to use the option above with more then 20 nodes at a time.
Create a VBO content admin view to allow the user to select more then 20 nodes on a same time, then select which action to execute.


How to import a Google calendar so that it can be styled? I am wondering if anyone has any ideas regarding solutions for a custom/styled Google Calendar embed on a Drupal Website. I have a client that would like their events updated via Google calendar but is displeased with the look of Google Calendar.

I have tried tons of different modules, but nothing seems to really work well. The FullCalendar module came the closest, but the calendar appeared empty (same for other modules as well - just no events appeared in it).

I did try using the Aggregator module, but it includes some extra fields and the information shows up in Spanish for some reason!

Any help would be greatly appreciated! I'm pulling my hair out trying to figure out a way to just import these freaking Google Calendar events, or embed the calendar in a way that it is styleable.

If you are embedding it using iframe, you cannot style it with your own css or javascript as this would be considered cross site scripting.

Basically you cannot style or alter anything that is not in your own domain.

The only possible way to style it would be if Google Calendar has a setting on their website to change the style, but you would only be able to do that through their website.


how many content type fields can I have on a drupal site? I have a Drupal site for tracking equipment. I have a bunch of content types that are basically questionnaire forms that are related to the equipment. I need to associate those with specific equipment nodes.

ex. equipment node "1500" has 6 forms that each have numerous fields that need to show up under it when you view the full node. I've done this with entity views attach and it works fine. But one of these forms has about 85 fields in it. Most of these fields are checkboxes/radio buttons. Some of the other forms have 40-50 fields.

I recently noticed my site's performance slowing to a crawl after adding these fields to one of the content types and I'm worried that there are too many fields. I can't find any info on how many fields I can use though. Does Drupal limit the number of fields? Or is there some other limitation that could cause a problem?

RJ

BTW: I was going to use webform, but I can't access the fields in views with that (don't think so, anyway)

In Views, take a look at the SQL that it is generating in the preview of the view.  If you see tons and tons of JOINs, one for each field, that is most probably the cause of the slowdown.  What Drupal does is create a table for each field that is shared between content types and that means Views has to join everything back together again based upon the nid.  So, if this is happening, you might be able to improve performance by having each of these fields unique to an individual content type.  In that case, just as long as they are single value fields, they will just be another column in the database table defining the content type and can be grabbed all at once.


One-to-many and many-to-many relation between nodes of different content types I am using Relation module for creating relationship. But i didn't find the option how to create one to many, many to many relation.
Can anybody tell me regarding that
Thanks

The Relation module itself provides a block that can be used to create relations, you can create a simple relations by configuring relations and entity collector or can use the Rules module to create relations.

If your want to set up a relationship between entities than you may use the relation_add module: It provides a block that allows the user to add an appropriate relation from an entity page to any other appropriate entities, with a generic autocomplete for each endpoint, and relation fields. Tutorial for relation add module.

Tutorials for creating a relation type (administration toolbar > Structure > Relation types):
https://drupal.org/node/1276284
http://nodeone.se/en/creating-a-first-relation-type-the-entity-collector
http://nodeone.se/en/directional-relations-and-fields-on-relations

Few Tutorials that may be useful for you:
http://vimeo.com/28178686
http://nodeone.se/en/learn-the-relation-module
https://drupal.org/node/1276298
https://drupal.org/node/1276380


programmatically save image to node with link in custom module Im quite new to drupal 7. But my approach is learning by doing. This have worked fine until now....

My problem is, that I in a custom module, with a form submit, save a node with all the filled fields, including images. (Code below)

My problem is that i want to add a, a href to the images i save, so when opening the node the images will link to the link i have saved.

Is this even possible?

My node_save with pictures is like this:

$who = $user->uid;
$test = 'term_id' . $who;
$test1 = 'sales_id' . $who;
variable_set($test, $base_url . '/Sales/' . $form_state['values']['sales_id_terms']);
variable_set($test1, $base_url . '/Sales/' . $form_state['values']['sales_id_comp']);

$term_id = $form_state['values']['sales_id_terms'];
$file_temp_top = file_load($user->top_banner);
$file_temp_bund = file_load($user->bund_banner);
$file_temp_power = file_load(110);

//$file_temp_top = file_save_data($file_temp_top, 'public://firm_images/', FILE_EXISTS_REPLACE);

$node1 = new stdClass();  // Create a new node object
$node1->type = 'product_link';  // Content type
$node1->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
$node1 = node_submit($node1);
node_object_prepare($node1);  //Set some default values
$node1->status = 1;   // (1 or 0): published or unpublished
$node1->promote = 0;  // (1 or 0): promoted to front page or not
$node1->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node1->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden

$node1->title = $form_state['values']['sales_name'] . '_1';
$node1->field_betingelser['und'][0]['value'] = $terms;
$node1->field_top_banner['und'][0] = array(
                'fid' => $file_temp_top->fid,
                'filename' => $file_temp_top->filename,
                'filemime' => $file_temp_top->filemime,
                'uri' => $file_temp_top->uri,
                'status' => 1,
                'display' => 1,
);
$node1->field_bund_banner['und'][0] = array(
                'fid' => $file_temp_bund->fid,
                'filename' => $file_temp_bund->filename,
                'filemime' => $file_temp_bund->filemime,
                'uid' => 1,
                'uri' => $file_temp_bund->uri,
                'status' => 1,
                'display' => 1,
);
$node1->field_powerd_by['und'][0] = array(
                'fid' => $file_temp_power->fid,
                'filename' => $file_temp_power->filename,
                'filemime' => $file_temp_power->filemime,
                'uid' => 1,
                'uri' => $file_temp_power->uri,
                'status' => 1,
                'display' => 1,
                'href' => $GLOBALS['root_url'] . '/new-products/',
);
$node1->field_terms_id['und'][0]['value'] = $form_state['values']['kon_id_terms'];

// Add author of the node
$node1->uid = $user->uid;

// Set created date
$node1->date = 'complaint_post_date';
$node1->created = strtotime('complaint_post_date');

$new_path = 'sales/' . $node1->field_terms_id['und'][0]['value'];
$node1->path = array('alias' => $new_path);

// Save the node
node_save($node1);

The file field will handle the display of the file regarding to its settings in the FieldUI.

So referencing the fid is sufficient:

$node1->field_top_banner['und'][0]['fid'] = $file_temp_top->fid;


Drush command to show site information configuration I would like to display all available information about a site using its alias name.

the closer thing I could find is drush status.

$ drush @loc.my-project-7-26-2-5-dev status

  PHP executable        :  xxxxxxxx
  PHP configuration     :  xxxxxxxx
  PHP OS                :  xxxxxxxx
  Drush version         :  xxxxxxxx
  Drush configuration   :  xxxxxxxx
  Drush alias files     :  xxxxxxxx

I would like the site information, such as Drupal version, profile name, default theme, temporary directory path etc.. to be displayed instead.

If you are running multisite then you can do

$ drush @sites status

Or site specific

$ drush [site-name] status

Note : You should be in Drupal installation directory to run drush commands.


CSS Not Displaying Correct Via .info File (ok on page.tpl) Hello I have a strange situation that I just cannot get my head around and I hope someone can help.

If I add css directly in page.tpl as:

<style type="text/css">
  my css
</style>

Everything works as I expect. However, when I move the css to file called ross.css, and add  stylesheets[all][] = css/ross.css to my theme.info file the browser will parses the css code but the effect is not what I'm expecting. I don't know if I should post all the css in here as I don't think the code can be the problem if it displays as I expect when I insert it directly on the page.

PS: I'm using a bootrap-based theme.

I suspect it's because, when it's ross.css, your css gets applied before another .css file; while, when it's in .tpl it gets applied after.

Ex: if h1 exists with the same command, it uses the last h1 (which is in some other .css file).

JS FIDDLE EXAMPLE

So try adding !important; to your css. ex: h1 { border: solid red !important; }

JS FIDDLE EXAMPLE 2


Drupal Form PHP Passthru I will preface my post with saying I'm new to Drupal and feeling the upward learning curve but I am working my way through api.drupal.org and The Definitive Guide to Drupal 7. That being said. Here is what I'm trying to achieve.

1) Have a form collect user input.
2) When that form is submitted pass that data to the PHP passthru command.
3) Return the results preferably real time of that command as it's running. (I will settle for just getting the results right now AJAX can come later)

Where I am at: I have built a custom module to display the form. I believe my submit handler is even working and the script is kicking off. I just can't get the resulted data. Tried using drupal_get_message but nothing seems to happen.

<?php

function my_module_menu() {
$items = array();
$items['ios_upgrade/form'] = array(
'title' => t('IOS Upgrade'),
'page callback' => 'ios_upgrade_form',
'access arguments' => array('access content'),
'description' => t('IOS Upgrade'),
'type' => MENU_CALLBACK,
);
return $items;
}

function ios_upgrade_form() {
return drupal_get_form('my_ios_upgrade_form');
}

function my_ios_upgrade_form($form_state) {
$form['ipaddress'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('IP Address'),
'#required' => TRUE,
);
$form['username'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('Username'),
'#required' => TRUE,
);
$form['password'] = array(
'#type' => 'password',
'#size' => 30,
'#title' => t('Password'),
'#required' => TRUE,
);
$form['ios'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('IOS File'),
'#required' => TRUE,
);
$form['md5'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('MD5 Hash'),
'#required' => TRUE,
);
$form['ftp'] = array(
'#type' => 'textfield',
'#size' => 30,
'#title' => t('FTP Server'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
'#submit' => array('sample_form_submit'),
);
return $form;
}
function sample_form_submit($form, &$form_state) {
if (isset($form_state['values']['submit'] ) ) {
$int = 0;
$ip = $form_state['values']['ipaddress'];
$usr = $form_state['values']['username'];
$pwd = $form_state['values']['password'];
$ios = $form_state['values']['ios'];
$md5 = $form_state['values']['md5'];
$ftp = $form_state['values']['ftp'];

$message = passthru("expect scripts/ios-upgrade.exp $int $ip $usr '$pwd' $ios $md5 $ftp  2>&1");

drupal_get_message($message);
}
}

Ideally the user would be redirected to a new page to get this output, which sounds like a multi-step form would be in order. I'm trying to build this one small step at a time though before I add more layers of complexity.

Thank you in advance.

theme('status_messages') will output all of your messages those are pushed using drupal_set_message()

EDIT:

If you are processing your form via ajax call then you can return the status messages by following code example. Use it in your ajax callback where form is being posted.

$messages = theme('status_messages');
drupal_json_output(array('status' => 'OK', 'data' => $messages));


Menu options missing in node form In Drupal 8, despite the fact that there is a menu set for the content type, menu options are not showing in the node form.

I have disabled some menu modules in case they were interfering, but with no result.

What else can I check?

I found it. Silly me, it was the module Menu link (field), it actually says in the project page The "Menu settings" tab is however removed from the node form and replaced by an field widget. Argh, so much time looking for the reason, I didn't see that one when I uninstalled the ones that were interfering.


How to use Subtitles/Captions with MediaElement.js module Would anyone have some direction to upload subtitles/captions using the MediaElement.JS module?

The MediaElement module doesn't support it. In order for ME.js to display subtitles, you need to add a <track> element (e.g. <track kind="subtitles" src="subtitles.srt" srclang="en" />). The module's theme function, theme_mediaelement_video(), doesn't render that element.

In lieu of this, you can override the theme function to add the required <track> element. For example placing this in your theme's template.php:

//Here we're assuming an .srt with the same name of the video exists alongside
//(e.g. "sites/default/files/video.mp4 & sites/default/files/video.mp4.srt)
//Given you might want to upload srt files along with content
// you'll want a better solution

function MYTHEME_mediaelement_video($variables) {
  $output = '
';
  $output .= '<video ' . drupal_attributes($variables['attributes']) . ' >';
  $output .= '<track kind="subtitles" src="' . $variables['attributes']['src'] . '.srt" />';
  $output .= '</video>';
  if ($variables['settings']['download_link']) {
    $output .= '
' . filter_xss_admin($variables['settings']['download_text']) . '
';
  }
  $output .= '
';
  return $output;
}


Unknown drupal_view() function although Twig Tweak is installed Acquia BLT won't let me commit some Twig.
> tests:twig:lint:all
Validating twig syntax for all custom modules and themes...
Iterating over fileset files.twig...
  ERROR  in ~/repos/agency/client-site/docroot/themes/custom/client_theme/templates/taxonomy/taxonomy-term--faq.html.twig (line 35)
      33       {{ title_suffix }}
      34       <div class="accordion" data-accordion>
  >>  35         {{ drupal_view('faqs_per_term', 'block_1', term.id) }}
  >> Unknown "drupal_view" function.
      36       </div>
      37     </div>
 [WARNING] 28 Twig files have valid syntax and 1 contain errors.

I have installed and enabled Twig Tweak module, and rebuilt cache.
Do you know of any reason why BLT might not know the module is installed?
Possibly relevant: I'm running Drupal and BLT under Lando. The error is triggered after git push but I get the same result if I call lando blt tests:twig:lint:all directly.

If a module defines new twig filters or functions, they need to be manually excluded from the blt linter. Per a comment in the BLT issue queue, you can make these exclusions in blt.yml like:
validate:
  twig:
    functions:
      - drupal_block
      - drupal_field
      - drupal_view
      - drupal_block
      - drupal_region
      - drupal_entity
      - drupal_field
      - drupal_menu
      - drupal_form
      - drupal_image
      - drupal_token
      - drupal_config
      - drupal_title
      - drupal_url
      - drupal_link
      - drupal_messages
      - drupal_breadcrumb

This is also documented in the Overriding variables at runtime section of the blt docs (it's near the bottom of the section, under the tests: list item).


Change role of indirectly referenced users with Rules I have two content types: Courses and Teachers (with a node reference field between them) and actual users are connected to Teachers with a user reference field. I'd like to assign users to a drupal role when they (the Teacher content they are refered to) refered to a Course.
I can do it easly with a Rule if the node reference field has only one value but I can't cope with multi-value field.
I have built this rule so far:

{ "rules_oktato_hozzaadas_oktato" : {
"LABEL" : "Oktat\u00f3 hozz\u00e1ad\u00e1sa - oktat\u00f3",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Oktat\u00f3" ],
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--course" : { "bundle" : "course" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_teacher" } },
  { "OR" : [
      { "entity_has_field" : { "entity" : [ "node:field-teacher:0" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:1" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:2" ], "field" : "field_related_user" } },
      { "entity_has_field" : { "entity" : [ "node:field-teacher:3" ], "field" : "field_related_user" } }
    ]
  }
],
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-oktato" ] },
      "ITEM" : { "teacher_oktato" : "Tant\u00e1rgy oktat\u00f3i" },
      "DO" : [
        { "drupal_message" : { "message" : "Kurzus oktat\u00f3i: [teacher-oktato:field-related-user]" } }
      ]
    }
  }
]
  }
}

This setup works as I would like to but [tantargy-oktato:field-csatolt-user] is not available in 'change user's role' action. I can choose there only the individual field-teacher entries (:0, :1 etc.)

Finally I managed to solve this issue. The Conditional Rules modul is the key:

{ "rules_oktato_hozzaadas_oktato" : {
"LABEL" : "Oktat\u00f3 hozz\u00e1ad\u00e1sa - oktat\u00f3",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Oktat\u00f3" ],
"REQUIRES" : [ "rules_conditional", "rules" ],
"ON" : { "node_update--course" : { "bundle" : "course" } },
"DO" : [
  { "LOOP" : {
      "USING" : { "list" : [ "node:field-teacher" ] },
      "ITEM" : { "list_teacher" : "List of teachers" },
      "DO" : [
        { "CONDITIONAL" : [
            {
              "IF" : { "entity_has_field" : { "entity" : [ "list-teacher" ], "field" : "field_related-user" } },
              "DO" : [
                { "user_add_role" : {
                    "account" : [ "list-oktato:field-related-user" ],
                    "roles" : { "value" : { "13" : "13" } }
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  }
]
 }
}


How can I make views page with unique dates? I've made views page with node titles and dates:

Title       Post date
node1125    2016-08-09
node1137    2016-08-09
node1138    2016-08-09
node1139    2016-08-10
node1140    2016-08-10
node1141    2016-08-10
node1142    2016-08-13
node1143    2016-08-13

How can I make views page for these nodes with unique dates only:

2016-08-09
2016-08-10
2016-08-13

?

Im not sure i fully understand your question. However, assuming you want to simply have a list of dates.

Edit the view
Make sure the format uses fields
In the field section add or remove field as required (fields can be removed using the rearrange menu item , under the arrow next to add)


Users don't have access to view as soon as relation is added, drupal commerce I'm creating a new drupal commerce site and I wanted to create a view of all my products.

I didn't want to use Format: content but Format: fields instead. Of course then I needed to add a relationship to get the right fields like price (which are not part of the product display but rather the product itself) in to my view.

All of this worked rather well, I can see my view and it lists the products nicely.

The problem is that only I, the admin, can see the view.
Authenticated users and anonymous users are not able to see anything.

As far as I can tell, the query does not display a result for them...
(I added a string in the no results behavior section)

I checked all of the permissions needed for this view and made sure that all the content is published and that the view shows published content.

I did notice however that when I remove the relationship, the view does have a result.

I find this rather strange and I cannot find the answer so I turn to you.
Is there anyone here who knows what I'm missing?

Thanks in advance

This is an issue listed in the Drupal Commerce issues queue. http://drupal.org/node/1276450 Its happens when your view has a relationship to a commerce product.  I came across this earlier today when I was doing the same thing as you.

Two different solutions are suggested at comments 5 and 6 on the issues page. The first is to disable SQL rewriting under the Advanced > SQL Settings section of the view.  This can have security implications if your using contextual or exposed filters.  The other suggestion is give all user roles the 'View any product of any type' permission under permissions.  This is what worked for me.


How to disable i18n language dropdown in node form? I'ld like to prevent editors from changing the language of a node. Role check works. But I how to disable the language field? Why doesn't it work like any other form field? How is this field placed there? Where can I alter it? This doesn't work:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
        $form['language']['#access'] = FALSE;
    }
}

So, the i18n dropdown is attached to the node form afterwards. For now I simply unset($form['#after_build'][0]) where _i18n_node_form_node_form_alter is called. Unsetting it hides all other available languages from the dropdown making it impossible to change it. To me that seems fine. If there's a more appropriate way to do this, please let me know.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    if (isset($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE && $editor) {
        unset($form['#after_build'][0]);
    }
}

Finally I did it like @J.Reynolds suggested with hook_module_implements_alter to ensure that my module runs after Locale module

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    $editor = in_array('editor', $user->roles) ? TRUE : FALSE;
    $node_edit = isset($form['#node_edit_form']) && $form['#node_edit_form'] ? TRUE : FALSE;

    if ($node_edit && $editor) {
        $form['language']['#disabled'] = TRUE;
    }
}

function MYMODULE_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'form_alter') {
        $module = 'MYMODULE';
        // store
        $group = array($module => $implementations[$module]);
        // unset
        unset($implementations[$module]);
        // add to the end
        $implementations = $implementations + $group;
    }
}


How do I group items with same color We use Drupal Commerce. Products in our catalogue have various colors and we have a filter for that. I don't want to see one product in ALL colors on the product list page, but only in one; say black.

When I apply the filter to 'white', I want to see all the products in white. Ideally, without the page reload.

Our catalogue is made with the Views module.

How can I achieve this?

Add a filter of your color field and expose the filter.

Enable ajax for your view, it's listed under Advanced.

There is a catch though: I believe this only works for page views only and not for block views.


Menu to be displayed as jCarousel Is there a method to show a menu as a jCarousel? My requirement is to show each menu item as element of a jCarousel.

Short: If your "menu" was actually a taxonomy tree, it would almost trivial to do what you want, and much more, as most contrib modules operate on a entity basis.

Longer: This answer will mostly be applicable to someone that does not already have a menu structure created, so for some people, it will be of little use.

While displaying a Drupal menu in essentially any way is certainly possible, the menu system in Drupal is rather aged compared to a lot of other functionality.

Generally, whenever you wanna do fancy stuff, I would recommend you avoid the menu system completely. You can even disable it completely in D7. Yes, this type of setup will require more work initially, but is a lot more flexible.


What is the order of page load in Drupal? How does the page load order occur for Drupal?

I understand that first the modules are run and the data is returned to the view files. But which files are responsible for the view loading inside the theme?

Would it be page.tpl.php?

Also I trying to determine the page load when a 404 error is thrown. Which page.tpl.php loads the page when a 404 error is thrown?

I know that drupal_not_found() function returns the data, but how would I know which view would load that page?

With regard to error pages, Drupal has its defaults, but you can create your own just like any other node.  Just create a page for the error, then go to yoursitename.com/admin/settings/error-reporting and specify it as the page to display. You can do this for 403 and 404 errors.

The error pages are loaded just like any other. Which theme files are loaded depends highly on the theme. In Drupal 6, page.tpl.php is the top-level template file in the theme, and would be used for error pages just like any other page. However, it is quite possible to have other files that only theme certain portions of the page.

I would highly recommend a slow, methodical reading of Drupal's theming guide for an introduction. This will help you understand how Drupal decides which .tpl.php files (as well as CSS, JS, etc.) to use for a given page request.

Also, note that a lot of the details have changed significantly between Drupal 6 and Drupal 7. If you're doing new development, you'd probably be better off focusing on version 7—but of course if you have older sites to maintain, you'll need to look at the relevant documentation.


hook_form_alter checking $user->uid == $node->uid I need to check if the node uid and the logged-in user's uid are identical when the user is in the node edit form, and then add a class to the form if that condition is true.* The relevant code in my custom module currently looks like this:

function custom_form_alter(&$form, $form_state, $form_id) {
    global $user;
    $node = node_load(arg(1));
    switch($form_id) {
        case "custom_type_node_form" && "$user->uid == $node->uid":
            $form['#attributes'] = array('class' => 'test-class');
    break;
    }
}

The class is getting added even if the user isn't the author.

*Use case is that all site members with role X can edit nodes of type Y, but if the member editing the node is the author, I'd like to add some CSS.

I'm using Drupal 6.31.

hey You can simply do this :-

function custom_form_alter(&$form, $form_state, $form_id)
 {
    global $user;
    $node = node_load(arg(1));
    if($form_id=='custom_type_node_form')
     {
       if($user->uid == $node->uid)
        {
          $form['#attributes'] = array('class' => 'test-class');
        }
      }
}

I hope this will work for you.


How to display a timetable for reservable resources? Is there a module that will allow me to display a timetable in a grid similar to the attached image?

Rooms are vocabulary terms, and each of the time blocks (e.g. Elementary, Junior) are nodes of a specific content type (Time Block) which contain a starting and ending time (date field) and the term reference field pointing to the room name.

Try to use any of below modules :

Field TimeTable

  A Fields module that creates a timetable field that can be display
  through an nice weekly grid. Can be use to display opening hours or
  working hours in a very neat way.

  If you need to display office hours in a graphical way you have now a
  proper solution !

Grid Field Formatter

  the Grid Field Formatter module provides a simple way to overridde the
  display of multi-value fields to show as a grid/table with a certain
  number of columns.


Read contents of uploaded file before saving I am using hook_node_presave() to build a module (which I am new to) in Drupal 7. I am able to reference fields via $node->field_foo[$node->language][0]['value'] (which I have seen mentioned several times here in Drupal Answers).

This particular content type I am working on has the ability to upload files. I am new to Drupal 7, but I noticed that:

First, the user uploads the file
Then, the user saves the node (with a reference to the file)

How do I access the content of that file after it has been uploaded, with hook_node_presave()?

The ['value'] value is typically found on fields that just store 1 kind of thing, like a text field. Other field types use whatever they need – case in point, the file field type will have an array of many values:

$node->field_some_file_field_name['und'][0] = array(
  fid => 650, // The file ID, which is important and cool.
  display => 1, // Show the file when a user views the node.
  description => 'foo',
  uid => 7, // The user ID who uploaded this file.
  filename => some_file.pdf, // The **original** filename.
  uri => public://some-dir/some_file.pdf, // The URI to access the actual file.
  filemime => application/pdf,
  filesize => 3067583,
  status => 1,
  timestamp => 1352331360,
);

The FID is a cool thing, because the file_managed table stores the references to files (including all of the info above) and an entity only needs to know the FID in order to join with this table and get all of the file's metadata without reading the file.

To read the contents of the file, you have a few options:

drupal_realpath($uri) function to generate the server path to
the file
file_create_url($uri) function to generate an HTTP path
to the file (i.e. an image to be displayed in an <img> tag.

Not sure what you mean explicitly by "read contents", but a literal file_get_contents() would look like this:

$filepath = drupal_realpath($node->field_some_file_field_name['und'][0]['uri']);
$file_contents = file_get_contents($filepath);

If you want to check the MIME or filesize or something like that, you already have that data available to you in the field's array.

If you can elaborate on "reading" the file and what you might like to do before the file field is attached to the node, please update your post and I'll try to update this answer accordingly. There may be another, better place for your work to happen.


Scope of constants in drupal I am connecting to a third party library to connect to authorize.net. In order to begin making any calls to the library, you must first define some constants, such as:

define("AUTHORIZENET_API_LOGIN_ID", "[LOGIN ID HERE]");
define("AUTHORIZENET_TRANSACTION_KEY", "[TRANSACTION KEY HERE]");

My issue is this: I have two separate Authorize.net accounts which need to be updated, both happening as the drupal user saves his account. Currently I have one custom submit handler added to the user_update_form form but I can't use this to make both calls. Should I be able to simply make a separate submit handler for each account, or will the constant be constant though both files?

This is more a PHP question than a Drupal one...

Global constants cannot be re-declared within the same request (well, short of using an extension: https://stackoverflow.com/questions/8465155/redefine-constants-in-php).

Since everything in Drupal 7 and below is in the global scope, you can't redeclare those variables within the same request.

If it's hard-coded and causing you a problem, a patch to the module in question to allow contextually different API credentials would be the best thing to do IMO.


How to resolve the warning on my homepage, after deleting mini panel? I deleted a mini panel and then created a new one and on the homepage I keep getting a warning message and I don't understand why.

  Warning: Creating default object from empty value in panels_renderer_ipe->render_pane_content() (line 145 of E:\inetpub\wwwroot\modules\panels\panels_ipe\plugins\display_renderers\panels_renderer_ipe.class.php)

Please can someone explain why this happens? This is quite confusing ...

It seems like your problem is caused by what is detailed in the issue about PHP 5.3.9 Strict Warning on Panels Empty Value. It was first reported in Panels 3.2, and has status 'Closed (Fixed)'.

The patch in comment # 15 of it should help you resolve the error. And according to comment # 26, this patch is included as of Panels 3.4.


6 - No content displaying though content is there I'm new to drupal, moved from WordPress. I'm trying to get a local install of a client site working. I have the site running normally but no content wants to show.

The content is there, I can see it in the backend and on, say, the blog page it has the right amount of paginated links. Plus the markup and css are correct. The div is empty though.

I've disabled memcache, that might be it, plus all things on the net I could find.
- truncated the cache tables
- run update.php
- tried creating a new view, same issue

plus some others I can't think of right now.

Any help with debug pointers would be much appreciated, thanks.

This can be of due to many reasons. Check one of these,

Go to configuration/system/site information, Make sure, you have correct number of posts and front page. [Number of posts on front page ]
When you add content, then, make sure, you click on publishing option and click on 'published' checkbox. You can check the content is published or not, by making a menu link of it.
If these are okay, then, please check by changing the theme, may be your theme page is broken or something. Go to appearance and select new theme.

Make sure, you flush your system, cache and try.


Use node edit form layout for other entity types The node edit form got a nice overhaul for Drupal 8's default admin theme, whereby a lot of the metadata fields like Revisions, Meta Tags, URL Aliases, Publish status, Promote status, etc are moved into a sidebar.

I'm using the Group module, and have enabled metatag integration and revisions via patch from #2829966.

Currently however the meta tags and revisions appear in a vertical tabs block at the bottom of the edit form, making the page extra long.

How can I get those items into a sidebar like the Node edit form does?

Drupal\node\NodeForm provides it own build() method that puts the meta items into an  advanced group, and then the classy template node-edit-form.html.twig renders that group in a sidebar. The form builder also attaches the node/drupal.node library, which provides the layout CSS.

To copy this layout and style for another entity, you could implement hook_form_alter in a custom module and move the metadata form items into an advanced group like NodeForm does. You also need to theme the form with the node_edit_form template and attach the node/drupal.node library.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Select the group add/edit form.
  if (in_array('group_form', $form['#theme'])) {
    // Use the node edit form template.
    $form['#theme'][] = 'node_edit_form';

    // Use the node form layout library.
    $form['#attached']['library'] = ['node/drupal.node'];

    // Create the advanced element if it doesn't exist.
    if (!isset($form['advanced'])) {
      $form['advanced'] = [
        '#type' => 'container',
        '#weight' => 99,
      ];
    }
    else {
      // Make 'advanced' a container instead of vertical_tabs.
      $form['advanced']['#type'] = 'container';
    }

    // Add the style class to tell the admin theme how to style it.
    $form['advanced']['#attributes']['class'][] = 'entity-meta';

    // Move detail elements into 'advanced'.
    $form['detail_element_you_want_to_move']['#group'] = 'advanced';
  }
}

Alternatively, you could create your own Twig template and library and use those instead of borrowing from node.


I have a tab in mysite.com/user which I don't know where it's coming from? I have a tab in mysite.com/user called "Evaluaciones" but I don't know why is there. The link for this tab is user/1/webform-submissions-por-user then I guess it is generated by the webform module, but I already disabled this module and the tab is stil there.

How can I trace it? How Can I remove it?

Its coming from the webform module.  I believe if you turn off the ability to allow users to view previous submissions it will go away.


Post-installation PHP crash I decided to give a shy try to Drupal 8. Installation went quite smooth, but when everything was ready to hit the home page I was delighted with the following error:

  CRASH: PHP segmentation violation in method_exists() called at [/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Controller/ControllerResolver.php:72], in Symfony\Component\HttpKernel\Controller\ControllerResolver::getController() called at [/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php:117], in Symfony\Component\HttpKernel\HttpKernel::handleRaw() called at [/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php:73], in Symfony\Component\HttpKernel\HttpKernel::handle() called at [/core/lib/Drupal/Core/HttpKernel.php:52], in Drupal\Core\HttpKernel::handle() called at [/core/vendor/symfony/http-kernel/Symfony/Component/HttpKernel/Kernel.php:197], in Symfony\Component\HttpKernel\Kernel::handle() called at [/core/includes/bootstrap.inc:2208], in drupal_handle_request() called at [/index.php:12]

How would I go about solving this? Is that something of a Drupal programming error? Is that something that depends on final configuration? I kind of don't believe this would massively occur to all people, so I assume it might be caused by something in my setup.

I'm running PHP 5.3.21 with a local php.ini setting the magic quotes flags to off.
Due to the hosting, I had to comment out the htaccess bottom part for gzip compression, if that matters.

A PHP segmentation violation is a PHP bug. You can not solve this at the PHP, or Drupal level, this needs a bug report for PHP itself, here.

Segmentation violation means that PHP somehow mismanaged it's memory, which is impossible to directly cause with PHP code, since pointers aren't available.

Notice though that there are two releases of 5.3 after the one you're running, upgrading should be your action, as a problem in method_exists() should have gotten a lot of attention, and is hopefully already fixed.


Where do I make a feature request to drupal.org? What is the best place to make a feature request about the drupal.org website?

I probably spent an hour searching.  There is/was the redesign project, there is the drupal.org issue queue but I was refused access.

FYI - I'd simply like to suggest that project owners have a tab for "roadmap" or "project Future".  Sure, the summary page can include that but often it is crammed with things and maintainers forget to talk about what plans they have, what they need, etc.

Generally speaking, the correct place to post feature requests for Drupal.org is the Drupal.org customization project issue queue.

However, you also wrote:

  FYI - I'd simply like to suggest that project owners have a tab for "roadmap" or "project Future".

If you just want to suggest that project owners publish a "roadmap", you can add that suggestion to the community documentation. It is a wiki so you don't request anything - you just do it (like I just did).

If you want to actually modify the project page layout by having a feature where project owner's may add an addtional tab for "Roadmap" to the page summary, you request this in the Project module's issue queue

Finally, I shall not suggest you use the Webmasters issue queue for any type of feature requests.  The Drupal.org webmasters issue queue is for reporting spam, broken links, or user account problems at Drupal.org - and that is about it.  My experience is that nothing much happens to feature requests posted there, even if the request just involves flipping a trivial setting in a module already installed. The webmasters obviously have the power to do this, but they do not make decisions about such things.  They usually move feature requests to the Drupal.org customization project, and bug reports to the Infrastructure project.


Set wysiwyg's value with javascript How do I set a WYSIWYG's value with javascript? does the WYSIWYG module provide an api for this?

I don't know which editor user is using, so I can't use the api of editors.

The following code worked perfectly fine for me,

(function($) {
    $(document).ready(function() {
      $("#edit-body-und-0-value").val('this is a test content.');
    });
})(jQuery);

I have placed this code is test.js file. 'edit-body-und-0-value' is the ID of the textarea.

I have installed WYSIWYG module and placed CKEditor under sites/all/libraries/ckeditor folder. Although it doesn't matter if you are using CKEditor or any other editor because we are mainly referring to ID of our textarea.


How do I get Path Auto to display one value in the URL structure when node:field has multiple values? Using path auto to create a url structure, I would like the following:

my-content-type/[node:field_restaurant_category]

Note that node:field_restaurant_category can have multiple values, and in my url structure this is unfortunately the case. I have a url now that is my-content-type/t1-t2-t3-t4-tetc

How can I limited the node:field_restaurant_category to be just one and only one term? I honestly don't care which term the module chooses so long as the limitation is in place.

I read earlier that something like node:field_restaurant_category:values:1 should work, or something, but I cannot get any logical configuration of that to work correctly.

For multiple cardinality fields you can use a pattern like [node:field-name:1] (note the use of hyphens instead of underscores).

This is an example of the tokens available for a field called field_profile_categories with multiple values:

I think in your case the pattern should be:

[node:field-restaurant-category:1]

Although the comments in the token table suggest that deltas start at 0, so you might need to use [node:field-restaurant-category:0] if you want the first item to be used.


Allow markup inside drupal 8 Link function I always try to use the core functions for linking in drupal, but I'm not able to add html markup like Link text. Any ideas?

Use the Markup class:

use Drupal\Core\Link;
use Drupal\Core\Url;
use Drupal\Core\Render\Markup;

$url = Url::fromUri('http://www.example.com');
$linkText = 'My link <br> containing tags';
$linkMarkup = Markup::create($linkText);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();


Spam url_alias entries being created - how do I stop them? I'm using Drupal 6 and having trouble with url_alias spam.

Somehow spam entries are showing up in the url_alias table as aliases for valid content.

I thought an administrator or valid user would have to create these.  I don't understand how they're appearing for content that I created.

I appeared to have stopped spam registrations using a combination of Mollom, honey pot and spamicide.  I can't figure out how the url_aliases are appearing.

Can anyone give me a good place to try to start figuring this out?

Thanks,
Joe

Who have access to Administer ➔ Site building ➔ URL aliases depends on how you've set access to the permissions administer url aliases and create url aliases under  Administer ➔ User management ➔ Permissions.  If you've granted access to the Anonymous user role, everybody can do it.  If you've granted access to Authenticated user role, a rogue authenticated user can do it.

First, check out these permissions and make sure they are safe.  Leave them unchecked for all roles. Then, only the super admin (user #1) can create aliases using the GUI.

If these setting are secure, and you still get unwanted url_alias entries created, then some outsider has gained direct access to your database.  That's bad.

Finding the cause of database intrusion is not easy. Possible attack vectors are: A bad module that permits SQL injection, some means outside of Drupal (an inscure phpMyAdmin is the most common cause), or (in particular if you're on shared hosting) a host misconfiguration.

However, without having direct access to your site's and its log for forensics, it is impossible to know how an outsider has gotten into your database (if that is indeed the cause).


Node_save fails silently I am trying to programmatically update a node with a value from another entity. When I call node_save, the function just "stops". There is nothing in watchdog or in my php_logs that would indicate that any issue was encountered.

$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][] = array('product_id' => $entity->product_id->value());

dpm('This text prints.');

node_save($node);

dpm('This text does not print.'); //This line is never executed.

I have tried a variety of methods for saving the node including using entitymetadatawrappers on $node. So far, nothing I have tried has gotten me anywhere.

Thanks!

Edit:

A few more details on what I have tried/am trying to do.

This field is a product reference field that I am adding a reference to.

There is nothing at all in the php logs or the watchdog logs.

I am trying to do this as a part of custom rules action. I was originally using the add item to list action, but only one item was being added to the list (usually there will be 4-5). As a test, I tried to update and save the node manually (thus the code above).

I should have specified that part, but got a bit wrapped up in my own solution. Either way, it seems pretty odd to me.

Edit Part 2:

I have confirmed that the structure for field_product is correct. I am also doing checks to make sure that I am not referencing a non-existent field, etc.

I wasn't originally using dpms for debugging, it just seemed like the simplest way to communicate my issue. Originally I was doing some further processing on my data that was not being done. Since that further logic isn't pertinent to the problem, I added a dpm as an example. There were no errors in the following logic and it wasn't dependent on the node save.

The field structure you are using for your entity reference field is not correct. See entityreference_field_schema().

The correct column name is target_id, not product_id, so it should be like this:

$node = node_load($base_node->nid, FALSE, TRUE);

$node->field_product[LANGUAGE_NONE][]['target_id'] = $entity->product_id->value();

node_save($node);

This assumes you are using an entity wrapper to access the $entity object but not for accessing the $node object.

[edit]

Regarding your dpm() not firing, it is quite possible it is firing but you aren't seeing the output. This can happen depending on where you are calling it from.

A good alternative in these cases could be dd() or watchdog() since their output will be visible regardless of where you call it from.


Including multiple authors in Authoring information for a Drupal 7 node I have a CMS to which many people can possibly provide data. So, I would want to include all the users who have contributed the data for a node by adding new data or moderating existing data, because everyone who contributed for a node deserve themselves to be undersigned. Right now, only the first person who creates the content would be the rightful author.

How can I achieve this?

I have googled but could not get much help. The closest I could find was this, which still goes unanswered. I have checked Entity Reference module but I could not get it to auto-fill the author whenever a user edits an existing node.

I have automatic revisions enabled, which means I do have the information of each author for a node who have contributed. But how do I pull each author out of the revision information and display the collection of all authors & contributors in a nice manner at the end of each article?

Please help me find a solution, I am not that well versed with PHP programming.

Thanks & Regards,
Raj Pawan G

I accomplished this by the following steps:

Download and enable the Rules module and the Entity Reference module.
Add a field called "Foo" to your content type. Field type: Entity Reference. Target type: user.
Create a new Rule.

Add event: "Before saving content"
Add condition: Data comparison. Parameter: Data to compare: [node:type], Data value: bar (Where "bar" = your content type's name)
Add action: Add an item to a list. List: [node:field-foo], Item to add: [site:current-user]

Now every time content is saved, the user who saved it will be added to the list of editors of that page.


How to debug D8 library loading? I'm having trouble attaching a library using the new #attached mechanism in Drupal 8. Is there an easy way to debug and see which libraries Drupal is trying to load, and possibly, what goes wrong?

Motivation

In a form class, I'm returning a large render array. One of the elements has an #attached property:

$form['contact'] = array(
    '#type' => 'fieldset',
    '#title' => t('Contact'),
);
$form['contact']['#attached']['library'][] = 'my_module/contact';

In file my_module.libraries.yml:

contact:
  version: 1.x
  css:
    theme:
      css/contact.css: {}

I'm suspecting that contact.css is either not found, not loaded, or altogether ignored. Therefore I'd like to follow the process in which Drupal loads the library and integrates it into the page.

How to debug D8 library loading?
  ...Therefore I'd like to follow the process in which Drupal loads the library and integrates it into the page.

There some ways to attach a library (look here to see them), this make  a bit hard, the task to create a debug workflow following each process.

  ...which libraries Drupal is trying to load, and possibly, what goes wrong?
  ...Can someone add a general method of how to debug D8 library loading?

Well, there are some ways to see what are attached, I know two options to 'debug'.

Option 1 (check libraries)

Use a function to inspect which library was attached in your page.

function module_page_attachments_alter(&$page) {
  $array_libraries = $page['#attached']['library']; //Use a breakpoint at this line to see libraries.
}

Attention: It is not safe to see all libraries, remember, any other module or theme can use this function too (and you don't know which is called for last), said that, use this option just to check libraries of your own module/theme if they are included, if not, you messed up (misspell, attach at wrong place), you need to check your 'attach' code.

Option 2 (check for files attached in a library)

First, like pointed by @cilefen, you must turn off CSS and js aggregation in performance config tab.

Then you can check all CSS and js files at your browser.

For CSS is easier, they are organized in <head> tag:

All CSS files are grouped in by one <style> tag for each type of media. In this screen has three <style> group with media 'all', the first is base theme, the second is the core (admin bar stuff), and the last one is my theme. If you expand you will see all files:

For js, there two places, if you specified, you will find at <head> tag, if not they are all in end of your <body> tag.

Now,
 - if you miss a file, check your library if is really defined your file;
 - if not loaded (4xx, 5xx, responses to a file), check your file location;
 - and make sure that you cleared the cache.

To keep on track of my libraries I just follow some rules.

When theming, I usually avoid add things in preprocess or other function, and attach all libraries in twig template.

Using this code:

{{ attach_library('theme/library') }}

When creating a module, I just add essential code and always at end of build function and in a top level of $build var (just created a standard for me and always follow this rule).

This way is easier to find where is wrong.

Very important: Considering that you follow all rules of a .yml file and follow a schema for a library definition, sometimes its just tabs that your text edit insist to use, you indentation is wrong or you misspell something.


geofield and leaflet maps: how to show proximity-originator on map? My Goal:
Show a hotel on a map, together with nearby restaurants.

Currently, i have only a table, based on a view with the hotel's node-id as contextual filter.
Now i'd like to put all that in a map.

I think with OpenLayers i could show the hotel in one layer, and the restaurants in another.
But i'd prefer leaflet for it's size, so i did not try Openlayers yet.

Using geofield, i saw there is a proximity-filed in views.
With that, i can show the restaurants and have the proximity in the tooltip, but i can't show the Hotel.
My case would be an "abuse" of the proximity field, but i guess there would be more reasonable use-cases, which could use such a feature.

I also thought about how to do a view that contains hotel x and all all referenced restaurants, but i did not find a way yet.
Restaurants and Hotels are nodes, with hotels having a multivalue entity-reference field pointing to the recommended restaurants.

If you are using geofields you can set up a proximity filter, and in your view filters, add the geofield proximity. In the settings 'source of origin input' try 'other geofield'?  Ty mapping the hotels and restaurants using two separate geofields, one for hotels, one for restaurants. Then map the restaurant distance from the hotels as origin>


How do I translate "Please fill out this field." on the user registration form? Obviously users need to add an email address to register an account.

I'm using the Bartik theme. In Firefox and Chrome, if I don't enter a value for the email address and press submit, the form is not sent; instead, I get a JS popup, "Please fill out this field."

When I search the translation UI, I can't find this string ("Please fill out this field.")

I also can't find the string when I grep for it over the entire D8 git repository.

How do I translate this string?

This message is coming from the browser and not from Drupal, so, there's not much we can do about this, except for not using HTML5 required attributes.

I have my system in French and the message comes in French, and I don't have the French language installed in my site.

Read more about this in the Drupal core issue about "HTML5 validation is not fully accessible".

EDIT: It seems that we have a working patch that solve the problem.


Change the sorting order used for Book nodes How can I change the order used for Book nodes, which by default is based on weight and title?

I have a set of nodes displayed inside a page that use a structured book. I want to display them ordered by weight and random, instead of weight and name.

The book is used to structure different types of local companies and restaurants.

I have traced the code looking for a solution, but it's a bit messy for me.

Is there a hook that could be helpful to achieve this?

You should checkout the Book helper module.

  The Book helper module enables additional features from Drupal's menu system to improve the ordering of a book's pages. This module also allows administrators to further customize a book's navigation block.

  Features

  Enhances the book outline manager
  Adds 'enable' checkbox (aka hidden) to the manage book outline page
  Adds an 'Order' tab (node/%/order) to a book's main page
  Adds 'administer own book outlines' permission for ordering books from a book's main page
  Removes the 'Outline' tab from all nodes
  Removes the book fieldset from node edit pages if the content type does not allowed book outlines
  Removes 'add child page' and 'printer-friendly version'
  Removes book navigation
  Customizes visibility of a book's navigation elements
  Automatically 'Create new book' for selected content types
  Includes 'Book (inline) navigation' block that can be easily positioned after a node's content
  Disables new revisions from being created when a book's node title is updated
  Displays a warning when deleting a book page (node/%/delete) that has child pages


How to call field label & values in custom content type page template I have created a custom page--mycontent-type.page.tpl for customizing display with html tags classes & attributes.
I'am unable to call that content type fields & their label.
I've tried these to print values but not worked for me.

<?php print render($content['field_name']); ?>
<?php print render($page['content']['field_name']); ?>
<?php print render($fields['field_introduction']->content); ?>

Please suggest me what code call the actual fields & label. Thanks in advance :)

For the objective of adding classes to fields in a node (as you made clear in your comment) you can use hook_node_view to intercept the node and then you can change the markup of your fields.
You can find detailed examples here.


Display Suite Custom Wrappers and Custom Classes Tabs Not Appearing in Manage Display I am using Display Suite layouts for some of my pages. I want to add in some custom classes for the regions. However, the custom classes and custom wrappers tabs are not appearing on the Manage Display screen for my view modes. I am able to add custom classes on the Display Suite Custom Classes screen, but cannot apply them to the display, as the tabs are not there.

Am I missing something? I have seen videos where they appear for other users so don't know why they are not appearing for me.

Below is a screenshot showing the missing tabs.

I want to basically target the view mode as a class on the page. At the moment, it is only inserting the layout I have selected as a class, so if I am using the same layout for different view modes I can't differentiate between them if they are for the same content type.

Two possibilities come to mind.

1) Have you saved since you selected "One Column" as the layout? The configuration options change once you select something other than -None-

or

2) Have you checked that you have the correct Display Suite permissions? Namely, 'Administer classes' and 'Administer fields'


Drupal Commerce Custom Sizes I am creating a Drupal Commerce website to sale Custom Stitched Thobes in which I need to get the Measurement from the customers. I am unable to understand where & how should I add fields to take the measurements for the product he adds to cart.

Actually the idea is to offer some standard sizes like S,M,L or XL in case he don't want the standard sizes he can select Custom in Sizes Drop down, which will show up custom size text fields.

I was looking for a straight forward way to add text fields in Product Type through manage fields and check Enable this field to function as an attribute field on Add to Cart forms. so those fields can be appeared on add to cart form but unfortunately this option is not available for text fields.

Correct - the way the attributes system works, it requires you to define a SKU for every possible combination - depending on how many measurements options you have, it could be infinite. Instead you should look into line item fields that allow a customer to associate unstructured data with a product when it is added to the cart. This could accommodate both your fixed and variable sizes.


How to get a mini-calendar as a block on sidebar? I am using a Event Calendar module to display the Calendar and it is configured using views and linked with the events and popup the event when clicked.

I want a mini-calendar on front page with same events but like a mini calendar.

I have tried creating block for the view but it didn't work.

Can anyone help me how to do that?


different form state redirects in a hook_form_alter i have the code in template.php:

THEMENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'answer_node_form' && !isset($form['nid']['#value'])) {
    //dpm($form);
    // redirect after we created a new node
    $form['actions']['submit']['#submit'][] = 'node_reference_redirect';
  } elseif ($form_id == 'answer_node_form' && isset($form['nid']['#value'])) {
    // redirect after we have made changes to a node - node/17/edit
    $form['#submit'][] = 'node_save_reference_redirect';
  }
}

function node_reference_redirect($form, &$form_state) {
  $form_state['redirect'] = 'node/' . arg(1);
}

function node_save_reference_redirect($form, &$form_state) {
  $form_state['redirect'] = '/index.php';//$form['field_answer']['und'][0]['nid']['#default_value'];
}

function named node_reference_redirect() works as expected - it redirects after creating a new node: node/add/content-type, but the 2nd redirect - when we are doing changes to an existing node: node/[nid]/edit, when we press "save" it doesn't redirects to a index.php for example... Can't figure out what's wrong. Any ideas? Thanks

I think it should be like:

$form['#redirect'] = $base_url';

you are missing '#' in both of the forms.


Can I take a list of Titles from a Content Type and turn them into a Taxonomy list? I have a content type called Instructor Profiles. The title field is their name. Can I use a list of this Title field and make a Taxonomy list. Is there a way to keep a list synchronised?

Yep, it looks like I can with Node Auto Term [NAT]

  Node Auto Term or NAT is a helper module used to facilitate node-node
  relationships through the use of the Taxonomy module; i.e. when a node
  is created, a taxonomy term is also created automatically using its
  title and body in any associated vocabularies. Other nodes can now be
  tagged with terms from these vocabularies thereby establishing
  node-node relationships.


How to always show "read more..." link? Is there an easy way to always show the "read more..." link when text is trimmed in a view?

Was looking for an "Always show read-more link" option for cases when the text is not long enough to be trimmed, but there is none unfortunately. :(

Any suggestions?

Thanks!

Add the trim limit for the content field what you want.
Add the link to content field in the view and put the display content.