How do I exclude a single menu item from the sitemap? In my sitemap, I am displaying main menu and footer menu, but as per requirement I don't want a specific menu item to display in the sitemap. My footer menu has following items:

industrial
mechanics
sports

Is there a way not to add mechanics to the sitemap?

Maybe you want to consider the approach described in comment # 1 in issue # 985138 (for D7), which is like so:

/**
* Override site_map function
*/
function hide_in_sitemap_preprocess_site_map(&$variables) {
  $mids = variable_get('site_map_show_menus', array());
  $output = '';
  if ($mids) {
    foreach ($mids as $mid) {
      $menu = menu_load($mid);
      // Use menu_tree_all_data to retrieve the expanded tree.
      $tree = menu_tree_all_data($mid);
        foreach ($tree as $branch => $value) {
          if ($value["link"]["options"]["hide_in_sitemap"]) {
            unset($tree[$branch]);
        }
      }

      if (module_exists('i18nmenu')) {
        i18nmenu_localize_tree($tree);
      }
      $menu_display = _site_map_menu_tree_output($tree);
      $rendered = drupal_render($menu_display);

      if (!empty($menu_display)) {
        $title = $menu['title'];
          $vars = array( 'title' => $title,
                        'content' => $rendered);
        $output .= theme('site_map_box', $vars);
      }
    }
  }
  $variables["menus"] = $output;
}


How to get an entity create route, given an entity type and bundle? I am the maintainer for Views Add Button: https://www.drupal.org/project/views_add_button , which creates a button (link with classes) in a Views header or footer, that allows the user to add content of a particular type. Link building and access checking are meant to be handled automatically by the module, so that the user does not have to write a custom plugin or put a "view in a view" to handle access control.

While working on a Drupal 8 port I'm running into some trouble getting the correct route for entities. At this time, the options form for the plugin will pass an entity type and bundle, but given that there are many entity types, some with bundles and some without, I am not sure how to calculate the route name for a given entity-bundle combination.

So far, I've written this to manually create the URL, based on some assumptions. I left the options building out as it is not relevant to the topic:

// Get the create route
$type = explode('+', $this->options['type'], 2);
$entity_type = $type[0];
$bundle = $type[1];
$u = $entity_type === $bundle ? '/' . $entity_type . '/add': '/' .$entity_type . '/add/' . $bundle;
// Create the link
$url = Url::fromUserInput($u, $opts);

The goal is to use Url::fromRoute() instead of Url::fromUserInput, using the entity type and bundle. For example, 'node' and 'article' should return 'node.add' , which would then be given to Url::fromRoute().

Given Clive's comment, and some further thought about it, one thing I could do is create an annotation, such that custom entity developers can declare their route. Further, I can add annotations to the module that cover all core cases (node/user/taxonomy), such that the module works with core out of the box.

From there, I could add conditional logic that looks for a given entity's annotation, and if it doesn't find it, it would then make the same assumption (/{entity_type}/add/{bundle}) as above. I suppose from there either developers can declare an annotation in their own module, or if a particular custom entity is popular and keeps hitting the issue queue, I could add that as well.


Is using a TLS/SSL termination reverse proxy currently possible in Drupal 8 I use Nginx (port 443) which terminates TLS/SSL then forwards the request to Varnish (port 80) and on to Apache (port 8080). This worked really well for D7.

Am I correct in thinking that because of the following bug this set-up cannot work without 'Mixed Content' errors due to CSS and JS being written as absolute paths rather than relative paths?

References to CSS, JS, and similar files should be relative to server: less bytes, avoids mixed content warnings

I am looking for conformation of this question to ensure that it is not my server configuration at fault.

The patch you reference was applied to Drupal 8 last month. Drupal 8.0.3 was released 3 February and included the fix. If you're using this version (or later) you should be fine.


Classes get stripped out: why? I am pasting the following code into the text editor.

ABC

After the initial save everything looks fine in preview mode. However, if I go back in to edit the page, the styles applied to ul and li tags get stripped out, and the source looks like this.

ABC

How do I prevent this from happening?

I haven't met this problem before. I did Google search and found this link Classes being stripped in CKeditor. Maybe your problems come from CKeditor and you just configure the allowedContent for CKeditor.


How to support legacy url alias' and/or support multiple url alias' (Conditional Pathauto?) I am migrating a site from wordpress and need to preserve my url structure whilst supporting native pathauto urls in the future (for new content)

Overall Drupal's clean url process is almost identical to wordpress but I am finding some small discrepancies and with around 2k posts to migrate over I need a programmatic way to do this that won't feel like I'm trying to roll a keg up hill.

I was thinking of inserting in the old wordpress url as field_legacy_slug and then I could create paths based on that, but... as far as I know pathauto doesn't have any conditional abilities and I'd want to use a field_legacy_slug only if it exists, else use a standard token based pathauto pattern (site.com/2011-01-01/title-of-post)

I also don't think creating multiple alias' for content is advisable (aka letting wordpress url alias' exist beside the native pathautos) - but I am course asking you for insight into this :)

Creating node paths on import myself and allowing pathauto to catch new nodes seems like my only option but I'd hate for someone to run an "Update path alias" and ruin it all.

I believe the new-for-Drupal-7 Redirect module will provide what you need. Have not used it myself yet, but I used Path Redirect (which provides similar functionality for Drupal 6) to solve a similar problem. I generated a two-column table of values (old URL in one column, new URL in the other), and fed that to Path Redirect -- problem solved. Hope this helps.


Custom login -> admin I know it is possible, but is it advisable or even in common sense to try to implement second (own) login i.e. mysite.com/login2 and access that way to custom layout (admin page), where is some custom data to manage our own hidden things, nothing related to drupal tho.

The reason for this, I love drupal, and I would use it for frontend publishing and managing site easy. But thing is I need some sort of portal (module for drupal) to handle data from my other sources where this own login and admin comes handy.

This is currently done with custom coding, but is it possible to integrate this "custom code" to drupal with modules and use durpals see, friendly urls, database handling etc advantages?

I don't expect this to happen in no time, need to learn a lot deeper but if there is a change to do this in reasonable time and without breaking drupal itself, I would love to start developing this :)

It seems like you would like for one login to give access to Drupal site administrative functionality, and also give access to specialist non-Drupal functionality.

The easiest and most flexible way to achieve this is might be to add an extra link to the Drupal administrative menu. When someone logs in, that new link would be there prominently along side the other Drupal administrative links.

The link could point to another website, to non-Drupal pages and scripts on the same server, or to Drupal pages generated by a custom Drupal module you created.

Perhaps the biggest advantage of putting your custom code inside a custom Drupal module would be that you could use Drupal's access control system: logging into Drupal with the right role would automatically grant users (and only these users) access to your custom functionality.

Generally speaking, taking existing code and turning it into a Drupal module so that it outputs it results "through" Drupal in a minimal but viable way should be easy.

Fully converting your code to take advantages of all Drupal's API features (theming, UI widgets, etc., etc.) would be a much bigger task. It's not necessary for your stated goal, it's more something you might consider for the sake of improving the robustness of your code by leveraging the quality of Drupal's APIs.


SQL queries in theme functions - is it a bad practise? I know, that calling SQL queries in template files is bad practise. But is it bad practise also for theme functions?

For example when my form is rendering with my custom theme function:

<?php
$form['#theme'] = '_my_custom_theme_form_method';
?>

My custom method *_my_custom_theme_form_method* is placed in .module file.
Is it the same bad practise  as it is for template files?

Is it any serious performance issue, calling SQL queries form theme method?

thanks
Tomas

Any theming function only format variables passed inside them to specified format.
If you want to get some additional variables from database you should use hook_preprocess_HOOK https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess_HOOK/7.

So, in your case you should implement:

hook_theme() in module to register new theme-function;
hook_form_alter() in module to modify form theme (as showed in your example);
template_preprocess_HOOK() in module, to get aditional info from database;
[theme]_hook() in template.php of theme to format variables as you wish.

There is no any performance issues, it is "must do" practice.
If you have version control system, and you need to change some output, it's no required to change module files.


Using Search Api Solr indexed search? I Installed [search api solr module][1] and solr-5.5.2 server.
When I tried to add server in drupal backend(/admin/config/search/search-api/add-server) , I'm getting warning message as shown in attached image and I'm not able save the settings.Can anybody help me in this?
http://192.168.88.89:8983/solr/#/drupal8  is my solr server which is running

Though i added the configuration, why i'm not able to save.Is there any other settings? I have moved solr-conf/5.x files to server/solr/drupal8/conf.

For the solr core name, try using just "drupal8" instead of "/index/drupal8"

Here are the settings I'm using locally:


Ajax Framework Using Dynamically Generated Links I know, for links to be ajaxified they need to have a class: "use-ajax" and a proper url which has its own callback. For example:

Ajax Link

If the link was statically created on the server, it works perfectly fine. But whenever I add a new link with the same properties, ajax seems not to work anymore. For instance, if I remove existing link and add a new one with new url parameters:

var ajaxRightUrl = 'ajax-reader/nojs/1/' + lastNextDate;
arrowLinkLeft.find('a').remove();
arrowLinkLeft.append('');

It stops being an ajax link. Any ideas why?

you are probably missing the part to add behaviors to your new elements:

Drupal.attachBehaviors('.use-ajax');


FileField Paths works bad when upload image - the wrong way comes? I have my VPS with two sites: in first i have FileField Paths and it works bad. In second i have no FileFiled Paths and everything ok.

The error is this:

When I choose photo in the Image field and press "upload" it shows me blank image and when I open url address of this thumbnail - it shows 404. the thumbnail url is correct.

But the original image url is not corect. FileFiled paths make the original image url like this:

/system/temporary/filefield_paths/coctail-gold.jpg

but the pattern in Image field FileField paths settings is this:

blog_images/u[node:author:uid]/[current-date:custom:Y]

so this is the reasen why i see the blank image.

But when I save the post thumbnail shows correctly, so file creates.

Please what is wrong with FileField Paths?

Updated

Assuming your installation code is not altered, I would suggest:

A.

Clear log messages at /admin/reports/dblog > "Clear log messages"
Try and re-upload your picture
Check your log messages reloading /admin/reports/dblog
You should find here some diagnostic about your issue.

B.

Check your Status is nice and clear [ admin/reports/status ]

If nothing wrong so far, you should check FileField Paths Issues for similar issues, and eventually submit your experience. Drupal community will appreciate!

Hope will help.


How can I display a custom field for node reference in another content type? I have a node with custom fields that I would like to pull into a different content type. I do not want to display the full node, only one or two fields. Currently with Node Reference I only have options to display the title, ID, or the full node.

My content type has the option to list unlimited nodes of this type, so the end result could possibly have multiple node ids.

I think the best way to do this would be with a custom ph formatter but I am a little lost on how to make it work.

You can create a view for the entity reference field  with the fields whichever you want to list.

Below is the setting for the entity reference to select a view

In Field Setting--> Entity selection-->Mode -->Select Views and assign the same to "View used to select the entities *"

Here is the link to create a view of entity reference type link,


Programmatically User login not working I am trying to login users programmatically in Drupal 8. Here goes my code:

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
  exit(0);
}

I am getting the message 'Session opened for...' in watchdog. But the user is not logged in. Can someone tell me whats wrong with my code?

your code is Ok.

just add the following namespace:

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

delete in your code:

 user_login_finalize($user);

and

 exit(0);

A complete example would be.

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

$uid=1;

if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
  $user_destination = \Drupal::destination()->get();
  $response = new RedirectResponse($user_destination);
  $response->send();
ksm($user);
}

if you have installed the

  devel

module and the

  Kint

submodule,
You can use the function

  ksm()

, to show the information of a variable.


Using Rules to perform Node Export I would like to be able to use Rules to have the Node Export module create an XML file whenever a certain type of node has been updated. I have set up a Content Type with a display and an edit screen. The edit screen includes a Save button. I have also set up a Node Export which has successfully created an XML file with data from the node. It runs via a Node Export tab on the display screen of the node. What I would like to do is have the Node Export to XML occur whenever the Save Button is clicked, right after the update of the data is done. I began to create a Rule for this. For the Event, I chose "After updating existing content". However, under "Actions" I was not able to find any reference to Node Export. Has anyone been able to do this or can anyone point me in the right direction? Thank you.

The Node Export tab points to a link, so I was able to get this working by setting 'Actions' to 'Page redirect', and pointing it to the page that the Node Export tab points to, a page within the node called 'node_export', e.g. '../node/1602/node_export', where '1602' is the node id (nid). So I entered 'node/[node:nid]/node_export' as the Value of the URL to which it is to be redirected. I also left 'Force redirect' checked. Now when I click the Save button it performs the node export to XML after updating.


Modules Page: Keep Package Sections collapsed As I'm working over and over with modules, I'm constantly having to scroll past all of the Core modules and such. I can collapse module packages, but when I reload the page they are all expanded again. Is there any way to make drupal remember which module packages to remain collapsed?

This is a different approach, but installing the Module Filter module will allow you to quickly filter the list of modules by simply typing a few letters of the module's name.  Alternately, you can quickly show only the modules from the categories that you would like to see by using the vertical tabs it places on the left-hand side of the page.


redirect based on content type using rules my problem is really silly and i know I must be missing something. All I want to do is redirect a user based on the type of node being viewed.

Here is what I tried with rules:
Event: content is viewed

Condition: Content is of type: my desired type

Action: Path redirect: my desired url

Problem: when i search for anything using the search form, I always get redirected to the url I specified in the Action part of the rule.

Please let me know how to get around this

That's happening because you're reacting on the content is viewed event, which means everytime a content of the type you're describing in the conditions is displayed. You need to extend more those conditions to add the search context.

You can either compare with the site path with a "Data comparison" condition on  site:current-page:path to node/[node:nid]

A better solution would be to filter out the view mode, I'm guessing you're looking for reacting on the "Full" view mode of the node, so just add a "Data comparison" condition on view-mode and set it to Full content

Something very similar has been answered before in: How to set Rules event for "Content is viewed" from excluding Teaser view?

In any case, if you want a node type to not have a final page, I recommend the Rabbit hole module.


How do I manually configure the Link module? I would like to be able to add the file:// protocol to the list of filter_protocols so that we can add links to shared company files on a mapped drive from within our intranet website, but I'm not sure how to do this. Right now, it is apparently not included, according to Link Module Overview. Is there a way to manually configure this list in order to add file://?

You can override that in a container services file.

For example, create/edit /sites/default/services.yml, and add/alter the following lines:

parameters:
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
    - file

and make sure you have this line uncommented/added to settings.php:

$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';


Add a views with fields of nodes added from admin in the user profile I describe my scenario:

the users in their profiles must display a view (views module) with a list of fields that the admin adds each time;

I assume that the admin must add this fields from a specific content type and display this fields with a views.

My question is: how I can associate the fields of this content type to an user and how I can display in the view only the fields of the nodes that the admin have associated to the user that are displaying the view?

Any help is appreciated. Also change my approach if need.

Thank you in advance.

EDIT

Solve

I solve the issue:

Created a new content type;
Added a user reference field to the new content type;
Created a view that displays only this content;
Added a filter in the view to reduce it to only nodes that reference the currently viewing user;
Created a block in the view and place it to be only displayed on the user profile page;

With views you can display tables of items which are related to each other, like content users have created or fields of specific nodes of content.

Your question is not entirely clear. If you want to only show specific fields of a content type to a specific user those fields must be filtered by user ID, using a contextual filter.

If you want admins to be able to specify which fields are shown to which users you may want to use flags, and then filter your view of content on the flags which have been set.

If you can explain in more detail exactly what you are trying to do I may be able to help more.


Editing multiple nodes in 1 page I want to create a drupal site to record student's grades. Since every student will have a class, I want to make an assignment page that contains all the students' names(belonging to a class) so that I can record their individual grades. I do not want to edit individual nodes form by form.
However, since each student's grade is considered a node, I can only list the nodes in a view, which is not editable(unless I use the alpha release of Editable module).
This can be done easily in Filemaker but I do not know how to do it in Drupal. I wish to know what is the idea to achieve the goal? I think doing in Views is not ideal. What will you do to achieve this goal?

If you are comfortable with PHP, you could create a form that has all the students in a class and displays the student's name and then their grade.

Rather quickly, you could create a custom module and include several drupal hooks in it.  It would start out with something like this:

function YOURMODULE_menu() {
  $items=array();

  $items['class/grades'] = array(
    'title' => 'Class Grades',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('YOURMODULE_class_grades_form'),
    'access callback' => 'user_is_logged_in',
  );

  // any other menu items here

  return $items;
}

This creates a menu item so that when someone goes to

www.yoursite.com/class/grades

they will be shown a form.  NOTE:  With access callback set to user_is_logged_in, that means ANY logged in user on your site can do this but I am just trying to show you the broad strokes here.

We need to get the form, but before we go there, for another broad stroke, you will need to create a view that returns a list of student nodes. In the fields, just return the nid of the node.  If you hit preview, we want to see something like 13, 27, 55, 99, or whatever the nids are.  In that node, I am also going to assume you have a text field called grade that stores the grade for that student in the class.  For this, I will also assume this view is called just_the_nids.

Now, let's define that form:

function YOURMODULE_class_grades_form() {
  $form=array();

  $result=views_get_view_result('just_the_nids');

  foreach($result as $r) {
    $node=node_load($r->nid);
    $form[$r->nid] = array(
      '#title' => 'Grade for ' . check_plain($node->title),
      '#default_value' => !empty($node->field_grade[0]['value']) ? $node->field_grade[0]['value'] : '',
      '#type' => 'radios',
      '#options' => array(
        'A+' => 'A+',
        'A' => 'A',
        'A-' => 'A-',
        'B+' => 'B+',
        'B' => 'B',
        'B-' => 'B-',
        'C+' => 'C+',
        'C' => 'C',
        'C-' => 'C-',
        'D+' => 'D+',
        'D' => 'D',
        'D-' => 'D-',
        'F' => 'F',
      ),
    );
  }

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

  return $form;

}

What this does is grab the view you created and loops through it, loading each node and grabbing the title, which I hope is the student's name and then displays the grade of that student with radio buttons.  I know we could have returned the title and grade in the view and used it here, but just trying to "show the math" which might help later on :)

At this point, if you saved everything and flushed your menu cache, you could go to the page and see some like this:

Jill Doe
 ( ) A+
 ( ) A
 ( ) A-
  .
  .
  .

Doug Drupal
 ( ) A+
  .
  .

[GRADE]

However, pressing the [GRADE] button at the bottom of the page wouldn't do anything because we haven't declared what it should do other than just submit the form.  So we do that like this:

function YOURMODULE_class_grades_form_submit($form, &$form_state) {
  foreach ($form_state['values'] as $nid => $grade) {
    if (is_numeric($nid) && !empty($grade)) {
      $node=node_load($nid);
      $node->field_grade[0]['value']=$grade;
      node_save($node);
      drupal_set_message(check_plain($node->title) . '\'s grade set to ' . $grade);
    }
  }
}

What this does is go though the form and load each node again and set the grade field to what you clicked on in the form and then save the node back again with just that field changed (along with a perky drupal message telling you what it did :)

Now, what this doesn't do that it should for primetime:

Menu per class (unless you only have one)

Security (every logged in user can do this)

Internationalization (I didn't use t() where appropriate)

CSS Style (it isn't fancy, eg, the radios all go down vertically instead of horizontally, etc)

I assumed A-F grading, and also saved the text, You could get fancy here and store 4.0 for an A+, 3.7 for an A, etc, but right now it saves the actual text of the grade but anyway I hope it might give you some ideas on how to do it.

I also assumed D6, D7 has slightly different field structures.

A lot of information on the ins and outs of all this can be found in the Drupal Form API Quickstart Guide


Invalidating render cache items for anonymous? We have a certain content type in Drupal 8 that has a small grid of data on it that is populated from an API call when the node view is being built.

In that call, I am checking for cache and setting cache instead of talk to the API every request:

if ($cache = $this->cache->get($cache_key)) {
  return $cache->data;
}

// $content = request...

$this->cache->set($cache_key, $content, REQUEST_TIME + 3600, ['mymodule']);

Where $cache_key is just mymodule:remote_id:subscription_id. My default cache bin is handled via Memcache.

The Drupal page cache time is set to 30 minutes, and Varnish sits in front of it for anonymous traffic.

I am noticing that even though my custom cache data is set for an hour timer, and the Drupal cache is set for 30 minutes, users are able to see data from 3 days ago but I am not sure how. As soon as I go view the site (authenticated) and refresh, the data updates.

I tried backtracking this but nothing jumped out as missing, perhaps other than some cache tags I might need to add. Even still, the render object is what is being shown from cache, which the data is a part of before it is cached, not the cached data item itself.

System cron is running every hour. Shouldn't it purge invalidated cache as part of system_cron?

Edit: I switched my local from Memcache back to the default cache (MySQL) and noticed render cache items all have an expiration of -1.

At what point are entity render cache items invalidated? I feel like that might be my issue, but not sure how to address it.

the max-age (maximum age) ... defaults to "permanently (forever) cacheable"
...
Cache contexts, tags and max-age must always be set, because they affect the cacheability of the entire response. Therefore they "bubble": parents automatically receive them.
Cache keys must only be set if the render array should be cached.

from https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays
Render arrays are cached indefinitely by default and setting the page cache expiration time doesn't change the cacheability metadata of render arrays in general. As on the linked page above, ideally you do something like:
// Merges the cache contexts, cache tags and max-age of the config object
// and user entity that the render array depend on.
$renderer->addCacheableDependency($build, $config);
$renderer->addCacheableDependency($build, \Drupal\user\Entity\User::load($current_user->id()));

But this doesn't work here because the data lives outside of Drupal - or more specifically, if you add anything that doesn't implement Drupal\Core\Cache\CacheableDependencyInterface as a dependency, the render array is marked as non-cacheable and it bubbles up: see Drupal\Core\Cache\RefinableCacheableDependencyTrait::addCacheableDependency().
So in this case I think you just have to set the max-age yourself.


Drupal Blog Post templating I would like to know how to add to a template file a blog post content rendering code so that all blogs will be displayed whenever that template is rendered.

You can copy node.tpl.php and rename it to node--blog.tpl.php for any blog specific changes. Find more about Drupal Template changes


Display success message after submitting form I am try to display an success message after submitting my form and redirect to next page. The code I am using is the following.

public function submitForm(array &$form, FormStateInterface $form_state) {
  drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

It doesn't work for me.

Is there any alternate way to do it? What code should I use to display a success message?

The code you are showing is the same code Drupal core uses, for example in BanDelete::submitForm().

public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  drupal_set_message($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}

As drupal_set_message() is used from Drupal core in submitForm(), that is expected to work. I cannot say why it doesn't work in your case, since you don't show the full method code. It could also be there is a module that is interfering.

As for more OOP code, starting from Drupal 8.6, drupal_set_message() has been replaced with a service. the same code I showed (which is Drupal 8.4 code) has been changed to the following.

public function submitForm(array &$form, FormStateInterface $form_state) {
  $this->ipManager->unbanIp($this->banIp);
  $this->logger('user')->notice('Deleted %ip', [
    '%ip' => $this->banIp,
  ]);
  $this->messenger()->addStatus($this->t('The IP address %ip was deleted.', [
    '%ip' => $this->banIp,
  ]));
  $form_state->setRedirectUrl($this->getCancelUrl());
}


Allow users to edit just the vocabulary that belong to them? I allow users to create a taxonomy vocabulary. Then I need to be able to give permission to each user to edit their own vocabulary. I looked at the permission page but I don´t see anything like Edit own vocabularies.

Is there any way I can accomplish this.

Thanks.

The Taxonomy Delegate module (http://drupal.org/project/taxonomy_delegate) and the Vocabulary Permissions (http://drupal.org/project/vocabperms) let you delegate administration of a taxonomy to a role, but they do not do it for an individual user. You might be able to write a custom module from here, but what you're proposing goes a little against the role-based permission architecture. My search didn't seem to find one that does exactly what you want.


How do I dynamically change the title of a menu link? I made a menu in administration, structures, menu. I want to change the title, as it appears on the menu, of one of the links based on the gender of the currently logged in user.

I have found several answers to similar questions but I can't figure out how to implement the solutions. Some of them suggest using hook_menu_alter(&$items) and a separate callback function, but I don't understand the structure of $items. I was hoping to just print out the value of $items, find the string I wanted to change, and change that value in $items in the hook. Apparently, though, you can't debug the $items variable because hook_menu_alter is rarely called. I tried to figure out the structure of $items from a bunch of other questions and answers and I found stuff like this:

$items['user/%user_category/edit']['title']

Why is 'title' a property of a path? Does this mean that every menu on your site that has a link to that path will display the title that you set the above variable to? What if you wanted a link to a specific path on one menu to have a different label than a link to that path on another menu? Isn't there somewhere I can access and change the title of a menu link like this

$allMenuData['My Custom Menu']['an item on my menu']['title']

You might try hook_preprocess_menu_link()

function MYTHEME_preprocess_menu_link(&$variables) {
    global $user;

    if (isset($variables['element']['#original_link']['menu_name'])
        && $variables['element']['#original_link']['menu_name'] == 'my-menu-machine-name'
        && $variables['element']['#title'] == 'ORIGINAL LINK TITLE') {

        $new_title = (check for gender) ? 'New title 1' : 'New title 2';
        $variables['element']['#title'] = $new_title;
    }
}

Fill in your menu machine name, the title you want to change, the conditional for the gender and the new titles depending on the gender value.


How to show search results in view within panels? I created view & content pane that has many filters and also search term field.
In addition, I created a page with page manager and panels, that present this search view (content pane), with more different panels.

My goal is to have search field, on the header of the site, that will be available to user in any time. when the user will decide to use this search field, it will direct them to the search page I created (using page manger & panels), and will show the search results on this specific page.

Can I do that?
If so, can you please explain me how?

I read on how to that using views alone, but I couldn't understand how to that with the use of page manager and panels all together.

Thanks.

If I understand the question correctly, you would like to send users from a search form to a specific (custom) search results page (which happens to also have some other panels etc on it).

I do not believe the panels/page manager aspect really affects how the search box operates, in which case all we have to do is specify where you would like the search form to send the user.

The following code (for an imaginary module entitled customsearch just found existing module entitled custom_search, not related).

creates a block to hold a search form (you can then place this wherever you want)
constructs a simple textfield search form to go in the block
defines a custom submit to pass the search argument to your customised search results page

1)

// Implements hook_block_view().
function customsearch_block_view($delta = '') {
  if (user_access('search content')) {
    $block['content'] = drupal_get_form('customsearch_block_form');
    return $block;
  }
}

2)

// Implements hook_forms().
function customsearch_forms() {
  $forms['customsearch_block_form']= array(
    'callback' => 'customsearch_box',
    'callback arguments' => array('customsearch_block_form'),
  );
  return $forms;
}

// Form builder; Output a search form for the search block's search box.
function customsearch_box($form, &$form_state, $form_id) {
  $form['customsearch_form'] = array(
    '#type' => 'textfield',
    '#title' => '',
    '#title_display' => 'invisible',
    '#default_value' => '',
    '#attributes' => array(
      'title' => t('Search the website'),
      'placeholder' => t('search the website'),
    ),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Search'));

  // define function to determine search destination
  $form['#submit'] = array('customsearch_search_box_form_submit');

  return $form;
}

3)

// overide submission of search query from block
function customsearch_search_box_form_submit($form, &$form_state) {
  $searchterm = $form_state['values']['plus_search_form'];
  $search_path = 'specialcustomsearch'// replace with the path to your search results page
  // pass search term to your search results page as argument
  drupal_goto($searchpath .'/'. $searchterm);
}


How to use Views Photos Grid module with custom minimal theme I use Views Photos Grid module and it shows the results correctly with Stark theme.
However, it shows all the images stacked in only place in my custom theme.
I do include modules css and js files:

<link rel="stylesheet" href="/modules/views_photo_grid/css/views-photo-grid.css">

I also render the expected divs:

...more views-photo-grid-item divs are here...

Java script console shows no errors.
I've checked in debugger that the main JS function (function ($, Drupal, drupalSettings) is called but none of the other JS functions is called.
Could this be the cause?

Issue was missing JS includes.
The working set is:

  <script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"screenshots","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","google_analytics":{"trackOutbound":true,"trackMailto":true,"trackDownload":true,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"viewsPhotoGrid":{"gridPadding":"1"},"user":{"uid":0,"permissionsHash":"797a0805952a191ed3acd8cc0feee5a8b53895cab4446ce069563dbdd87139da"}}</script>

  <script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
  <script src="//code.jquery.com/jquery-3.3.1.min.js?v=3.2.1"></script>
  <script src="/core/misc/drupalSettingsLoader.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.init.js?v=8.6.3"></script>
  <script src="/modules/views_photo_grid/js/views-photo-grid.js"></script>

It doesn't work without the first messy line with data-drupal-selector. I wish I knew was is this good for...


Display categories in views to get chosen and to display specific tags I wonder if there is a possibility to display categories and after clicking them, views display only specific category's items. Is it possible?

Yes, You can able to list taxonomy terms of specific vocabulary using views.

You need to create a custom block and a view for this..

A custom block, Which lists all vocabularies .. Views doesn't support vocabulary listing..
Two, A view which lists specific vocabulary terms. You need to pass vocabulary id to this view in an URL and read it using contextual filters to filter the terms by category.

You can get list of vocabularies using below api function..

taxonomy_get_vocabularies

Link the vocabularies terms to some path like category/list-terms/{vid} .. make category/list-terms/% as your view path and read the argument using contextual filter vocabulary id to list terms..


Authenticated users must be able to flag webform submissions Authenticated users must be able to flag webform submissions.

How can I make this work?

Navigate to /admin/structure/flags/add/node and create a flag (do not check the "global" checkbox). For "Bundles" (on the same form, check "webform").

On that same form, review any of the various other options available to define/refine the flag to be created, such as:
- Flag Access,
- Display options,
- Link type,
- Etc.

Then use the "Save Flag" button.

A few other questions that may help to get you going (which are like variations of this question):

Any way to flag users who previously submitted a webform on revisit?
Adding a "processed" flag to a Drupal Webform, that admins can use to indicate whether or not they've dealt with a particular submission?

Note: The Webform Flag Submissions sandbox is for D6 only (I'm assuming this question is about D7, is it?).


Change URL of ?q=user By default, Drupal uses site.com/?q=user or with clean URLs enabled, site.com/user to display the user login page. However, that is conflicting with my hosting provider's own rewrite settings, where navigating to that link brings up the actual web server admin login. Is there a way to override this?

I think your hosting provides default cpanel url is /admin

In that case you need Rename Admin Paths module.

The purpose of this module is to secure drupal backend by overriding admin path.

Overview

This module allows you to:

rename path like '/admin/...' to '/something/...'

rename path like '/user/..' to '/something else/..'


How to render a field in a Views' PHP code field? in a view, I would like to render the field $data->field_field_video[0] in a PHP code field.
It seems that it contains all the information needed to be formatted but how can I output in the HTML ?

 [rendered] => Array
    (
     [0] => Array (
                [#theme] => image_style
                [#path] => public://video_embed_field_thumbnails/vimeo/58413545.jpg
                [#style_name] => square_thumbnail-100 [#children] =>  [#printed] => 1 )
      ...

Thanks

<?php
  print drupal_render($data->field_field_video);
?>


Force nodes created by Feeds module to be published even if nodes are unpublished by default How can I do this? Force nodes created by Feeds module to be published even if regular nodes are unpublished by default.

Implement hook_nodeapi() for the 'presave' operation to set the node status to published if there is a new one created by Feeds:

function MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op === 'presave' && empty($node->nid) && !empty($node->feeds_node_item)) {
    $node->status = 1;
  }
}


Ajax in drupal 7 dont return values Im in drupal 7, i need to make a select with many options, depends of the option taken, in a textarea will be loaded several values in a string.

After hours of test i come here for help.

Im working on a basic page:

function ajax_load_all_admins($form, &$form_state) {
    $form = array();
    $form['changethis'] = array(
        '#type' => 'select',
        '#options' => array(
            '' => '',
            '1' => 'Cargar todos los admins'
        ),
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'ajax_load_all_admins_callback',
            'wrapper' => 'listaCorreos-div'
        )
    );

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

    if (!empty($form_state['values']['changethis'])) {
        $payments_list = db_query('QUERY WORKING WELL');

        $value = '';
        foreach ($payments_list as $payment) {
            $value .= $payment->admin . ',';
        }
        trim($value, ',');
        $form['listaCorreos']['#default_value'] = $value;
    }

    return $form;
}

function ajax_load_all_admins_callback($form, $form_state) {
    return $form['listaCorreos'];
}

$form = drupal_get_form('ajax_load_all_admins');
print drupal_render($form);

The Ajax call is working but i only recibe:

0: {command:settings, settings:{basePath:/, pathPrefix:,…}, merge:true}

No other one position.

I think it can be for the drupal_render, but dont know why?

Thanks in advice.

After 1 week searching and trying things at home i decide to make a separate module for the form.

When i pass the code to a module all works fine with the same code.

I think for any reason Drupal needs to render form by his own, not forced like i was doing with the next code in a simple view:

$form = drupal_get_form('ajax_load_all_admins');
print drupal_render($form);

Hope this help, dont try to make Ajax calls inside a simple view like i tried.


View block filter by taxonomy term (field) I am doing some block experiments because I'm new in Drupal and I want to know if I can create a view block to place X(more than one) times in the same page with different results by taxonomy term content.

I have a new content type which its related(a field) to a taxonomy term, and I want to place the same block for each taxonomy term created and inside the block show the created content related to that taxonomy term.

Ex: Imagine you have a taxonomy term called "Vehicle type". We create two terms into "Vehicle type"(car and truck).
Now I create a content type called "Vehicle info" and I create.

I create a new "Vehicle info" content with a field "Vehicle Type" and check Reference type -> Vocabulary -> "Vehicle Type".

So now I want only a Block which can be placed twice in the same page and each block must list "Vehicle type" contents (one will have cars and the other trucks list).

I tried with contextual filters but when I place the block it does not shows to choose cars or trucks terms.

Many thanks :D

What is the criteria according to which the two different blocks will "know" whether you want to show cars or trucks?

If you want to control this, and have two separate Blocks showing different term-related content, you can create two Blocks but add regular Filters to them, filtering to show content related to either cars or trucks. The add each separate Block where you want them in a theme region.

If you want an automatic solution where a contextual filter does everything, you usually want to show either cars or trucks, but not both on the same page. Contextual filter will "sense" the context, it will recognize something on the page you're currently viewing, and where you placed the Block, and it will pass this context info to your Views, and filter results according to it. This is commonly used to place Blocks on Node pages, where you want to show other content that has been tagged with the same term. For example you're viewing Car1 node, and want the Block to list all the other nodes that have also been tagged with the term "car", so you would see Car2, Car3 etc. Besides the Contextual filter to pull the related content, you will also want the second contextual filter that would exclude the current node from the list, because it doesn't make sense to the visitor to see it there. You will need to adjust Contextual settings when placing the Block in a theme region.

The third option may sound the closest fitting to your description: Create One Block listing all nodes of that type, add the Field for the Taxonomy reference field, and under Format use the Taxonomy reference field to "Grouping field Nr.1". This will list all content but it will be Grouped in clusters based on the "car" or "truck" tags. You can edit the Field and "Exclude from display" because you will see it in the group title. There is no need for Contextual filters here as you want to list everything, you only want it separate into groups. Place the Block in a theme region and adjust visibility...

You can add the same Block to display in Drupal as many times as you want, in the same theme region, or in a different place, but you can't make it behave differently. A Block with a Contextual filter can show different results only if the Context it's surrounded with is different. But if on the same page, the context is the same, and the result will be the same.

BTW the "Vehicle type" is a Taxonomy Vocabulary, and the "car" is a Taxonomy Term.


How do I configure a view that gets a taxonomy on a node, and retrieves fields from the taxonomy? I have a view, which only appears when you navigate to certain nodes.

Each node which it appears under, has a taxonomy with a field called 'related_content_entity' referencing some related content. The node only has one taxonomy. I need the view to display data from the related_content_entity for the current node's taxonomy.

The brick wall which I have seemed to hit, isn't the entity reference, but filtering the results down to the one field referenced in the taxonomy associated with the node.

I get expected behaviour up to this point; creating a required relationship to the entity reference like this:

Gives me this result:

Which is entirely expected. But specifically what I can't figure out it how to filter these results down to the current node's taxonomy field. There's not a single contextual filter which I've tried which would filter the result down to only the node's taxonomy's field.

To put what I'd like to acheive more clearly:

Node-1 is under taxonomy-1, and taxonomy-1 has node-2 as an entity reference (though the entity reference module) in one of it's fields.

When view-A appears on Node-1, I'd like view-A to display the entity reference.

How do I do this?

Edit: This is my current set-up. This the input:

And this is the output:

@rooby, thanks for your help, but I don't actually get any results if I add any contextual filter under the sun.

Hi,

If you construct your view like the below and get the value from URL, you should be able to achieve.

EDIT: Allow me to guide you step by step:

You go to /admin/structure/views
You click on Add new view, and enter your view's name and description in the related fields in the next screen
Choose Content from the Show dropdown and your display format from the Display format dropdown and click Continue & edit.
Add Content: All taxonomy terms as a field, make your settings, and click Apply.
In the advanced section (to the right most section), add Nid as a Contextual Filter and click Apply (all displays).
Choose Provide default value and Content ID from URL, and click Apply (all displays

That's all there is to be done. You can test this by passing a node ID in the Preview with contextual filters field.


Remove calendar hyperlink Can see black circle at the picture below?

How to remove that hyperlink?

I found it. Due to i only want to post month calendar only. To solve this, just disable day, week and year in the view.


How do I remove the site name from the head title in drupal 8? The <title> element in the <head> of every page currently has the form
page_name | site_name. I would like to make this have the page name only site wide. I've found advice about how to do this in earlier drupal versions (eg here), but not for drupal 8. How is this possible?

Thanks

Until metatag's module port has not finished you should code a bit for doing that.

If I were you I'll edit YOURTHEME.theme file and add this:

/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function YOURTHEME_preprocess_html(&$variables) {
    unset ($variables['head_title']['name']);
  }


Drupal equivalent of Starkers As most of you probably know when themeing in Wordpress you can use Starkers as your base theme. This clears up the view to show pure semantics so you can style and theme cleanly.

Is there an equivalent for Drupal?

If you're looking for clean and easy base themes, there's Stark (which has a contrib version, as well as the version in Drupal core)

  This contrib version of Stark is an exact copy of the one in Drupal 7
  core with one exception. This version now uses a responsive design that matches a Drupal 8 proposal to make Stark use a responsive layout.

There's also Mothership, which I've never used - but it looks pretty awesome!

  The Mothership is a HTML5 base theme that offers a workaround to
  Drupal’s obscure love for wrapping everything in 2 divs and slapping
  on 3 CSS classes wherever possible.


drupal_http_request() with POST returns a 405 error I am trying to call an external API with a POST method which is working fine on Postman, but when trying to implement it in a custom module using drupal_http_request() I am getting a strange error.

  The requested resource does not support http method 'GET'.

This is the extracted cURL command from Postman: curl --location --max-time 2000 --request POST 'https://example.com/api' --header 'Authorization: [token]' --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'subject=Lead XXX' --data-urlencode 'firstName=XXX' --data-urlencode 'lastName=XXX' --data-urlencode 'Email=test@test.test' --data-urlencode 'Mobile=XXX' --data-urlencode 'Interest=XXX ' --data-urlencode 'meetingdate=2020-04-20T13:00:00.000'.

This is the code I am using.

$url = 'https://example.com/api';
$data = [
    'subject' => 'XXX',
    'firstName' => 'XXX',
    'lastName' => 'XXX',
    'Email' => 'test@test.test',
    'Mobile' => 'XXXX',
    'Interest' => 'Testing',
    'meetingdate' => '2020-04-20T13:00:00.000',
];
$options = [
    'method' => 'POST',
    'headers' => array(
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Authorization' => [token],
    ),
    'data' => json_encode($data),
];
$request = drupal_http_request($url, $data);

I have the feeling this must be easy, but I couldn't figure out what I'm doing wrong. I search the documentation, searched here with no luck.

Any hit will be appreciated.

In your post request you have specified

'Content-Type' => 'application/x-www-form-urlencoded'

but your post data is in JSON format.

Perhaps you need

'Content-Type' => 'application/json'

alternatively, pass the raw $data array as the post data for key=value&key1=value2 form encoding.

You also need to pass the function parameter $options instead of $data

$request = drupal_http_request($url, $options);


How to build Taxonomy Menu with Parents and terms based on node? After prowling here and Google for a couple of weeks, and not finding the answer, I submit.

I need help assembling a Views-made block, in Drupal 7, that will display links to the pages of each term marked in the content node. I also need it to have a structure of:

Parent Term

Term Link
Term Link

Another Parent Term

Term Link
Term Link

So far, I cannot get the block to display any results, until I remove the Contextual Filters (that I read I'd need.) Does anyone have any guidance? I've installed/uninstalled, made/deleted more Views, Blocks, and Modules than I'd prefer to. I need for this one menu to take shape, before I can move ahead with development.

Here's what I ended up having to do:

create a new view of Taxonomy Terms, unsorted.
Add Term: Name, & Vocab: Name as fields.
Set format as HTML list, grouped by Vocab: Name.
Add Taxonomy Term: Content with term relationship
Add Content: Nid contextual filter

I then added a filter to exclude certain vocabularies, and finally, added a weight sorting for both term & vocab names.


#markup is replacing colon in <gcse:search... tag with space I have the following code:

 return array(
      '#type' => 'markup',
      '#markup' => '<gcse:search queryParameterName="query" resultsUrl="'
        . Url::fromRoute('cn.search', [], ['absolute' => TRUE])->toString()
        . '"></gcse:search>',
      '#allowed_tags' => ['gcse', 'gcse:search'],
    );

but the output is:

  <gcse search queryparametername="query" resultsurl="http://d8.constitutionnet.org/search2"></gcse>

How do I prevent the colon being converted to a space?

Use an inline template:

  return [
    '#type' => 'inline_template',
    '#template' => '<gcse:search queryParameterName="query" resultsUrl="{{ url }}"></gcse:search>',
    '#context' => [
      'url' => Url::fromRoute('cn.search', [], ['absolute' => TRUE]),
    ],
  ];


Facet filter in Views wrongly returns "No results" I'm running into a strange behavior with Search API and Facets API, and I hope someone can point what I'm doing wrong.

I am working in Drupal 7 with Views, Search API, Database Search (search_api_db), Facets API, and Search Facets (search_api_facetapi). My view is working fine otherwise: exposed filters and facet filters work fine in isolation.

The problem happens when I search using an exposed filter, and then try to narrow it with a facet filter.

First step: I search using a exposed filter (see image 1). I get 606 results which display fine.

Then I try to narrow clicking "2" in the facet "Filter by level". The field level is an Integer, and is indexed by Search API as an Integer. Weirdly, I supposedly get 33 results (the View says "Displaying 1 - 20 of 33") but NOTHING gets displayed in the View body (the View says "No results"). Still, the pager at the bottom correctly indicates that there are 2 pages.

Any help will be appreciated.

PS: The field "Composer" is indexed as Fullsearch.

I figured out what the problem was. I was using Indexed Node: Composer for the exposed filter instead of Search: Fulltext search (the field composer was indexed as a fulltext index).


Migration has spun ubercart into checkout redirects I just migrated Drupal from my development site to my production site. This included a full database migration as well as a file migration.

Now, after adding products to my shopping cart and then clicking the checkout button all that happens is that the shopping cart refreshes. This happens whether or not I'm logged in.

I had a very similar problem with Ubercart in my site as well. The difference is that I would end up getting told that there was an infinite redirect and that seem to be quite what you're hitting. However, the root cause might be the same. I had an error in an email template that was supposed to get sent after completing checkout. I would suggest checking your server logs and possibly even setting display_errors = On in your PHP config. Also check your Watchdog logs for any errors.


How do I set up Search API index as cron task? From what I've read in Search API's settings, it sounds like pages should be indexing when cron is ran. This doesn't seem to be the case, but perhaps my logic is flawed.

I help manage a blog/news site. All of the content is indexed through search API, and I'm rendering lists of that indexed content using Views. One View display renders a list of the site's most popular content. This is calculated using the Statistics module. You can see here that I'm sorting this view using the Number of views field:

Initially, I didn't think that the sort criteria was working at all. I added the Number of views to the rendered output for testing, and found that the pages weren't being reordered when the page views changes.

However, I eventually discovered that the nodes will reorder, only after Search API is reindexed manually. Currently, Search API is set to index nodes immediately upon publishing, but I'm assuming that a full reindex does not occur when this happening. I tested this by creating a new node, and found that the order of nodes did not update. I've also run Cron manually, and have found that this does not work either.

Now, I'm of the impression that Search API is not reindexing when running Cron, but I'm unsure if this is a valid assumption. If it's not, I'd like to set up a nightly reindexing. How do I go about writing this cron task?

You are right insofar as a node will only get reindexed when it is updated. Someone viewing the node isn't seen as an update, so incrementing the number of views won't cause the node to be reindexed.

It's not normal to rebuild the entire index on a schedule. Cron only re-indexes those nodes that have been marked as needing to be indexed.

There are two ways I can think of you might schedule a nightly rebuild of the index.

If you have access to the server at command line level you could run the drush command "search-api-reindex" via a custom cron job. Run it as the same user as the web-server (eg. apache or www-user) and use the -l option to specify the url so the cron line would be something like: 0 23 * * * cd /var/www/home && drush sapi-r default
Otherwise you could write your own cron hook in a custom module to do the same. The module elysia_cron would help with scheduling it for the right time. You'd need to call search_api_index_reindex('default'); to have the same effect as the cron job in point 1.


Add a "Like" button after "Edit" and "Reply" links How can I add a Like link using the Flag Module, exactly after the Edit and the Reply links?

I know I must use print flag_create_link('bookmarks', $node->nid);, but I don't know exactly where to place it.

Implement hook_node_view() in a custom module that you create.

$node->content['links'][] = array(
  '#markup' => flag_create_link('bookmarks', $node->nid),
);

Or use the function MY_THEME_preprocess_node() in your template.php and add:

function MY_THEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['content']['links'][] = flag_create_link('bookmarks', $node->nid);
}

Replace MY_THEME with the name of your theme.
Some reading that might help you: http://www.whenwhowhere.com/tech-blog/add-variable-theme-template-files-drupal-7


Drush Make doesn't do anything (Windows) I've been trying to use drush make on a very simple test project (an empty folder containing just the make file) to see how it works, but nothing happens. In the shell, there's a one second delay after I press ENTER, and then the empty prompt comes back. There's no error or confirmation message, and nothing changes in the test folder (not even en empty folder is created).

The command I use is simply: drush make test.make.yml test
(Of cource I'm already in the correct folder when I type this command.)

If I omit the last parameter (e.g. drush make test.make.yml), then drush waits one second, then asks if I want to "make new site in the current directory ? (y/n)". But if I press Y, still nothing.

drush make -h shows the expected help information.

I'm using drush v.6 on a Windows 8.1 xampp local setup. The usual drush commands (e.g. drush dl views, etc) work fine, though. (As far as I can tell anyway: I'm not an advanced user.)

I tried with the example file provided in the drush/make documentation, and I also tried to simplify the content of my make file to the max:

api: 2
  core: 7.x
  projects:
    drupal:
      version: 7.36

Still nothing.

Is there something I'm missing?

I might be mistaken, but I think the YAML format for Makefiles is for Drush v.7 and later. I am using the "old" format with Drush v.6 (and Drupal 7), also on Windows

Might that work with the sample below?

; Drush Make API version
api = 2
; Drupal core
core = 7.x
projects[drupal][version] = 7.36

Hope it helps,


Create an entity within an entity Hopefully there is something out there to do what I want. I imagine my terminology is off hence why my googling is failing.

I have two content types.

Album & Track.

I want to create a new Album. When creating an Album I want to be able to reference tracks to it. I know I could create the tracks first then use the entityreference module to add those tracks to the album.

What I want to do is to create the Tracks on the fly. So have an Add track button, fill in the fields for track and then for it to be associated with the album.

For my purpose Track does not need to be it's own content type but I need to able to capture more than one field when pressing the add button.

Any ideas if there is anything out there for this?

If not I can try hacking together something in code.

You want to use references and something like the Inline Entity Form module.

  Provides a widget for inline management (creation, modification,
  removal) of referenced entities. The primary use case is the parent ->
  children one (product display -> products, order -> line items, etc.),
  where the child entities are never managed outside the parent form.
  Existing entities can also be referenced.


How does a user subscribe to a group with GCC? I have the Groups, Communities and Co (GCC) module installed [7.x-1.0-beta2] but I cannot find a way for an authenticated user to subscribe themselves to a group. I have moved the 'GCC Subscription block' so that it's in the sidebar but whatever I do it's still not visible to any user. Has anyone else run into this, probably very simple, issue and found a solution?

When you add the GCC Subscription block to the sidebar, It will not show. The only time it shows up is if a user is subscribed to a group. And then the block shows up with the unsubscribe button.

That's not true.

Here are the basic steps to make the subscription block work :

Enable GCC, GCC Context Detection, GCC Node, GCC Block
Go to admin/config/gcc/permissions and make sure NON MEMBER has the "Subscribe" permission
Go to admin/config/gcc/context, check everything and save.
Place the GCC Subscription block where you want.
Create a group.
Go to your group page with another user and you will see the subscription block


Is there any example for real project where field of deciamal type been used? Drupal has several types of numeric fields:

integer
float
decimal

I know, that decimal field is used to store numeric data with high accuracy. But when it may be necessary in real project? Are there any good examples?

Here's a link to an explanation of Drupal's different number types (integer vs. decimal vs. float) with some examples. Basically, it breaks down as follows:

Integer: You're storing numbers without fractional digits (e.g. a field that stores a product stock quantity, XX units)
Decimal: You're storing numbers with a fixed amount of fractional digits. (e.g. a field that stores a price, $XXX.YY)
Float: You're storing numbers with a variable amount of fractional digits. (e.g. a field that stores latitude/longitude coordinates, XX.XXXXXXX..., YY.YYYYY...)

Also of note is the underlying data structures of integer/decimal/float that gets stored in the database. See Fixed point vs. Floating point for some discussion on the differences.


How to add default text that clears on focus with jQuery to a search form text field in Drupal I would like to have a default text in an Exposed Views Search form that says something like 'type in a keyword to search' which will disappear if the user clicks on the text field and reappear if the user removes the cursor and didn't type anything. I would like the title of the field which is added through Views to become the text in the text field box. Should I use pure jQuery to add the text to the box? Or should I use hook_form_FORM_ID_alter() to add the jQuery and change the location of the title?

You can do this by implementing hook_form_alter() in a custom module.

function custom_form_alter(&$form, &$form_state, $form_id) {
    if ($form['#id'] == 'search-block-form') {
        $search_text = 'Your search text here';
        $form['search_block_form']['#default_value'] = $search_text;
        $form['search_block_form']['#attributes'] = array(
        'onfocus' => "if (this.value == '$search_text') {this.value = '';}",
        'onblur' => "if (this.value == '') {this.value = '$search_text';}");
    }
}


Passing contexual filters I am creating a view in drupal 7  here is attached screenshot

Here

And preview of this Screen Shot is  or output of this view is

Which is working fine .

Now when i try to pass contextual filter see

Named Edmonton it shows following result

And Result is not correct

It must show only filter with edmonton name

Any Body has idea what is the problem?
Thanks in Advance.

I think the implementation has some issues. The first contextual filter that you have added is date, right and when you are passing an argument, it's not a date. Is that a username? If so then you need to use proper contextual filer. You have a filter as "Add Property View" and also the same in Contextual Filer.


Can't pass variable from theme hook or controller to custom template On Drupal 8, I want pass a variable to a overrides template from my controller OR from the hook theme.
I do several tries :

from my .module file :

function ms_story_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['page__ms_story__global'] = array(
    'variables' => [
      'toto' => "toto", //try one
    ],
    'base hook' => 'page',
    'render element' => 'elements',
    '#tata' => 'tata', //try two
  );
  return $theme;
}

from my .php controller file :

class customController extends ControllerBase {
  public function map_global($name) {
    return [
      '#type' => 'markup',
      '#theme' => 'page__ms_story__global',
      '#markup' => $this->t("Implement method: hello with parameter(s): $name"),
      '#tutu' => "tutu", //try three
      'variables' => [
        "tyty" => "tyty", //try four
      ],
    ];
  }
}

But when I want display all available variable from my overrided template file (via {{ kint() }} ), I don't see anywhere variables I want add. Variables 'toto' 'tata' tutu' and 'tyty' aren't present in the array structure displayed via kint (I cleared all cache of course)

Where is my mystake ?

Bonus question : how can I add a variable who use not any cache ? (the variable is calculated again every time the user load page ?

You cannot use #markup and #theme in the same element. #markup will always take precedence, and #theme is ignored. If you want to output some markup, you need to include that as part of your theme. If the markup is dynamic, then include it as a variable to be passed to your theme (though you need to name the variable as something other than markup).

You've also defined the variable as toto in your hook_theme() implementation, then passed the value in #tutu in your render array. You need to use '#toto' => 'some value'.


Drupal Events Calendar I can't show the main calendar as a page. What am I doing wrong?

I try to add to panel, but the finish button stops working in order to add it. Any idea?

I've added a snapshot:

Seems like my copy of Drupal was having some problems after update.


What are the major differences between solr modules I am looking into Solr search for my site and am seeing two equally well-used modules.

Apache Solr Search (lots of contrib around this)
Search API Solr Search, built on Search API

Why would I pick one over the other?

I would recommend using Search Api Solr. Search Api Solr is a little bit more complex; however, it is more powerful.  In addition there are many sub-modules that allow you to extended the search funcionality.

You should consider reading the article Battleplan for Search & Solr in Drupal 8.

According to this post.

  The two maintainers of Search API and Apache Solr have meet in person and have determined a way forward for advanced searches with Drupal and they both have agreed that Search API is it.


Entity reference field definition to auto create entities I have a field definition set up like below. I want Drupal to do all the heavy lifting for me, so my definitions are minimal and rely on Drupal defaults:

    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSettings([
            'target_type' => 'target_entity',
            'handler' => 'default',
            'handler_settings' => [
                'auto_create' => true,
            ],
        ])
        ->setDisplayOptions('form', array(
            'weight' => $weight,
        ));
    ;

target_entity is just a simple bundleless entity.

This creates an entity reference auto-complete field in forms, but if I type something that doesn't match any existing entities, Drupal will say that no matching entities found and will refuse to create a new one.

How do I make the auto_create setting work?

The answer is 'you cannot auto-create bundle-less entities in Drupal 8.2.0. I don't know if this is a bug or a feature, but you have to have a bundle for target entity ('all_target_entities' in my example) and indicate that as target bundle in the settings:

$fields[$field] = BaseFieldDefinition::create('entity_reference')
    ->setSettings([
        'target_type' => 'target_entity',
        'handler' => 'default',
        'handler_settings' => [
            'auto_create' => true,
            'target_bundles' => [
                'all_target_entities' => 'all_target_entities',
            ],
        ],
    ])
    ->setDisplayOptions('form', array(
        'weight' => $weight,
    ));
;

I think it was not the case up to some point, so stating the exact version I am having this issue with.


How to add a heading at the top of node/add or node/edit? In my node/custom_content/edit and/or node/add/custom_content page I want to place a heading at the top of the page as "Create New My-Content".

Seems simple enough, but I am unable to do so. How can this be achieved?

If you mean to change the title of the page you can do this. This will make all node add form titles "Create new [content type]" instead of "Create [content type]".
It doesn't change the edit form because it doesn't make sense to put "new" in the title there because it is not new content, you are editing existing content.

Create a new custom module that implement this:

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MODULE_NAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // For the node add form.
  if (!$form['nid']['#value']) {
    // Add "new" to the page title.
    $node_types = node_type_get_names();
    drupal_set_title(t('Create new @type', array('@type' => $node_types[$form['#node']->type])));
  }
}


db_query and db_select I have static query (db_query works great) but for some reason, I have to put a condition to the query result

I don't want to re-write the same db_query with "where", I'm looking for a way to write just the condition part and avoid to re-write all the query.

So I want to add a condition (that is for dynamic query) to a static query

Is there any solution ?

Here is one example on my code :

$resultat = db_query(
    "SELECT `field_titre_en_arabe_value`, `field_etat_du_livre_value`, e.denomination_ed, entity_id, `field_prix_value`, `name`
    FROM (
        SELECT `nid`, ta.entity_id,  n.created, `field_titre_en_arabe_value`, `field_etat_du_livre_value`,`field_prix_value`,`name`, n.uid, edi.field_edit_target_id, COALESCE (edi.field_edit_target_id, n.uid) as newid
        FROM {node} as n
            left join {field_data_field_etat_du_livre} as et on n.nid = et.entity_id
            left join {field_data_field_titre_en_arabe} as ta on n.nid = ta.entity_id
            left join {field_data_field_edit} as edi on n.nid = edi.entity_id
            left join {field_data_field_prix} as pr on n.nid = pr.entity_id
            left join {field_data_field_categorie} as cat on n.nid = cat.entity_id
            left join {taxonomy_term_data} as tax on cat.field_categorie_tid = tax.tid
        ) as tabb
        left join {editeur} as e on e.uid = tabb.newid
        order by  field_etat_du_livre_value asc, created desc"
);

Now here is the condition I was talking about, and look at the 'where' part, it came after I re-write the same first query, I want to write only the "where" part after the if

if (isset($form_state['storage']['etat_livre'])){
    $resultat = db_query(
        "SELECT `field_titre_en_arabe_value`, `field_etat_du_livre_value`, e.denomination_ed, entity_id, `field_prix_value`, `name`
        FROM (SELECT `nid`, ta.entity_id,  n.created, `field_titre_en_arabe_value`, `field_etat_du_livre_value`,`field_prix_value`,`name`, n.uid, edi.field_edit_target_id, COALESCE (edi.field_edit_target_id, n.uid) as newid
            FROM {node} as n
                left join {field_data_field_etat_du_livre} as et on n.nid = et.entity_id
                left join {field_data_field_titre_en_arabe} as ta on n.nid = ta.entity_id
                left join {field_data_field_edit} as edi on n.nid = edi.entity_id
                left join {field_data_field_prix} as pr on n.nid = pr.entity_id
                left join {field_data_field_categorie} as cat on n.nid = cat.entity_id
                left join {taxonomy_term_data} as tax on cat.field_categorie_tid = tax.tid
        ) as tabb
        left join {editeur} as e on e.uid = tabb.newid
        where field_etat_du_livre_value = :field_etat_du_livre_value
        order by field_etat_du_livre_value asc, created desc", array(
            ':field_etat_du_livre_value' => $form_state['values']['etat_livre']
        )
    );

As it is now, it works, but i think the code is redundant is there any way to avoid that please ?

Since you are querying some tables to get the value of an entity field, I would rather use the EntityFieldQuery class.

To answer your question, what you want to achieve can be obtained by concatenating strings to the the query string.

$query = "The first part of the query";
$args = array();

if (isset($form_state['storage']['etat_livre'])) {
  $query .= "WHERE field_etat_du_livre_value = :field_etat_du_livre_value";
  $args[':field_etat_du_livre_value'] = $form_state['storage']['etat_livre'];
}

$query .= "ORDER BY field_etat_du_livre_value ASC, created DESC";

$result = db_query($query, $args);

As side note:

The query should not use back-ticks
The reserved words should be written in upper case


Is hook_boot() removed from drupal 8? Is hook_boot() hook removed from drupal 8?

If yes then what is alternative method which can be used instead?

You can see here

  In Drupal 8 hook_boot() was removed since the same results can be
  achieved with other ways, for example:

  A module that needs to interrupt the request very early based on certain conditions can use an event listener (see #1794754: Convert
  ban_boot() to an event listener) (Note that modules are loaded by this
  stage unlike in Drupal 7.)
  A module that needs to run on cached pages should prompt its users to add code in settings.php


Custom CSS and JavaScript How to add custom css and javascript file in Drupal 8.

there are several ways to add js/css, one example:

Attaching custom javascript or css in your theme

Add a library to yourtheme.libraries.yml in your theme folder:

  yourlib:
  version: 2.6
  css:
    theme:
      css/your.css: {}
  js:
    js/your.js: {}
  dependencies:
    - core/jquery

The paths given are relative to your theme. Dependencies is optional, you can force loading of additional js like jquery.

Now to add this library to your theme go to yourtheme.info.yml and add it like this:

    libraries:
      - yourtheme/yourlib


Create a custom element in Webform? I am trying to create a custom Webform element that can be added to any webform. It is a select list, but I am providing the options from a remote API call (they cannot be static or hardcoded).
I can get the element to appear in the admin UI with:
use Drupal\webform\Plugin\WebformElement\Select;

/**
 * Provides a 'tour type' element.
 *
 * @WebformElement(
 *   id = "tour_type",
 *   label = @Translation("Tour Type"),
 *   description = @Translation("Provides a form element to list tour types from Funnel."),
 *   category = @Translation("Options elements"),
 * )
 */
class TourType extends Select {

}

I can add it to a form, and give it options like a regular Select in Webform, but nothing renders on the form.
I was trying to follow this here, but don't quite understand what needs to be done: Why do my custom elements not get rendered?
Do I need a WebformElement plugin, or a new Element class? I don't see how the two are correlated.

You need to create a 'Form Element' to process, validate, and render an input and corresponding 'WebformElement' to integrate the input with the Webform module.
You can use the Webform Example Element module as a starting point.


How to copy Location Country field value from Parent object to Child object field default value? I use Parent and Child content types with a Field used in both types.

I would like Drupal to automatically propagate the Field value from Parent value to the Child field default value.

How to do this ?
I am interested specificaly in an example for Location>Country field.

I use node reference or organic groups modules to set up Parent<->Child relationships.

Guess you want this to take place, when you create (aka save to db) a new node. You could do this in hook_node_presave.


Code to output individual fields in a Theme view I know this question seems to have been half answered a few times but I'm finding it difficult to apply a working solution. I have created a new theme from scratch to use for a view I have created. I can get the view content to display in the Theme by using:

  print render($page['content']);

However because of the complexity of my theme layout I need to display the fields in the view individually.

I understand that I need to create a file in the theme folder called something like:
views-view-field--viewname.tpl.php and add some php, then add some code to this but I just can't seem to find the correct code that is needed plus the correct syntax I add to the theme page.tpl.php to show the individual fields. Could anyone please help?
Thanks.

OK,
I sorted this out. I didn't quite understand that I need to make layout changes in the appropriately named views-view-fields--viewname.tpl.php. I was hoping to just add some php to the page.tpl.php theme file I have developed for my views.

It's quite a learning curve with Drupal!


Generate unique barcode for each registered user I'm using D7 and I would like my website to create unique barcode for each user when they register an account, and send the barcode to them through email. This barcode should be part of their profile.

I found that "Barcode" module can generate barcode in a page, but I'm not sure how to use this module to create barcode for user. Is there any way I can modify the codes to do this?

Just some background information:

I need a barcode generated to each user as I want to scan it in mobile as taking attendance when web admin is having an event. After event ends, web admin will export the attendance list in excel or any document style, to check on the attendance detail (name, userid, date, scanned barcode)

Anyway the scanning and retrieving list is mobile app issue. I need to start with generating barcode first.

Any suggestion on this?

Enable the barcode module.
Goto: admin/config/people/accounts/fields
Add a barcode field and configure as you like
Towards the bottom of: admin/config/people/accounts, Modify the email to include the barcode

Another option: Commerce Event Tickets, This sounds a lot like what you need.


How to print taxonomy terms field in node templates? How can I display node taxonomy terms field in node templates of Drupal 8?

We do this in Drupal 7 by add this code to node.tpl.php file:

print render($content['field_tags']);

I tried adding the below code in Drupal 8:

{{ content.field_tags }}

but with this code have problems:

If I add some styles or make some changes to field--node--field-tags.html.twig file these changes displays in all content types also.
If I don't want to show default taxonomy terms in the bottom of article nodes (I want to move and show taxonomy terms in the top of the article) and I assign "Hidden" value in "Administration>Structure>Content types>Article" in "Format" section, this settings cause to not displays all the taxonomy terms fields in throughout of the article nodes at all.
Taxonomy terms Label always display even if no tags added to the node. How can I show taxonomy terms label and their values only when have been added any tags to it?

Yes, this will be used in all nodes with that field ! You could add a contenttype specific node.html.twig (see next point), or if you only want to add classes, do it in template_preprocess_node(&$variables), add classes to $variables['content']['field_tags'][x]['attributes']['class'][] = 'my-style', you can check there for the contenttype.
What are you rendering ? If you render the node's field, you'll only get the assigned terms ?! For custom node-specific theming you could use something like this in

node--type-your_contenttype.html.twig:

   {% for item in content.field_tags %}
      {% if item['#title'] %}
        {{ item['#title']  }}
      {% endif %}
    {% endfor %}

Also {{ item['#options'].entity.url() }} or {{ path('entity.taxonomy_term.canonical', {'taxonomy_term': item['#options'].entity.tid}) }} could be used to retrieve the URL.

Regarding your icons

Use tid or parent and name it like icon-34. Access it in twig like: item['#options'].entity.parent or item['#options'].entity.tid.

  But I would recommend the use of a preprocess function to add a
  key-value pair to each item array where you set the name. For example
  from a field you added to your taxonomy. You could then access it in twig like {{ item.key }}


Enable/Disable field values based on another field's value I am using Drupal 7 with the Entityform and Conditional Fields modules to build a form and need to see if it is possible to disable a value in one field based on the selected value of another field. Here are the details:

Field: Source Region
List (Text) - Radio Buttons

Values:
US-East
US-West
APJ
EMEA

Field: Destination Region
List (Text) - Radio Buttons

Values:
US-East
US-West
APJ
EMEA

The behavior I am looking for is this:
When a region value in Source Region is selected, I need the corresponding value in Destination Region to be disabled but the rest of the values to be selectable. This is to make sure the Source and Destination regions are not set to the same value.

Example: Source Region selected value is US-East, I need Destination Region US-East gets disabled.

If this is not possible with the Entityform and Conditional Fields modules, please let me know how best to obtain this functionality. If this means writing a form from scratch, I am willing to do this but need some type of tutorial or howto document to learn how to do this.

I doubt whether it is possible. You cannot hide certain radio options in a radio group. It is the whole group or nothing. I will look rather at a custom jQuery solution coupled with a server-side validation method.

The jQuery will have to:
display all hidden radio options in destination, then hide the corresponding radio option in the destination when source is selected. You will have to add the jQuery to the page via  hook_preprocess_html or something similar, or use the module JavaScript Libraries Manager.

Server-Side:
You can use the Field validation module. Put the validation against both fields, and use 'Equal values on multiple fields', and set it to reverse.


Drupal How to use regex or specific keywords as menu arguements I have a drupal website, in which I wanted to add a new URL. This menu have two arguements which should be passed from the client side.

function campaign_management_menu() {
  $items = array();
  $items['campaign-management/test/%/%'] = array(
    'title' => 'Campaign Management',
    'description' => 'A section where you can manage your campaigns',
    'page callback' => 'cm_home',
    'page arguments' => array(3, 4),
    'access callback' => TRUE,
  );
  return $items
}

Here, for the fourth argument, there should be only two options {add/edit}. Is there any option in drupal to set these two keywords explicitely. ie,

$items['campaign-management/test/%/{add|edit}'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

There isn't such an option; you just define two route items.

$items['campaign-management/test/%/add'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

$items['campaign-management/test/%/edit'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

Alternatively, you define your route as follows.

$items['campaign-management/test/%/%'] = array(
  'title' => 'Campaign Management',
  'description' => 'A section where you can manage your campaigns',
  'page callback' => 'cm_home',
  'page arguments' => array(3, 4),
  'access callback' => TRUE,
);

Your page callback then will do something when the last argument it get is 'add' or 'edit'; eventually, it can return a 404 error when the argument doesn't have one of the desired values.

Keep in mind that in Drupal 7, a user visiting (for example) node/1/sgsdrgdfgdfe45t63635wsg will normally see the node page (node/1, in this case). To keep that behavior, you should define the campaign-management/test/%/add and campaign-management/test/%/edit routes.


Disable user creation at login with Simple LDAP I have the simple LDAP module installed and running, and I would like to prevent Drupal from creating a new user after a user authenticates if it does not already exist in Drupal.

I found the function 'simple_ldap_user_load_or_create_by_name',
if (!$Drupal_user) ...

I cannot find a hook to modify this function, no way to do it without changing the module?

As you are describing it, this is not possible. You can limit authentication and user creation to only LDAP accounts, but you must have a local Drupal user.


How to prevent showing background code in Drupal 7 admin? I am seeing the following screen when i am saving or updating a node in drupal 7 admin.

I am using Drupal 7 with Seven theme.I am seeing the following texts in white screen.To get the actual i need to click back button.

  [ {"command":"settings", "settings":{"basePath":"\u002F",
  "pathPrefix":"", "ajaxPageState":{"theme":"nbiz_train",
  "theme_token":"BVOiHIMf2BoQgMAltQtiv_GRDGBYoFOGNn3hJ8eJRxw"},
  "colorbox":{"opacity":"0.85", "current":"{current} of {total}",
  "previous":"« Prev", "next":"Next »", "close":"Close",
  "maxWidth":"98%", "maxHeight":"98%", "fixed":true,
  "mobiledetect":true, "mobiledevicewidth":"480px"}}, "merge":true} ]

How can i remove this error?

Sounds like it may be related to (caused by) JQuery Update, similar to what is described in "Cannot edit my views.. I get a JSON string?".

Maybe you want to (temporary) try any of these potential work arounds:

Disable or change the settings within JQuery Update (to see if it solves the issue).
Change the admin theme to any theme included in the Drupal version you downloaded.


building a complex frontpage I've built all my site apart from the frontpage which right now shows:

No front page content has been created yet.

The frontpage will be the most complex page of all, containing a lot of boxes (blocks) which will be presenting lists of items.

I've got 2 solutions for this problem and I'd like to know which one is best.

solution 1 - blocks

create the ~10 blocks that the frontpage needs
make them translatable
use description prefix "front -" for easier identification in admin/structure/block
configure "Only the listed pages": <front>
somehow remove the "No front page content has been created yet" message

This solution seems very tunable. The CM will be able to do whatever he wants with the individual view blocks of the frontpage.
On the other hand there will be too many blocks in the administration page (but only 1 for all languages).

solution 2 - node

create a node
the node should be of a type which has fields for configuring the fetching and displaying of items. e.g fields:

int: number of news to fetch
int: number of events to fetch
bool: should display teaser
html: teaser content
etc

in admin/config/system/site-information set that node as Default frontpage

The drawback of this is that I should implement the fetching and display, and if the CM wants to change something that the content type does not support I'll need to implement it.
On the other hand I'll have full flexibility in HTML if I provide a separate template just for this content type.

So, is there a definite winner between those 2? Also note that, for various reasons, I don't want to use panels.

I know you said you didn't want to use it, but this is a PERFECT use case for Panels.  I'm not a huge Panels user and will generally steer clear of it if I can, but sometimes you have to step outside of your comfort zone and just use the best tool for the job.

There's a video here that focuses on using Views and Panels for a home page layout.

  In this Drupal video tutorial we take a brief look at panels. I show
  you how to recreate a home page that relies on views content panes. As
  a result, we create a two column home page panel which pulls in recent
  content from across all content types and shows which users are
  online.

But if you are REALLY set in your ways, then go with the blocks.  You can always put the blocks into Panels at a later date.


How and where do I programmatically add a menu to the Navigation menu? I want to add menu items to the Navigation menu dynamically, depending on certain states (example: user is logged in, etc). I assume I do this in theme_preprocess, but I can't seem to find the var to tweak.

Am I looking in the wrong place? Where is the best place to do this, and what is the best method?

I'd suggest checking out hook_menu(). For example, the following implementation of hook_menu() placed in either a module or template.php should insert a menu item into the navigation menu for anonymous users. Take a look at the User module for some good examples of how to implement hook_menu() for different user roles.

function MODULE_menu() {
   $items = array();
   $items['the/menu/path'] = array(
   'access callback' => 'user_is_anonymous',  //or 'user_is_logged_in' to check if logged in
   'type' => MENU_NORMAL_ITEM,
   'menu_name' => 'navigation',
   'title' => t('Title of Menu Item'),
  );
  return $items;
}


What are the significant differences between the Sharethis, Addthis, and Service Links modules? AddThis
Service Links
ShareThis

These three modules appear to be very similar in terms of functionality.  AddThis has about double the number of the installs compared to the other two, but Service Links and ShareThis each have over 10,000 installs, which is not too shabby.

What, if any, are the significant differences among these modules?

There is some detailed information on each of these, and others, over at Comparison of Social Network connectors/Sharing modules.  It would be best to add any new information to that wiki page so that we have something that's always up-to-date.


FAPI #prefix YAML filter tag button_submit:
   '#prefix': '
text<button>button text</button>'
   '#suffix': '
'
   '#value': Send
   '#type': submit

I have the code above in YAML form. When I edit the code, I see the button tag; when rendering, only the following markup is left.

ALGOasd
<input id="edit-button-submit" class="button js-form-submit form-submit" type="submit" value="Send" name="op" data-drupal-selector="edit-button-submit">

It´s clear that I have some filter, but I can't find it out. I also tried putting a <button> in a container item, but the same thing happens.

Why does this happen? How can I fix it?

You need to include the #allowed_tags property which is applied to #markup, #prefix, and #suffix. (See: Pass raw html to #markup)

button_submit:
  '#prefix': '
text<button>button text</button>'
  '#suffix': '
'
  '#value': Send
  '#type': submit
  '#allowed_tags':
    - div
    - button


How do I insert a block into a node? I can't insert a block into an article on Drupal 8.

I installed the module, created a custom block, created an article using the Full HTML input format, inserted [block:block=1] into the article body, and saved it.
Nothing happened. [block:block=1] appears in the text instead of the desired block. I tried to find something in admin/config/content/formats/manage/full_html to make Drupal recognize the inserted blocks, but I found nothing.

Am I doing something wrong?

The insert block module implements an "input filter" via the core Filter module. A text format is a collection of enabled input filters. So when enabling a module that provides an input filter, the next step would be to configure the text format to use the input filter.

The Full HTML text format does not have that input filter enabled by default.

In addition the module has a Drupal 8 development release, but the code underneath still seems to use PSR-0 for its class loading and has not been updated in 3 years. It may be broken for other reasons as well.


My breadcrumbs are skipping a level I've got a Main Menu and am using Superfish, not sure if this makes any difference.

But in the breadcrumbs the top level of the main menu is being skipped. Eg.

Instead of

Home - A - B

My breadcrumb looks like:

Home - B

B, being the page I am currently on.

What am I doing wrong?

Drupal core breadcrumbs can be flaky at times.

You may be interested in

Menu Position ( contrib module )
Custom Breadcrumbs ( contrib module )
hook_preprocess_breadcrumb ( theme preprocess function, set $variables['breadcrumb'] )
theme_breadcrumb ( theme function )

Using one or more of those methods, you can control breadcrumb behaviour.


Admin Module frontpage has gone - How do I get it back? I took the liberty to upgrade to v7.25 today; four hours later (after trying to get back to where I was 8 hours before) I had to used Backup and Migrate to restore my previous v7.24. I've tried numerous update.php attempts but my Admin Module page just will not show via /admin/modules path. I can get admin/uninstall but any attempt to get back to /admin/modules gives me a black white screen so I cannot manage any modules.

Can anyone suggest a solution. I'm aware of Drush and have it to hand, but not too aufait at present (I'm on an Ubuntu desktop with localhost).

I do get a PDO error starting as:
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'has_children' in 'field list':......

if that has any influence.

Thanks.

Try using phpMyAdmin. Backup again, then show the system table. Change the status of the problem module from 1 to  0 from phpMyAdmin. Then refresh Drupal pages to see if it resolves it. Other modules might be the issue so try process of eleimaination, toggling 1 to 0. If the 0 works, try and uninstall then reinstall if practical.


How to embed images in MIME mail system? How to progamatically embed images in mail?
I am using mime and mail system module

Here is my code:

function send_rush_me_mail($node){
  $dataArr = array();
  $dataArr['field_name'] = $node->field_name['und'][0]['value'];
  $dataArr['field_email'] = $node->field_email['und'][0]['value'];
  $body = location_beacon_email_body_string('rush_me', $dataArr);
  $params = array(
    'body' => $body,
    'subject' => 'Auto Response for Ask Me',
  );

  drupal_mail('register', 'register', $dataArr['field_email'], language_default(), $params, 'example@domain.com', TRUE);
  watchdog('Ask me mail', print_r($params,1));
}

With the help of Rules module and filtered HTML text format allowing img tag in the format you could send HTML emails with images.

Here is a summary of the required steps:

Enable the required modules, eg using Drush like so: drush dl rules entity mimemail mailsystem
Configure the MAIL SYSTEM SETTINGS choosing MimeMailSystem the Site-wide default and Mime Mail module class from admin/config/system/mailsystem
Set the text format to be filtered html or the format that allows img tag from admin/config/system/mimemail
Use Rules to send html e-mails.

For a more detailed tutorial, refer to How to Send HTML Emails in Drupal 7 using Rules.


How to set target="_blank" for links in CKEditor I use CKEditor in Drupal 8.
I want that every link will open in a new tab of browser. I want that the code look like this

    my link

But if I use the link Button in editor I do not have choice for target blank. I only can fill in the url of link and the code looks like this

    my link

Any idea what I have to do for changing this?

D8 Editor Advanced link module

  Enhances the link Dialog in D8 CKEditor. Allows to define the
  following attributes:

  title
  class
  id target
  rel