Does node_load() function prevent multiple loading of the same node? In some cases, for example page where a lot of block are loading the same current node in one request it could be useful to load node just once for every block. Once I read somewhere this is default functionality for node_load() function.

Is it really true, or do I have to workaround that by myslef (store node as global variable or something like that)? Documentation says nothing about that.

Yes, node data is statically cached per request, if the requests are for un-revisioned nodes. No, you don't need to do the caching yourself.

The cache read/write happens in NodeController::load() if you're interested in what's going on behind the scenes.


theme_links() override has no effect So I want menus to output in a custom way. I would not output the following HTML.

       foo

       bar

I would replace it with the following one.

   foo
   bar

So I put in the template.php file the following function (my theme is called mFAC).

function mFAC_links($variables) {
    // custom stuff
}

I am starting with a light alteration, but nothing seems to have any effect. I cleared the cache.

Is there anything I am missing?

You can override the menu wrapper in this manner:

function YOURTHEME_menu_tree__MENU_NAME($variables) {
  return '<nav class="menu'.$variables['delta'].'">' . $variables['tree'] . '</nav>';
}


Add condition to specific content type in apache solr I've installed apachesolr,search api solr and views. I have only indexed article and basic page content type.

Then i've added new field "internal use only" as checkbox for article content type. I want to add filter "internal use only" only in article content type. I want to show except those articles.

How to alter apache query?

Check apachesolr.api >> hook_apachesolr_query_alter

function hook_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

More details about solr query DrupalSolrQueryInterface


How to override registration form message I should override registration form message "Registration successful. You are now logged in." with String Overrides module it does not work, because new text is long and every line with other style, it is in Drupal 7
I try to do it in template.php , but no my code is working.
Can anyone help me?

You can check this message in hook_init it's working for me please try this code.

function custom_init() {
 if (!empty($_SESSION['messages']['status'])) {
  $message_text_to_remove = "Registration successful. You are now logged in.";
  $key = array_search($message_text_to_remove, $_SESSION['messages']['status']);
   if ($key !== FALSE) {
      $_SESSION['messages']['status'][$key] = t('Greta Now your message changed');
    }
  }
 }

Thankyou


View to display nodes with lat long in proximity of specific lat long I have a content type and it has a geolocation field which stores a lat long . If I create one node with some lat / long info, I need to  look up / show a view of other nodes that have lat long information which is in the proximity of the former's lat long info. Any idea how to do this?

Geolocation Proximity seems to be exactly a solution for you. You will need to keep location data using Geolocation Field to benefit from it.

Current features are:

  Views filter that can be used to filter entities (nodes, users, etc.) based on distance from a certain point (defined as lat/lng point). The input widget is very basic at the moment. Patches welcome...
  Views field to display the calculated distance between the entity and a reference point (can be synced with filters' lat/lng values).
  User-friendly input widget for exposed filters using Google's reverse geocoder

Big lacking features are:

HTML 5 Geolocation input
proximity SQL look ups

It's competitor is Get Locations module. It's a suite that uses Google Maps API. One of it's functions is:

  Getlocations Search which uses Google Geocoding on entered search terms and shows nearby locations. The search form is fully configurable with options for setting the Search distance, Distance units, Number of locations to show and Restrict the search to a content type.

Emphasis mine.

Last but not least, you can use Computed Field. It can be calculated on access, so it is perfectly possible to make PHP computed field displaying "distance from X" where X is defined on the fly. You will need to write computation in PHP, but you will not be tied to any particular metric.


Adding attributes to field_view_value I'm using the following function to render a image field in a template, this works great but I would also like to add a custom alt attribute to the image:

function <module>_render_field($node, $field_name, $delta = 0, $display = array()) {
   $field = field_get_items('node', $node, $field_name);
   $field = field_view_value('node', $node, $field_name, $field[$delta], $display);
   return render($field);
}

<module>_render_field($node, 'field_image', 0, array(
  'type' => 'image',
  'settings' => array(
     'image_style' => 'object_380x250',
     'image_link' => 'content',
   ),
));

I was trying to add the alt attribute to the image by changing the above code to:

<module>_render_field($node, 'field_image', 0, array(
  'type' => 'image',
  'settings' => array(
     'image_style' => 'object_380x250',
     'image_link' => 'content',
   ),
      'attributes' => array(
         'alt' => 'alternate'
      )
));

The above didn't worked but I managed to add the attribute by changing the module code to:

function <module>_render_field($node, $field_name, $delta = 0, $display = array()) {
   $field = field_get_items('node', $node, $field_name);
   $field = field_view_value('node', $node, $field_name, $field[$delta], $display);
   // add alt attribute
   $field['#item']['alt'] = 'alternate';
   return render($field);
}

I'm hoping there is a nicer way to achive this.

If you look at it, you'll notice MODULE_render_field is not useful at all. Once you get the renderable array from field_view_value you can change the values in it and render it. If you're adding that to a template, it will look fugly, for sure. But it belongs in a preprocess call, where it will look just normal:

<?php

function MYTHEME_preprocess_SOME_TEMPLATE($vars) {
  $field_items = field_get_items('node', $vars['node'], $vars['field']['field_name']);
  $field_value = field_view_value('node', $vars['node'], $vars['field']['field_name'], $vars['field'][$delta], $display);
  // Alter the renderable array.
  $field_value['#item']['alt'] = 'alternate';
  $vars['altered_field'] = $field_value;
}

And in the template:

<div class="something">
 <?php print render($altered_field); ?>
</div>


Migrate a CSV into two entities with reference I have a CSV as below:

chapter, headings, sentences
1, heading one, "1,2,3,4,5,6,7"
2, heading two, "1,2,3,4,5"
2, heading three, "6,7,8"

I want to migrate it to Drupal. The heading columns have to be migrated to the taxonomy heading. Once a heading is added, it should loop through the value in sentences and update the sentence entity by adding a reference to it.

The entity to be updated should be loaded matching the sentence column and chapter column. The sentences entity is already pre-populated with data.

Fields in each entity:

Taxonomy:
heading(string)

Entity(sentences):
sentence_no(int)
heading_reference(entity_reference)
sentence(string)
chapter_no(entity_reference)

I tried this tutorial. While the link is straight forward it doesn't really help my need.

I am ok if I migrate to D7 or D8. However D8 is preferred.

It's fundamental to how the migration process works that it processes one item being written at a time. In this case, since it's sentence entities that are being updated, it needs a migration that processes one sentence at a time. The layout of your CSV here is not well-suited for that, and to work directly from that CSV would require significant hackery. The best approach would be to either generate your CSV in this format in the first place, or have a preprocessing step to put the data in this form:

chapter,sentence,headings
1,1,heading one
1,2,heading one
1,3,heading one
1,4,heading one
1,5,heading one
1,6,heading one
1,7,heading one
2,1,heading two
2,2,heading two
2,3,heading two
2,4,heading two
2,5,heading two
2,6,heading three
2,7,heading three
2,8,heading three

Then, you'd have a migration with source IDs chapter and sentence, setting the heading for each sentence from the headings column.


How do I get posts of a content type on node writing I have three content types: endorse, deals, and recommends. Recommends has three nodes.

How do I show those three nodes from the recommend content type on the deals content type using a field on the deals content type writing panel?

You can use the References Module, that can be used as a node reference of any other content type. After installing the module, go to deals content type manage fields, select the node reference to field to recommends content type and while configuring field make it as unlimited, and now go to deals content type writing panel, here you can see the multiple field and can access the node id or name of the references content type nodes.
You can list the selected nodes of references under deals node in views using relationship.


How do I programmatically delete a node by internal url alias? How do I programmatically delete a node with a specific internal url alias?

Background:
We are trying to delete this node so that it can be replaced during an update hook.

After some digging around through the available services and core classes, I have determined you need to get the nid through the path.alias_manager.  Additionally you need to wrap everything in a couple of conditions or you will throw errors if the path does not exist.  (eg. if you are trying to roll this change out to a fleet of sites that might or might not have this path already)

Below is my example code:

  // Check the path is valid before proceeding.
  $pathIsValid = \Drupal::pathValidator()->isValid('/blog');

  if ($pathIsValid) {
      $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/blog');
      $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
      // Get nid.
      $nid = $params[$entity_type];
      $node = Node::load($nid);

      // Check if node exists with the given nid.
      if ($node) {
      $node->delete();
    }


Adding pager to queried content in a custom module Drupal 8 I've created a custom module to get X items using entityQuery, and then display them as a list. I need to limit these and add a pager to click through to the next page, but I cannot find how best to do this. Examples I've found either use external search sources, or are depreciated functions of older versions of Drupal.

I've added the pager option in the query, initialized the pager, and added the #type = pager to the content block, but it's not showing up. I know I am missing something but I cant figure out what it is.

class MyPageController extends ControllerBase {

public function myPage1() {

    $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'page')
    ->range(0, 10)
    ->pager(3)
    ->sort('created', 'DESC');

    $nids = $query->execute();
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

    pager_default_initialize($query->total, '7');

    $list = array();

    foreach ($nodes AS $node){
        $list[] = $node->get('title')->value;
    }

    $content = [
        '#theme' => 'item_list',
        '#list_type' => 'ul',
        '#title' => 'Page list',
        '#items' => $list,
        '#attributes' => ['class' => 'my_page1_list'],
        '#wrapper_attributes' => ['class' => 'container'],
        '#type' => ['pager'],
    ];

    return $content;
}
}

The format of the render array is wrong, you have to place the pager in its own render element (see this question, which was almost at the same time Pager with EntityQuery) or if you want to have it in the theme in a variable, but then a name other than #type.


Views exposed filter with selected tags/terms I am importing RSS content with Feeds Module that is tagged with the Atom standard category-tag. I would like to give the user the opportunity to filter the content in a view, but only by some selected tags (as the tags imported are too many and I am not able to assign them to different vocabularies). I tried to achieve it with grouping, but only received empty results. Is it possible to offer filters that only offer some selected tags?

I found the answer by myself: Sometimes it is so easy and obvious and you too are blind to see it:

Choose selection type dropdown
select terms
check "Limit list to selected"


How do I call some function after an AHAH callback that adds a new item? I've tried

'#ahah'   => array(
        "url": "/?q=content/js_add_more/pmemo/field_tracks_disks_chapter",
    "event": "mousedown",
    "keypress": true,
    "wrapper": "field-tracks-disks-chapter-items",
    "selector": "#edit-field-tracks-disks-chapter-field-tracks-disks-chapter-add-more",
    "effect": "fade",
    "method": "replace",
    "progress": { "type": "throbber" },
    "button": { "field_tracks_disks_chapter_add_more": "Add another item" } ,
        'after' : 'myJsFunction'
),

But it is not working.

I wasn't able to find any solutions to this problem.

Thanks for any help.

You could handle ajaxComplete jquery event, which is called right after completion of ajax/ahah requests.


What can Menus do that Taxonomy cannot? 'Comments', 'Users', 'Taxonomy' are Entity Types because they each define their own sets of required fields.

I am having a discussion with my boss where I am arguing that 'Menu' are really just a type of 'Taxonomy'. This is because Taxonomy has a parent field, and a title, but Menu also shares this, and extends it to require a 'link' field. He, however, disagrees with me and says that there are things which Menus can do that Taxonomy cannot. But I don't see what.

'Menu' has the concept of hierarchy, so does 'Taxonomy'.
'Menu' has a 'link' field to link to a Node, or an external link. But this can also be done using 'Taxonomy', by manually adding in a 'link' field manually.
You can control permissions on 'Menu' items, you can also do this with Taxonomy

I understand that a 'Menu' serves a special and common need, but conceptually I think it's just a type / superset of taxonomy, not another Entity. I think this chain of thought is common, as reflected by the number of sites that uses the Taxonomy Menu module.

In a previous question, I grok that Comments and Nodes are different Entities because they have completely different fields. But here, Menu seems to have the same fields as Taxonomy - namely parent and title.

So, why has the Drupal community decided that Menu need to be its own Entity Type, instead of a being just a module that extends taxonomy? (i.e. Taxonomy Menu) What does Menu offer that you cannot achieve in Taxonomy?

Basic difference I run into some time ago: a menu can link to only one content where taxonomy term can refer to several nodes. So, if you need a relationship node -> term that allows one node to be marked with many terms (and, in consequence, have one term assigned to many nodes) then menus won't do that for you (at least not out of the box). Node -> menu relationship is more 1-to-1 where node -> term is 1-to-many.


How do I add icons to taxonomy terms? I have a sample site running Drupal 8.1.x, I want to add icons to the taxonomy term.

Example.

I have a term called Animals with the following list in it

Cats
Dogs
Fish

i want to assign an icon for each terms, a picture of a cat for Cats and so on and will be using it as exposed filter. So i want the pictures/icons instead of the the words Cats - Dogs - Fish.

I have looked into template_preprocess_field(&$variables, $hook). I dont know how to go about it, also tried assigning an image filed for each term but the pictures are not showing up on the exposed filter menu.

Please help.

You can add image field in taxonomy.You can find option like this.

Then add image field instant of title.


Views - How to suppress ajax errors without leaving a log entry in browser I have a views page that is continually updated using views_autorefresh.  My setup works fine except for the occasional error message:

AJAX Request terminated abnormally

This only happens if the user tries to navigate away from the page during an update.  Is there a way to suppress this message?  Because I know that this message will happen (repeatedly) I do not want for there to be a log entry of it.

This problem is solved by the Prevent JS Alerts module


"drush sql-sync" failing with Illegal string offset 'site' backend.inc:1030 I'm using Drupal 8.
I have an installation on my local dev machine as well as one on my remote demo machine.
I'm attempting to use drush sql-sync so that I can make sure my local dev has the same data as my remote demo.

The command I'm running is:

drush sql-sync @remote.demo @local

The error is:

  Illegal string offset 'site' backend.inc:1030

  The command could not be executed successfully (returned: env: drush: No such file or directory, code: 127)
  Error: no database record could be found for source @remote.demo

My aliases file is ~/.drush/aliases.drushrc.php.

<?php

$local = '/var/www/drupal/';
$aliases['local'] = [
    'root' => $local,
    'path-aliases' => [
        '%dump-dir' => "{$local}drush.dbdumps",
    ]
];

$remote = '/var/www/drupal/';
$aliases['remote'] = [
    'remote-host' => 'x.x.x.x',
    'remote-user' => 'myUsername'
];

$aliases['remote.demo'] = [
    'parent' => '@remote',
    'root' => $remote,
    'path-aliases' => [
        '%dump-dir' => "{$remote}drush.dbdumps"
    ]
];

?>

I know it's being picked up because it shows up in drush status.

This is a snippet of backend.inc (the file referred to in the error):

1028        if ($proc['output']) {
1029            $values = drush_backend_parse_output($proc['output'], $proc['backend-options'], $proc['outputted']);
1030            $values['site'] = $site;
1031            if (is_array($values)) {

It seems to me that drush_backend_parse_output() is parsing something incorrectly but I'm unable to figure this one out. Any idea what I'm doing wrong?

UPDATE
I ran the drush command with the verbose flag:

drush -v sql-sync @remote.demo @local

The output is long but the relevant output is:

ssh -o PasswordAuthentication=no myUsername@x.x.x.x 'env COLUMNS=112 drush --backend=2 --verbose --root=/var/www/drupal/  sql-conf   --all 2>&1' 2>&1                       [notice]
Illegal string offset 'site' backend.inc:1030

It seems like the drush command run on the remote machine is generating output that my local drupal is tripping on. Not sure how to resolve this though.

Note: drush --version gives me Drush Version : 8.0-dev on both machines.

I had same issue and fixed it by specifying the %drush-script path for my remote machine alias. Just ssh into your remote machine and run "drush status" to find the correct "Drush script" path and put it in under path-aliases array. So it would look like this:

'path-aliases' => array(
  '%drush-script' => '/{your_path}/drush.php',
)


How to add css class attributes to the anchor element inside the links of a given menu by theme function Do I miss something or is it impossible to theme the link anchor HTML element

  for a targeted menu on the theming level (theme functions)?

We can theme the
 elements and the menu block elements with HOOK_menu_link_MENU_NAME(). Thanks to David Thomas for pointing that out to me. But I had no luck with targeting the nested anchors itself. The Devel array output and the drupal.org docs only brought me to theme_menu_item_link(), theme_links, theme_link(), and others, but I can't see an opportunity here to elegantly incept dynamic values for css classes on the anchor element?

I would like to add style class attributes to the  element in  ul > li of a given menu (not of all menus, thats what theme_links() does)...

NOTES:

nested css targeting by altering the upper element is not an option
here, since the required css class is level sensitive and should NOT
be applied to the upper html element.
And yes, I know the menu_attributes module. It's an awesome
module I use very often. But the approach is different. I don't want
to change the menu link data in the DB, but the output only.
There is an issue for the theme_links() function on drupal.org mentioning
some trouble with its scope and how it works: https://drupal.org/node/588148

  theme_links(): Returns HTML for a set of links. => theme_links($variables)
  https://drupal.org/node/588148 => theme_links() is not really
  themeable [#588148] => Drupal core, theme system, normal, needs work,
  49 comments, 1 IRC mention

Another option would be to add  elements inside the anchor elements. I already did this for node objects but I don't know if this is possible here and if this is the right way to do it.
Edit: Here are two questions - 1 - 2 - on stackexchange I read thru' atm, since there are near issues discussed. Maybe it will enlighten me soon ... (Thanks to Clive, who has pointed me to the second one.)

I am probably looking at this upside down or backwards but, are you rendering this menu yourself, eg, you are calling theme('links', $variables) somewhere and can easily modify $variables?

If so, a quick look at the theme_links() function itself reveals the following comment...

/**
 * Returns HTML for a set of links.
 *
 * @param $variables
 *   An associative array containing:
 *   - links: An associative array of links to be themed. The key for each link
 *     is used as its CSS class. Each link should be itself an array, with the
 *     following elements:
 *     - title: The link text.
 *     - href: The link URL. If omitted, the 'title' is shown as a plain text
 *       item in the links list.
 *     - html: (optional) Whether or not 'title' is HTML. If set, the title
 *       will not be passed through check_plain().
 *     - attributes: (optional) Attributes for the anchor, or for the <span>
 *       tag used in its place if no 'href' is supplied. If element 'class' is
 *       included, it must be an array of one or more class names.
 *     If the 'href' element is supplied, the entire link array is passed to
 *     l() as its $options parameter.
 *   - attributes: A keyed array of attributes for the UL containing the
 *     list of links.
 *
 *  (rest of comment deleted)
 */

showing that what you need to do is put in an attributes key with each link, as, further on down in the code, when it is creating the link itself, it does, as the comment above also mentions, adds in the full $link as the $options parameter, eg...

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

So, if you create an attributes key that points to an array with a key of class for whatever link needs a special class, and that key itself points to an array containing that name, this class will be added to the anchor.


How to show results in entityreference autocomplete only after the user enters 5 characters I want to know if it's possible to show result of an entityreference autocomplete only when the user enters 5 or 6 characters.

One way to do it is create your own custom autocomplete (a good example is here) in your custom module. Then within your custom autocomplete function check if the submitted autocomplete string is 5-6 chars long then execute the search, like so (using the example from the tutorial above):

function demo_autocomplete($text) {
  if (strlen($text) > 5) {
  // execute your code here:
    $results = array();
    ... etc
    drupal_json_output($results);
  }
}


update text format "filtered html" on old nodes currently i have a content type with multiple nodes, that were created with a text format of plain text. is there any way to update all these nodes to be filtered html?

/admin/config/content/formats

i changed the default format to be filtered html, by making its weight -10 it is now at the top of the list. now when a user creates a new node it will have this format but how do i convert all the old ones?

Update the database directly using SQL queries. The queries are something like

UPDATE field_data_field_[example] SET field_[example]_format = '[text_format]';
UPDATE field_revision_field_[example] SET field_[example]_format = '[text_format]'

for a field named field_[example] that was created with the Field UI module and a text format with machine name [text_format]. Clear the cache afterwards.


How to make a theme hook suggestion for blocks according to region? Since Drupal 8 it is not possible with template naming conventions to load a specific block template according to the region it is placed in ("Per-region block markup and per-region block templating feature removed"). But I need to have different html for blocks if placed in a certain region. How do I accomplish this?

I've thought about using MYMODULE_theme_suggestions_block_alter but I don't know how to get the current region.

You can get region if you get Block Entity.

.module or .theme file

use Drupal\block\Entity\Block;

function MODULE_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (!empty($variables['elements']['#id'])) {
    $block = Block::load($variables['elements']['#id']);
    $suggestions[] = 'block__' . $block->getRegion() . '__' . $variables['elements']['#id'];
  }
  /* Use this 'else if' only if you are using page_manager module and want to know which region is the block */
  else if (isset($variables['elements']['#configuration']['region'])) {
    $suggestions[] = 'block__page_' . $variables['elements']['#configuration']['region'] . '__' . end(explode(':', $variables['elements']['#plugin_id']));
  }
  return $suggestions;
}

Edit 1: Cover page_manager module case.


Create a new user on Webform submission I have a Drupal 8 website with an application form built with Webform. I would like to be able to auto create a user when the webform is submitted using details from the webform, so the person filling in the application can log-in and check the status of their application. I've seen several options online but all are for Drupal 7 and the modules used are not available for Drupal 8.

Any ideas?

You can write your own WebformHandler to do so. Just extend WebformHandlerBase and write your code into the postSave() function. Here is a little example: https://gist.github.com/mharmuth/0ab021d5b65e4cab7c6efec951fc59e9

This class has to be stored in your custom module in the directory your_custom_module/src/Plugin/WebformHanlder/CreateUserHandler.php

After creating this handler, you will be able to add it in your webform under "Email/Handlers".

Hope this helps ;)


How to use URL as a filter in view module? I asked a question here and now I am going to create a view that the view take the URL and use it as a filter.

and I want to have a the view by a dynamic filter use the URL path and show the result by different type something like sport, economy, etc.

Pathauto: news/[node:news_type]/[node:title]

I want to use [node:news_type] in my filter

You need to add a Contextual filter under the Advanced pane in your view's edit page.

Look for your field, it would probably be Content: News type then add the field
Under WHEN THE FILTER VALUE IS NOT IN THE URL select Provide default value
Choose Raw value from URL for Type
Choose 2 for Path component
Check Use path alias


Custom drush command not being loaded I'm creating a custom drush command in my module but it's not being seen. Wondering if someone would know why. The module is enabled. It seems the hook_drush_command() is never being called for my module, but I see it being done for other modules. I've tried clearing cache.

bir.drush.inc is located in /bir/drush directory

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

  $items['bir-process-images'] = array(
      'description' => dt('Process images on image server.'),
      'aliases' => array('birpi'),
      'arguments' => array(
          'days' => dt('Number of day(s) in the past to begin processing.'),
          'nids' => dt('Comma separated list of node ids to process.'),
      ),
      'required-arguments' => array(1),
      'options' => array(
          'days' => dt('Number of day(s) in the past to begin processing.'),
          'nids' => dt('Comma separated list of node ids to process.'),
      ),
      'examples' => array(
          'drush bir-process-images --days=7' => dt('Process images from 7 days ago to now.'),
          'drush bir-process-images --nids="2409,2309,5896"' => dt('Process images for given node ids.'),
          'drush birpi --days=7' => dt('Process images from 7 days ago to now.'),
          'drush birpi --nids="2409,2309,5896"' => dt('Process images for given node ids.'),
      ),
  );

  return $items;
}

When I type $ drush help at the command line, my command is never shown. I tried printing out the $items array in the function and it never even gets there. If I print $items out in another module, for example search_api, it prints to my screen. So, for some reason it's simply not picking up that I'm calling the hook in my file. Or, not seeing the file?

I figured it out. Even though I closed the command line window, I never cleared the drush cache. Running "$ drush cache-clear drush" fixed the issue.


Auto add nodes on save to a queue using entityqueue I am using entity queue module, Created a queue with a name ABC.

I want to add nodes automatically to this queue for a specific content type while creating new nodes.

Is there a way to do this?

Try Auto Entityqueue module to Automatically add entities to entityqueues.


How can I use NID Token with the Insert Module? I have setup insert module to upload images in a body field.
I want to set the path for the "FILE DIRECTORY" to the "node id" token but it does not show in the avaliable tokens.

The image field looks like

Browse avaliable tokens looks like

Why isn't the nid token available?

You want to use the filefields_path module to add node tokens to your imagefield (or any other file fields):

  The File (Field) Paths module extends the default functionality of
  Drupal's core Upload module, the FileField module and many other File
  Upload modules by adding the ability to use node tokens in destination
  paths and filenames.

In my test environment with the insert module and this module enabled, I now have the capacity to use node:nid in the filefield path as well as a number of other useful tokens:


Load Hierarchical list automatically from Hierarchical select option I have this Hierarchical taxonomy structure

In content type, I have a taxonomy term reference to this vocabulary using Hierarchical List provided by Hierarchical Select Module. When I want to add the content, I get the default Select Option as:

(Note the Update Button Above). When I hit Update then only I get child terms of iPhone

Now, if I want to select Nokia instead of Apple

I don't get that Update Button, or I cannot change it until I refresh the page.

Is there any way the Child list (list in hierarchy) would load without hitting Update and change whenever I change the Parent list?

In short : I want to get rid of Update Button and load the Hierarchy List automatically when I change the value in the list.

If I select Apple, the list in the Apple would show.
If I select Nokia then Phones under Nokia would show without having
to hit Update or Refresh the Page.

Instead use Simple hierarchical select module, It actually load child terms without button.

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.


Exposed filter AJAX error I have put an exposed filter on my page, which is an auto-submit textbox without any submit button. When I put the focus on this textbox and refresh the page with no value inside the textbox, the page gives me an error which is caused by emptiness of the textbox.

**Error:**
An AJAX HTTP request terminated abnormally.
Debugging information follows.
Path: /************/views/ajax
StatusText:
ResponseText:
ReadyState: 4

What is your solution for it?

When you give the focus to your field, it triggers an ajax call to the server. If you reload the page right away, it breaks the ajax call and throw this error in an alert.

This only happens as you reload the page during an ajax call. As far as i know you can't do anything about it, unless you modify the core I guess - which is "unclean".

You could use the classes added in css to display a loader while there is an ajax call to the server, and let the user know the page is working on something.

EDIT:

Thanks to clive's comment I actually got rid of this alert by overriding Drupal's Drupal.ajax.prototype.error function.

In a js file, you can add :

Drupal.ajax.prototype.error = function (response, uri) {
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  // Reattach behaviors, if they were detached in beforeSerialize().
  if (this.form) {
    var settings = response.settings || this.settings || Drupal.settings;
    Drupal.attachBehaviors(this.form, settings);
  }
};

This is a copy of the original error handler callback without the alert() function. This will remove your message, but will also hide any error message returned by Drupal's Ajax.


What if I don't want node pages for content type? I am creating a node type that I don't want to have a separate node page for. I am going to use a page view to pull them into a list. And they will link to a URL that is stored in a field for the content type.

These are simple content types and there is no need for them to have a node page. I know I can avoid having a page for them just by having no way to get there, but is there anything else to think about.

Maybe they should be something else besides a content type? Or is there a better way to not have node pages for a content type?

Edit:

I'm not really trying to prevent people from viewing these nodes. If they want to get to the node with the URL then that's fine. The nodes are just very simple(title, short blurb, link) and the node page would be pretty useless. I am just wondering if I shouldn't use some other Drupal construct for something like this.

You are looking for Internal Nodes

  Some content/nodes should never be viewed directly; only visible be
  through something else such as Views or Panels. This module denies
  access to node/[nid] URLs while allowing the content to stay published
  and otherwise viewable. Try the demo!


How do you theme a content type's create/edit form? Like it says -- I've got a D7 content type whose editing form needs to be themed.  I did this all the time in D6 by registering theme functions in template.php and writing the associated theming functions, but things seem to have changed in D7, especially regarding what goes into template.php, or if D7 has shifted to using .tpl.php files for this, or whatever.  Is there any advice out there?

You have two options.

option 1: using the template.php of your admin theme

Pick the right theme to customize.  Remember that by default, drupal 7 uses a different theme for administration and there is a setting under admin/appearance that says what your admin theme is and if content editing should use the admin theme.  look at this setting and figure out whether you want to customize your main theme or your admin theme.
once the theme has been identified, if that theme is a core theme and not one that resides in sites/all/themes or sites/something.com/themes, you may want to create a base theme rather than changing the existing theme.  it is a bad idea to change a core theme anyways.  Even if it is a downloaded theme, it makes sense to create a subtheme so that you can keep upgrading the downloaded theme when new versions come out.
(optional) to create a subtheme.  lets say, your admin theme is seven and it is also being used for content editing, simply create a folder called my_seven under sites/all/themes. next add a my_seven.info under the newly created my_seven directory with the following contents

base theme = seven
name = My Seven
description = My simple one-column, tableless, fluid width administration theme (child of Seven).
Now add a file called template.php under the same folder with the following contents.  please note that the form id is strictly derived from your content types machine name.  the template name however can be anything you please but -node-form looks like a good convention to follow.

<?php

function my_seven_theme() {
  return array(
    '<my_content_machinename>_node_form' => array(
        'arguments' => array('form' => NULL),
        'template' => '<my_content_machinename or anything else>-node-form',
        'render element' => 'form',
    ),
  );
}

now create a <content_type_machinename>-node-form.tpl.php file with the following contents to test if things are working.. once you see the custom form, just change the tpl.php to your heart's content. pick a custom field other than title to be sure it is working fine.. ideally pick something that is not a simple text field.  a term reference field type would be a good candidate to ensure that your subtheme is working ok.

    <?php print drupal_render($form['title']); ?>

    <?php print drupal_render($form['field_<my_field1>']); ?>

clear your theme registry cache (actually not required for the first time a theme is made use of but do it anyways)
set the new subtheme as the admin theme using the admin/appearance page.
edit a content or create a new content and you should see your modified form.

option 2: using your own drupal module to customize the form

create a new folder called custom_content_forms under sites/all/modules
create a custom_content_forms.info file with the following contents

name = My Custom Content Forms
description = A trivial module to customize my content entry forms such as smartphone
core = 7.x

create a custom_content_forms.module with the following content

<?php

function custom_content_forms_theme() {
    return array(
        '<contenttype_machine_name>_node_form' => array(
            'template' => '<contenttype_machine_name>-node-form',
                'render element' => 'form',
        ),
    );
}

now create a <content_type_machinename>-node-form.tpl.php file with the following contents to test if things are working.. once you see the custom form, just change the tpl.php to your heart's content. pick a custom field other than title to be sure it is working fine.. ideally pick something that is not a simple text field.  a term reference field type would be a good candidate to ensure that your subtheme is working ok.

    <?php print drupal_render($form['title']); ?>

    <?php print drupal_render($form['field_<my_field1>']); ?>

go to administration and enable the new module and you should see your customized form when you add or edit content of the targeted type.

NOTE: If you customize using both mechanisms, drupal will prefer the theme over the module.

EDIT: the above will only produce the fields.  you wont get the node settings menu and submit and preview buttons by default.  if you just add a

<?php print kpr($form); ?>

on the page (devel module needs to be enabled for kpr to work) to produce a dump of the $forms array.  You will see that you can get these things on your form page quite easily by adding the following to the tpl.php

<?php print drupal_render($form['additional_settings']); ?>

<?php print drupal_render($form['actions']); ?>


How to find a Data Selector in a rule condition? Update 3: I just need to know how to find a Data Selector in a rule condition

In a Commerce Kickstart distribution:

To reproduce:

1) I added a billing field called: "VAT NUMBER" at: "admin/commerce/customer-profiles/types/billing/fields"?

2) I created a Sale Tax at: admin/commerce/config/taxes

3) For this new Sale Tax I clicked at "configure component" to edit the "rule component" for the tax.

4) Now inside the rule: in Conditions I need to check if the field: "VAT NUMBER" is empty

Here is my problem: I don't know which is the Data Selector to get the field: "VAT NUMBER" and make the comparation.

I found this screencast which shows how to create a conditional tax based in the address field: http://www.drupalcommerce.org/videos/tutorials/drupal-commerce-condition...

I need to do the same that is shown in the video with the only difference that the condition for the video is based in the address field and in my case I need to base the condition to the value of "VAT NUMBER"

UPDATE: This post is no the solution that I need, but it might help to put it in the right direction: http://www.drupalcommerce.org/faq/rules-field-data-selection

UPADE 2 I tried to use the condition "Entity has field" but I can't find which is the right Entity to select to get the condition to TRUE

Found the way:

To drill to the selector I have to create 2 "entity has field" conditions.

1) entity "site:current-cart-order" has field "commerce_costumer_billing"

2) entity "site:current-cart-order:commerce-customer-billing" has field "vat_number"

then I can select the data selector


How to remove all nodes authored by users when their role changes? I have two roles on my site: Standard and Premium. Standard users are able to upgrade to Premium accounts. When this happens, I would like to deleted all content that the Standard users has authored.

Can this be achieved with Rules? Or, is there a different way?

You could use the Rules API to define a custom action that gets triggered whenever your users upgrade their accounts. In your custom action you could have a SQL query that searches all that users' content and deletes it.

For how to invoke a Rule programatically see this other DA answer: programmatically-execute-an-action-set-rules-module


How to redirect to a different URL based on node content while loading a node I have a site that uses the webforms module to gather user information. On the front page there is a list of previous submissions. Each of which has a link to view the submission (generated by Views module)

Link is like thingie.com/node/115/submission/1763

However, some users are saving the form as draft and coming back at a later date. When they get to the view page they aren't noticing they can click on the edit tab and are filling in a second submission. So we're getting 'weird' duplicates and they're wasting time.

As the submission view node is loading I'd like to check if it is a webform; which is in draft; and they are the submitting user. If so I'd like to redirect them to

thingie.com/node/115/submission/1763/edit

I think know how to do the redirect and the test but I'm being slow and am not sure what hook to catch.

I'm about to investigate the node load hook but wondered if there was a better way.

Ah ha... and I just learnt about row and field level templating in Views... isn't views incredible?!

I followed the instructions here http://drupal.org/node/352970 and can alter the link and it's text based on the context of each row.

Super!


FacetAPI graphs not working I have been trying to use FacetAPI graphs for my site but no luck yet .
after doing all the configuration set up facetapi - > selecting  'Graph Combo' in filter option and display configuration. when I execute the search , the search gives blank page in chrome , the same operation done in IE gives error 500 .
while doing  the configurations setup I noticed In Facet Combo the Y FACET scroll has blank. I dont know if it can be cause of problem .
Any pointers in fixing this is highly appreciated
Regards
Sakar

FacetAPI graph doesnt work with solrsearch it seems , I installed search api and was able to get all the options and fixed the problem .


REST post plugin broken from Drupal 8.4.5 to 8.5 I just upgraded my Drupal installation from 8.4.5 to 8.5
Now my REST plugin is not getting any data on POST.

My client post like this:

POST /rgptemprest?_format=hal_json HTTP/1.1
Host: 10.10.10.1:443
Authorization: Basic ****REPLACED******
Content-Type: application/hal+json
Accept: application/hal+json
User-Agent: ESP8266
Connection: close
Content-Length: 108

{"netcard":"997800940160","DS18B20":"28ADBCE70800008C","battery":"2952","temperature":"23.375","rssi":"-33"}

On my drupal server I have a plugin
with this code (not complete)

public function post(array $data = [])
{
    var_dump($data);
    if (!empty($data))
    {

....

And here I see the difference
on 8.4.5 it show an array of the data sent:

array(5) {
  ["netcard"]=>
  string(12) "997800940160"
  ["DS18B20"]=>
  string(16) "28ADBCE70800008C"
  ["battery"]=>
  string(4) "2952"
  ["temperature"]=>
  string(6) "23.500"
  ["rssi"]=>
  string(3) "-33"
}

but on 8.5 it's empty

array(0) {
}

What has changed between 8.4.5 and 8.5? And what do I need to change?

Wim Leers found the answer:

Change this:

public function post(array $data = [])

to:

public function post(array $data)


How to do autocomplete in a Bootstrap modal form? I've got a D7 page that constructs a Twitter Bootstrap modal form; it appears in response to a click on a button on the page.  I'd like to have in that form a textfield that uses the standard Drupal autocomplete mechanism; the problem is that the textfield isn't getting properly hooked into the autocomplete system.  I'm loading the Bootstrap versions of misc/ajax.js and misc/autocomplete.js into the page with drupal_add_js() so that they'll be around if the modal is invoked, but all the attached behaviors in autocomplete.js aren't getting invoked when the modal form is constructed and presented, and so the textfield stays a regular textfield.  Or so I think, anyway -- I'm kinda out of my depth here.

I suppose I could roll my own ajax code for the field, but the basic autocomplete behavior is so obviously the right thing that it ought to be used.  Any advice out there?  Thanks!

Drupal's JS is powered by behaviors. If you find yourself in a situation where you need to poke the system into life, you can manually attach the behaviors like so:

Drupal.attachBehaviors();


hook_file_dowload() randomly thinks user is anonymous I have a custom module implementing hook_file_download() for both public and privately managed files. At the head of my hook implementation I have the typical declarations to access the $user global:

function contractor_file_download( $uri ) {
  $caller = 'contractor_file_download';
  global $user;

  devlog( $caller.': uri is "'.$uri.'", user is "'.$user->uid.'"' );
  devlog( $caller.': globals user is "'.print_r( $GLOBALS['user'], 1 ).'"' );
  ...
}

The problem I'm having is that $user contains the anonymous user sometimes, if that makes any sense. Although it makes no sense, when testing via an OSX machine, any browser, the $user is always the valid logged in user. But when testing via any flavor of Windows, about 70% of the time both $user and $GLOBALS['user'] both contain the anonymous user. Yet, in all instances, the "My Account" link can be clicked and the correct logged in user profile loads.

What could cause $user to contain the anonymous user even after the user has logged in?

Additional info: the files being accessed getting the anonymous user are all private managed files.

Solution is insuring all site urls use the same subdomain, either including the www before the domain or not including the www before the site domain. Plus within .htaccess forcing all user urls to reference the site via that same subdomain qualifier.

The problem was inconsistent use of www and nothing as the site's subdomain.


Design views display and views filters separately? Looking of the exported views code it looks like the code for the filters is usually in a separate section from the fields and their layout.

With that in mind I want to separate out the aspect of views which cover the selection of fields and their display from the design of the filters, so I can continue to improve the filters on one page, whilst designing the data selection and presentation on another. I would then merge them into a new view later.

Is something like this feasible? Of course that means when designing a view I should not remove any of the fields in the display view which are used in the filters.

Views results (sometimes in Fields Format), Exposed Filters, Attachments are all output into their own HTML containers. But you can override each View output in templates (look under Theme: Information under Advanced View settings).

For whatever purpose you can create two different Views, or two Displays in the same View, define Fields in one, and define Filters in the other. Then later you can export both, combine and replace the relevant parts of the export into one and Import with an override of the existing View so you end up with a combined configuration.

But why would you want to separate them in the first place? You can add exposed Filters to a View, work on CSS to style them, then later add Fields and style them.

It isn't necessary to have the exact same Fields a in View that you want to use as Filters. Fields and Filters are independent. Maybe this is what has been tripping you up?

You can have Filters that filter out one Content type and also filter by creation date. While in Fields show Titles, Author and Taxonomy terms. A completely different set of information in those sections.

A lot of confusion may be coming from nomenclature. Views Displays are the different outputs you create according to your needs (Page Display, Block Display). Fields are bits of information defined in Content types. Views Results can be displayed as Fields. Filters control qualitatively what is shown in Views, if you expose them then users can change that themselves (Exposed Filters you usually see above Results that let you control the filters on the fly).


How to change user id from incremental integer to random hash? By default drupal uses incremental user id but I want random 7 character hash, is there any module that can help me with that? If not what is the simplest way to achieve that?

from:
    user/1

to:
    user/5rey2t5

by the way I know how to generate the hash in php I'm looking for the best way to implement it.

Just aliasing the path (as suggested by m1n0) will not be enough, as  users allowed to see the user profile will still be able to connect a user name and profile to a numeric user ID by entering an URL ending with user/ID (where ID is an integer, e.g. 1 for user #1). This will let anyone permitted to view user profiles to view the user name and profile associated with user/ID.

As pointed out by Jimajamma, totally replacing the numeric user ID with a random hash is a major undertaking, since just doing it will break a lot of stuff hard coded in Drupal.  No module exists that will do this for you.  If you want to do this, you'll have to start from scratch.

What you need to do to avoid numeric user IDs from being associated with specific user names and profiles is to prevent non-privileged users from ever seeing the user profile.

Navigate to  Administration » People » Permission and make sure that non-privileged user does not have the permission "View user profile".

After doing this, if a non-privileged user typed in an URL ending with user/1 (or anURL with any other numeric user ID) a 403 status code (Permission denied) will be returned.  Also user names that appear in bylines, etc. will no longer be linked to a profile when viewed by a  non-privileged user.


How to override template for view mode of a entity within a module? I see in theme suggestion array that I can override template for my custom entity type based on view mode like this:

  custom_entity__custom_entity__view_mode_name

Now I want to put

  custom-entity--custom-entity--view-mode-name.tpl.php

inside custom module.

I'm trying something like:

function custom_module_theme_registry_alter(&$theme_registry) {

  if (isset($theme_registry['entity'])) {

    $entity = &$theme_registry['entity'];

    if (!isset($entity['theme paths'])) {
      $entity['theme paths'] = array();
    }

    $entity['theme paths'][] = drupal_get_path('module', 'custom_module') . '/templates';

    if (isset($entity['theme path'])) {
      $entity['theme paths'][] = $entity['theme path'];
      unset($entity['theme path']);
   }
  }
}

So my template file is in custom_module/templates directory.

But after clearing cache always entity.tpl.php is used for all view modes.

I did this using hook_process_HOOK($variables) for nodes view mode tpls :

function view_mode_tpl_preprocess_node(&$vars) {
  $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__' .$vars['view_mode'];
}

hope this will help you.


How to avoid rendering of same node in two different view blocks on same page ? One of my page shows two different view blocks. Suppose View-block-1 and view-block-2.
Both renders and display nodes from same content type, say products. Node display Limit is set to 1 in both view and ordered by random.

Products:

Product 1

Product 2

Case 1

View-block-1  |   View-block-2

Product 1     |  Product 2

Case 2

View-block-1  |   View-block-2

Product 1    |    Product 1

Problem is that (case 2) sometimes both block shows same node since ordering is set to random.

Is there any way to ensure that both view do not show same node ?

Install Views exclude previous module.Then your views filter criteria will have a option like this

Views: Views Exclude Previous (<> Exclude nodes that where loaded in any node based view.)

This will restrict the same content to be displayed in page more than one time.

Hope this answers your question.


How to check for product taxonomy term in Rules actions (Ubercart) I am using Drupal 7 with Ubercart. I am trying to configure to send an email when customer makes a purchase of a product mapped to one particular taxonomy term.

I tried adding actions in a custom rule (created with Rules). But there is no such action available to check the product field values or based on taxonomy terms.

Is there any alternative ways to check product fields in Rules actions?

Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tags" } },
      { "list_contains" : { "list" : [ "node:field-tags" ], "item" : "21" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_tags] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_tags", which is the machine name of the term reference field I want to check for.
List contains item "node:field-tags" and with Taxonomy term identifier value "21" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_tags] just got created or updated." (with [node:field_tags] the actual term with term id = 21).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions.

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Replace the Rules Event with an event that matches your "when customer makes a purchase of a product".
Within the Rules Conditions, perform these changes:

replace the "node" entity with your entity.
replace the machine name of term reference "field_tags", and adapt the "term id" to fit your case.

Replace the Rules Action by "send an appropriate eMail".


add content reference to product in drupal commerce how can I add content reference to commerce product?
consider your product is mobile phone, and you don't want to enter add specifications of the phone, just make content type of phone, make phone contents and reference them in product.
is there a better way? because I couldn't reference content in product.

I found the solution anyway:

Using EntityReference module this can be done!! you just add an entityreference field to your product and then in settings you choose your bundle.


How to get rid of auto generated classes in secondary menu links and add my own classes I have taken the standard code for secondary menu from a Drupal 7 theme:

 <?php if ($secondary_menu): ?>
            <?php print $search_form; ?>
          <?php endif; ?>
    <?php if ($search_form): ?>
        <?php print theme('links__system_secondary_menu', array(
          'links' => $secondary_menu,
          'attributes' => array(
            'id' => 'secondary-menu-links',
            'class' => array('menu', 'nav', 'navbar-nav'),
              ),
              'heading' => array(
                'text' => t('secondary'),
                'level' => 'h2',
                'class' => array('element-invisible'),
                  ),
                    )); ?>
                  <?php endif; ?>

Now the ht,l output generates some autogen css witch i whant to get rit of and replace with my own classes?

secondary

My account

Log out

How to delete menu-3 and menu-15 as well as all classes following when we add more links and add some custom links to work with stuff like font awesome?

You can use this preprocess hook to modify the menu classes.

For example, modify the output of the secondary menu links like this.

function YOURTHEME_links__system_secondary_menu(&$variables)
{
   $output = "";

   foreach ($variables['links'] as $item => $link) {
      $classes = array('class1', 'class2');
      $output .= sprintf('
%s
', implode(' ', $classes), l($link['title'], $link['href']));
   }

   return $output;
}


A views page as “Output this field as a link” in a block (Drupal) Hello I´m trying to get a link from my thumbnails gallery http://www.nellens.com/home/photos to the full size gallery http://www.nellens.com/home/photos-full for each "Photo" content type that I have, but when I put the node (I tried with 2 methods, first creating a text field where I put the URL and another following this tutorial drupal.org/node/1215544, so I put in this case [counter]), but nothing overwrites my output link, it always lands to /content, showing all the fields of my content type, and I just want to show my full size pics fields only, not all the fields. My content type is made by a thumbnail image, the full size images that have relation between them and a tag field. So I did create all as in the FAQ tutorial but when I try to overwrite the thumbnail in the block to show the relative images and to land to the page /photos-full, it just does not work, it always lands me to /content.

Thanks in advance.

Images can automatically be made to link to either their node or directly to the image itself using the 'manage display' tab on the content type: admin/structure/types/manage/content_type/display

I would simply make your view an unordered list of teasers and link each image to the file itself if you only want to display the image, or if you would like to have other fields such as a description you could select content and link it out to the node. I am not sure how you have your content type setup but best practice would be to have the fields setup similar to the screenshot below. You would have one image field per photograph and simply use the teaser display mode and image styles to display thumbnails in a listing.


how to create a link to mysite/user and how to theme mysite/user? I have searched for this for some time and the only thing that pops up is how to create/customize your own login/register page.

I would like to add a link to the default Drupak 7 login/register pages and keep the default Drupal 7 login page (mysite/user) and registration page (myste/user/register). Furthermore, I would also like to add some fields to them.

I am currently using the LoginToboggan module and it has provided some help. Could someone please tell me how I can create a stand alone link that i can theme on the front page that will take a user to login/registration pages?

For example, I would to display something of the following on the front page:

login | register

So both 'login' and 'register' are stand alone links that appears somewhere on the front page and can be themed. but when clicked on, they will take the user to mysite/user (for login) and mysite/user/register (for register)

Thank you any help would be appreciated.

Like Stan Ascher posted the simplest and quickest way would probably be to create a block with the links and set it to appear where you want on the front page. With a wysiwyg editor it should be fairly easy to get the output themed to your liking as well.

If adding a block is not suitable for one reason or another there's also the option to manually add the necessary code in your theme's page--front.tpl.php file or if it doesn't exist then page.tpl.php. The code could look like this:

<?php if ($is_front): ?>
<div class="user_links">
  <?php print l(t('login'), 'user', array('attributes' => array('class' => array('login')))); ?>
  <span> | </span>
  <?php print l(t('register'), 'user/register', array('attributes' => array('class' => array('register')))); ?>
</div>
<?php endif; ?>

If the code is going into page--front.tpl.php then remove the first and last line. Basic HTML, CSS knowledge would probably be necessary with this approach though.

You can add fields for users on the 'admin/config/people/accounts/fields' page or select Configuration -> Account settings then the manage fields tab. These can be set to appear on user registration and users can edit them later with their other profile information.


How to get the value / URL of a Link field in a Twig template? I have a custom block Type with a Link field called "field_link" (for internal links only). Within my block Twig template I want to extract the URL of the link field. How can I do that? I read some post with similar problems, but none of the solutions seems to work so far.

What I tried so far:

{{ file_url(content.field_link.uri) }}
{{ file_url(content.field_link.0.url) }}

I only get "/" but there should be "/node/1"...

This is my standard block template:

<div{{ attributes.addClass(classes) }}>
      {{ title_prefix }}
      {% if label %}
        <h2{{ title_attributes }}>{{ label }}</h2>
      {% endif %}
      {{ title_suffix }}
      {% block content %}
        {{ content }}
      {% endblock %}
</div>

You can get the URL and the value (text) this way:

{{ content.field_link.0['#url'] }}

{{ content.field_link.0['#title'] }}


Drop UserMailRequired constraint In my Drupal site, only administrators create users. And users are created without an email. Users can edit themselves some of their account fields, but the email is not one of them.

But the user module adds a UserMailRequired constraint to the User entity email field. On submit, the user module's validator UserMailRequiredValidator adds a violation if the current user is not an administrator :

class UserMailRequiredValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    /** @var \Drupal\user\UserInterface $account */
    $account = $items->getEntity();
    $existing_value = NULL;
    if ($account->id()) {
      $account_unchanged = \Drupal::entityManager()
        ->getStorage('user')
        ->loadUnchanged($account->id());
      $existing_value = $account_unchanged->getEmail();
    }

    $required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));

    if ($required && (!isset($items) || $items->isEmpty())) {
      $this->context->addViolation($constraint->message, ['@name' => $account->getFieldDefinition('mail')->getLabel()]);
    }
  }

}

So, none of my user can edit its profile. On submit, they get an error message "Email field is required". Even if the field's #required property is set to false (using hook_form_alter) and the field not displayed (#access = false) in the form render array.

How can I drop this constraint from a custom module ? (using a hook for example)

For those that find themselves here trying to make User Emails Optional, use hook_validation_constraint_alter. You're not extending core's, you're creating a new constraint and using it instead of core's. In my case, I replace core's with... an empty function to achieve what I want.

Something like this in .module

function optional_account_email_validation_constraint_alter(array &$definitions) {
  $definitions['UserMailRequired']['class'] = '\Drupal\my_module_name\Constraint\OverrideUserMailRequired';
}

Then a copy of the two UserMailRequiredValidator.php and UserMailRequired.php files changed to your liking.

The module administerusersbyrole has a working example of this.

I'll see if I can get around to putting my custom module onto drupal.org in the coming months.


How to call fields individually like this in Twig template? I'm familiar with the Drupal 8 theming API,as well as all of the theme template suggestions available when Twig debug is enabled. I have created content type named (machine name) events .For overriding node.html.twig I have made node--events.html.twig . In this (node--events.html.twig) file I am trying to get individual values like below:
{{content.body}}
But it returns null . I have also tried {{ node.field_machine_name.value }} but It is not working for all the fields .

In my node twig template file I have this which works for me:

{{ content.field_name|field_label }}
{{ content.field_name|field_value }}

This works if the twig_field_value module is enabled.


Fatal error: while enabling AT theme I tried to enable AT theme and now have a white page with the error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /Applications/MAMP/htdocs/test/includes/theme.inc on line 98

I changed my php.ini memory_limit = 128M. No difference.

I am so crazy pressed for time, this is the worst thing to happen now. How can i fix this?
Please somebody HELP!!!!!

The site is on a localhost.

PS- now i see a different error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in /Applications/MAMP/htdocs/test/sites/all/modules/ds/includes/ds.registry.inc on line 554

Drupal 7.2.4

Looks like 128M of memory is still not enough, try more. If that still fails there's probably a memory leak or endless loop somewhere, or a too bloated configuration (e.g. too many fields, trying to debug a structure that has too many entries and so on).


Setting custom permissions in a view on a per-display basis Context

D7
Views (latest version as of this writing 2017-02)

Scenario

SingerRegarn has a D7 view with five displays, where the access control on each display is set to:

Access:Permission | View published content

SingerRegarn creates another display, but she wants access control to be set to:

Access:Permission | Administer users

SingerRegarn configures the permissions for the newly created display, using the setting:

For: This page (override)

SingerRegarn then saves the newly created display.

Problem

After saving the newly created display, the permissions for the newly created display do not differ from the other displays, as desired.

Question

Is there a bug-fix or workaround to prevent this unexpected behavior?

See also

https://www.drupal.org/node/1174588
https://www.drupal.org/node/1380402
In Drupal 7 Views how do you set permissions via roles for an attachment display?

Okay, so I put this to the test, using you example. I did not experience any unexpected results. I created 3 displays and set 2 of the displays to Access:Permission | View published content. For the 3rd display, I set it to Access:Role | administrator. When I'm logged in as an Administrator, I can view all three display pages. However, when I try to view the 3rd display page as an unauthenticated user, it returns an access denied error. Displays 1-2 remain visible to an unauthenticated user.

My configuration of display 1-2:

What my view page looks like for display 1-2 (viewed as unauthenticated user):

My configuration of display 3:

View page for display 3 (viewed as unauthenticated user):

I'd double check your configuration to make sure it's correct! If you're still having issues, you could output your displays as blocks. Then you could apply permissions on those blocks using the admin/structure/block interface. You can also plug in view blocks into something like a Panel page, and apply permissions to your Panel pages.


How do I implement access checks based on referring nodes in the grants system? Following a suggestion in another thread here I'm trying to rewrite the access restrictions that I developed using hook_node_access (and that are working well, so far) in Drupal's grant system (i.e. using hook_node_access_records and hook_node_grants). I would like to do that for two reasons:

I'm worried that the current access checks might become a performance bottleneck, when the number of users grows.
I need to use the results of access checks as a filter in views.

Here's a truncated version of my current access checks:

function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
  $type = $node->bundle();
  $user = $account->getAccount();
  $uid = $user->id();

  // only handle the lesson content type
  if ($type === 'lesson') {

    // ...

    // check the user's access to the referring courses
    $courseaccess = FALSE;
    if ($node->hasField('reverse_entity_reference')) {
      $parentcourses = $node->get('reverse_entity_reference')->getValue();
      foreach ($parentcourses as $course) {
        $coursenode = \Drupal\node\Entity\Node::load($course['target_id']);
        // perform access checks for the referring course
        $courseaccess = $courseaccess || ...
      }
    }

    // ...

    // return the result
    if ($courseaccess) {
      return AccessResult::allowed();
    } else {
      return AccessResult::forbidden();
    }
  }

  // ...

}

Note that, in essence, I need to check, whether the current user has access to any of the nodes (courses) that are referring to the viewed node (lessons): That determines, whether the user may access the lesson. I'm using reverse entity references for that.

As I see it (I'm open to suggestions), there are fundamentally two ways for approaching this. Unfortunately, so far, I have been unable to solve the problems involved. So, in my understanding, I could...

Put (more or less) the full access logic into hook_node_grants: That would mean, I need to have access to the currently viewed node (lesson) in hook_node_grants to be able to follow its reverse references to check, whether the user has access to any of the referring nodes. Is that possible? There's no $node variable...
Put (more or less) the full access logic into hook_node_access_records: In that case, the problem is that the hook only gets called (and thus the lesson gets updated), whenever the node is saved. So, the access restrictions will be out of date, as soon as a lesson is included in another course.

I'm unsure how to proceed at this point. Is it even possible to rewrite this in the grant system? Any other ideas?

Given that we don't have an exhaustive list of requirements & Q&A isn't suited well for long discussions, it will be impossible to definitely say yes.

The grant system isn't designed around any sort idea of hierarchy. Is it possible to rewrite? It depends if you can refactor your existing logic around what the grant system supplies.

You've framed your question as a dilemma, but you really need both hooks to use the grant system:

hook_node_grants need to assign realm/gid grants that correspond to the $user and the available lesson nid they can access.
hook_node_access_records needs to fire against a lesson $node

So if you can:

Map the realm/gid grant keys to match to courses the user has access to (e.g. mymodule_course_realm/123 where 123 some group identifier that maps to a group of users that have course access, thus lesson nid access)
Trigger lesson save events upon course updates (e.g. using hook_node_update, hook_node_insert, etc. to look for update courses, then doing dummy saves on the lesson nodes) so that hook_node_access_records can fire against lesson nodes that have a changed relationship. (or build custom logic where you insert grants directly via NodeGrantDatabaseStorage::write())

You can probably refactor around the hooks the grant system provides.


Views slideshow fields I have an image field in my content type and I want to make a slideshow using the Views Slideshow module to show one image at a time.

If I put each image in a node of its own, the slideshow works fine. But can I have a slideshow using multiple images from the same field in the same node?

The point of this is that it is easier / quicker to create one node with 10 images than to create 10 different nodes. So far the slideshow seems to load all 10 images at the same time, but I want it to display only one image at a time.

Interesting question, but I wonder if the Views Slideshow module can do what you're trying to achieve. Therefor you may want to consider the alternative modules, as detailed below.
Use the jCarousel module
Your question seems to be a variation of "Help with a Slideshow of Multiple Images in a Single Node", in which the Views Carousel module was recommended as a possible solution/alternative.
However the successor of that module in D7 is the jCarousel module. So maybe you want to give that module a try?
Use the Field Slideshow module
Another module to consider as an alternative, is the Field Slideshow module. Here is a quote about it from its project page:

Provides a Slideshow formatter for Image fields, using JQuery Cycle plugin.
Compared to Views slideshows, building the slideshow from multiple nodes, this module builds it from a single node, with a multi-valued Image/Media/Field Collection field.

This excerpt seems like pretty close to what is contained in the question details, no?
Curious to hear if either of these modules help somehow ...


how to make relations link when editing taxonomy not show When a user edits a taxonomy term, there is a link for "Relations" at the bottom.  how can I make that link not show up for certain roles?

You may create your custom permission in the hook_permission and then hide this part of the form in using hook_form_alter if user shouldn't have access to this element.


Multisite with content sharing The last couple of days I have been looking into Drupals multisite with content sharing. Got some great information like http://palantir.net/blog/multi-headed-drupal and http://munich2012.drupal.org/program/sessions/multi-headed-drupal

It gives me a good idea of the options I have building a multisite and content sharing setup. As I am quite new to Drupal I am trying to get input on my setup and the architecture that is required to build it. I will briefly explain the architecture and then the options I think will be suited for this.

Basic setup
The basic setup is as follows. There will be 1 global website with an own admin/editor. Next to the global site there will be 10 regional websites with their own regional admins/editors. The regional websites will have content in their own language, but in the CMS there is an option to translate the content to English.

Global website
The global website will be a 1 page website and it displays content (English) from the regional websites. Content that needs to be curated by the global content-editor.

Regional websites
The regional websites are all the same (pages , nodes, content types) except for some different styling and logo's.

Access levels
The global admin can access all the websites, this can be using other logins or preferably an own global account. The regional admins/editors can only access and edit their own site.

From the information I have so far, this will require a combination of Domain Access and Organic groups but I am not sure if this is going to work.
My main concern is combining a global home with the regional websites and push content to the global home. Not only pushing but the the global editor will need to approve content before displaying it on the global home.

Does anyone know if we can build such a setup with Drupal?

Thanks in advance.

I might think about using a login mechanism like OAuth (with its Connector module) or an LDAP instance so that your global admin can login to any site with the same login.

To distribute the content, I would try using a REST API from the regional sites via the Services module which supports login if content or views needs access control.

Good luck!!


Entity Reference - Auto complete field in content type I had an issue before (please click here to see it) related to entity reference and I was able to solve it with no problem. Now I have another issue:

I have 2 content types called projects and partners.

In the content type partners I have a field "projects" and I'm able to select from all the project pages that exist in my site. So far so great.

Now, in the content type projects I have a field "partners" and I would like this field to be autocompleted with the partners where that project was selected before.

What's the best way to do this?

Please let me know if you need any clarification, I know my English isn't the best.

Thanks so much in advance!

You can do this in various ways.

An easy option would be to display a view as the field. There are quite a few solutions that enable you to do so, such as:

Viewfield,

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.

Field Embed Views,

  The module provides a field type to attach any Views View display
  with, configurable on per-entity level, default values for exposed
  filters and sorting.

EVA,

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity.

Panels, Display Suite,  etc.

The view will list partners and the contextual filter will be the current project you are looking at.

If your field is also an entity reference field, then you should probably look at Corresponding Entity References.

Think about your solution where you will be duplicating database storage (both ends of a relationship) when one end can easily be computed (via an sql query for instance). Maintaining the data on both ends means more work as you have to synchronize it constantly, as well as more storage. Maintaining the data on one end only and making the other end purely a display issue is more maintainable.


Why cannot anonymous users vote, even though they have permission for it? I installed the Fivestar module and added the Stars (rated while viewing) field in a content type.

I gave to the rate content permission anonymous users. They can see all the content and the voting widget, but they can't vote. Why?

A possible explanation for this might be what is described in this issue on D.O: Fivestar Not Working for Anonymous Users with Cache Enabled.

A possible workaround for it is mentioned in Comment #9 of that issue, which states:

  ... When I set the author to anonymous on the field also set the field to allow users to vote on their own content, this appears to work as a crude work around.

Curious to hear if this somehow helps ...


Issues with custom redirect url using tokens when form field is empty I am trying to use Drupal webforms with tokens to build out a redirect url for my form submissions. Everything works great when all fields are populated, but if a field is left empty the redirect does not happen. Promo code is an optional field. This is with Webform 6.x-3.14

Redirect URL: %value[app_url]/user/new?email=%value[email_address]&first_name=%value[first_name]&last_name=%value[last_name]&promo_code=%value[promo_code]

I ended up writing a custom module to do the post using the following code as a starting point
http://www.midwesternmac.com/blogs/jeff-geerling/integrate-webform-3x-paypal


D7 performance issues once uploaded to remote server I just recently uploaded my D7 site to a remote server and now seem to have long wait times to do anything. I have caching turned off and am still in development mode. Could it be certain modules I am using. I tried turning devel but still same wait times. What do I need to do to speed things up? everything was quick when I had the site local...

NOTE:
- I am using Godaddy. i would think they have sufficient resources.

Check if you're experiencing the same issue for anonymous visitors?
Try increasing php memory
When was the last time you ran the cron?


Zen header 'site name' + links issue I'm using a Zen sub theme, and I've placed the main menu block into the header.

I would like to place the links to the right of the site name, but they only sit underneath. I've tried playing with the CSS styles that control the menu block, without success.

Is there a special trick of Zen's quirk I'm missing?

I am new to coding so anyone should feel free to correct are add to this.

Your theme is placing the content on a page using a file called page.tpl.php. It may be found in your subtheme folder or in the parent them folder. This file is responsible for assembling the HTML code that actually displays your page.  The file is a text file and is easy to open and edit (not as easy to understand if you are not familiar with HTML and PHP.  I am using Fusion themes, so there may be some difference, but if you search for 'menu' you will find the part of the template that generates the menu.  There you will probably find a HTML command to 'clear' or a Class definition that will include the clear command.  This command is telling the browser to push further content in the region, such as your block, to the next row.  To change this you will need to make an override page.tpl.php file (copy the parent theme file into your subtheme directory and remove the command. If the command is in the CSS file, you will have to alter the CSS file containing the class definition.

I do not recommend doing this if you are not yet familiar with coding in Drupal (do a bit of research first).  Good luck.


Specifying text format when creating field on custom node type I have a module that's creating a custom node type. I'm attaching a textarea to this node type. Currently it works, but the text formatting defaults to "Plain Text."

I would like to specify during installation that the field should be set to "Filtered Text," specifically, "Filtered HTML." This seems like something that should be possible when defining the instance of the field, but it's not working.

Here's the instance definition as it stands now:

<?php
// ...more fields above
    'release_notes' => array(
      'field_name' => 'release_notes',
      'type' => 'text_long',
      'label'  => $t('Notes'),
      'description'  => $t('Release notes (e.g. liner notes)'),
      'widget' => array('type' => 'text_textarea'),
      'settings' => array('text_processing ' => '1'), // Filtered HTML...?
      'weight' => 9,
    ),
// ...more fields below
?>

Does anyone have any ideas?

Thanks.

Set the 'format' => 'filtered_html' to allow filtered html

<?php
    // ...more fields above
        'release_notes' => array(
          'field_name' => 'release_notes',
          'type' => 'text_long',
          'label'  => $t('Notes'),
          'description'  => $t('Release notes (e.g. liner notes)'),
          'widget' => array('type' => 'text_textarea'),
          'settings' => array('text_processing ' => '1'), // Filtered HTML...?
          'format' => 'filtered_html' // <<--- Set this value to allow filtered HTML
          'weight' => 9,
        ),
    // ...more fields below
    ?>


Load only the submenus under given menu How to get ONLY the list of Submenus under given menu programmatically. Say, the given menu means a main-menu item. I tried with menu_tree_page_data. But not sure if I can use it to select only the required menus.

The scenario is, I have active menu loaded using menu_get_active_trail(). So I have all the details of the main menu. Now with those details I need to get the submenus under that.

$main_menu_tree = menu_tree('main-menu');
foreach ($main_menu_tree as $key => &$main_menu_item) {
    if (is_numeric($key)) {
        $main_menu_item['#below']['#theme_wrappers'][0] = 'some_other_theme_wrapper';
    }
}
print drupal_render($main_menu_tree);

If you have array of main menu active trails you can use foreach to loop through the array print menus and their sub menus.


Attaching Conditional widget on Drupal Field I have extended drupal user registration form by attaching fields to user entity.

One of the field is to let user select duration. I have set it up as radio button.

Form: When you started:

(radio button) Not yet started (need help)

(radio button) Just starting (1-2 years)

(radio button) Traction: (2-3 years)

(radio button) Experienced: (4+ years)

(radio button) We started our CI program in: (field for year)

Now the requirement is if the user select any of the top 4 options it shoudl go as it is. But if none of the above suites users choice than he will select the last radio button and on this radio button he should be able to type his year manually. So basically a text field should appear. I've no clue how to achieve this and didn't find it on google too.

You should create another field for the year and use e.g. Conditional fields module so that year field appears only when a specific option is selected.

Generally speaking, you should use form API states processing, and the Conditional fields provides UI for that.


How do I get rid of the Search at the top of the search results page? A customer of mine insists on having Search Results as a heading. I can set this on the block I have created using the Custom search module.

How do I get rid of the
Search
 at the top of the search results page?

I suggest way three way

Hide it with css ( set it to display:none)
Remove it with simple Jquery command  ( .remove)
override  search result page template

I mean duplicate page.tpl.php file in your custom theme set name to page--search.tpl.php and remove
<?php print $title; ?>
. finally don't forget clear the cache

If this TPL doesn't work then you have to declare it in template.php using theme_hook_suggestions in the same way as answer of your linked question. See for the URL which your instance is using for giving search result.

For $base_url/search use

//replace your theme name with MYTHEME
function MYTHEME_preprocess_page(&$vars) {
  if (arg(0)=='search') {
    $vars['theme_hook_suggestions'][] = 'page__search';
  }
}

Add this in your template.php & as you are suggesting TPL for page, you have to use THEME_preprocess_page($vars).


How to check the value from data sheet during Feeds import? I am trying to import some data by using feeds importer. I want to check if there is any information under "equivalent" Source in the sheet. If there is no value, just skip the import. If it has, continue and finish the import process.

I saw there is an event called "Before saving an item imported via Recommended Product Import(importer name)."

Does anyone have any idea about how can I set the condition and action parameter for implementing this rule?

This is one column from my sheet and rule sheet (you can see some products have equivalent, some do not have):

Thanks everyone, I got the answer. Instead of using Rules, I created a "custom feeds module."

Steps:

Create a folder named "custom_feeds"
Create two files, one is "custom_feeds.info", another is "custom_feeds.module"
Add following information in the .info file:

name = custom feeds module
description =custom feeds module
core = 7.x
package = Feeds
dependencies[] = feeds</code>

Add following code in the .module file inside <?php ?>:

function custom_feeds_feeds_presave(FeedsSource $source, $entity, $item) {
  // check that this is fired only for the importer being used
  if($source->importer->id=='recommended_product_import'){
     // "equivalent" is the column name in excel sheet
     if(!strcmp($item['equivalent'],"")){
       $entity->feeds_item->skip = TRUE;
     }
  }
}


switching between 2 views I have created two Views, I then placed the second view on the footer of the first view. Main view has date, an image, attachment and size of the attachment, the second one has an images that are linked to a files.
Output, latest one should always display on the top with an image, attachment and size of the attachment which I got it right when I click on the image from the footer I want an image to display above with the attached file and the size. May anyone help on how I can do the switching part in. See an the attached, am using Drupal 7

I have actually resolved my problem by adding a piece of php code within filter criteria. see attached.


Node teasers in node object filled with full node body if teaser is not defined When Editor saves the Node, If teaser field is filled, normally teaser node object is filled with that content.
But if Teaser field is not filled, System is populating teaser of node object with body of the Node.

That is kind of weird because i need to detect if node has teaser or not, programatically.

Is there a workaround how i could detect programatically that Node was saved without teaser has been touched ?

You can check summary text in node obj.

if (empty($node->body['und'][0]['summary'])) {
//do something
}


Views Contextual Filters with Wildcards URLs I have a view with two page displays.  The first page uses a contextual filter for the UID, which is provided with a default value for the user that is currently logged in to the site.  One of the fields displays an order ID, and I have a second Global: Custom Text field which displays a link that appends the order ID to last path component of the URL.

The second page display uses a wildcard within the path of page settings, that matches the scheme of the link generated in the first page display.  When the argument is provided in the preview everything works as expected, however when the URL is accessed via browsing I only see a blank page.

Does anyone have any ideas of why this may be happening or have additional information regarding using path wildcard and contextual filters.  Thanks in advance for any possible advice or tips.

It seems that the error had to do with URL that was used in the path.

When I originally had the issue I was using "account/page/%" , but after removing account so that it read "page/%" everything began to work as expected.


Table form valueCallback strange behaviour I am creating a table form using the table element. I do not push sub elements into #rows. I work as with children elements. But valueCallback does not map values right. I am looking inside. It looks very strange. Especially:

return is_array($input) ? array_combine($input, $input) : [];

$input always is array. So combining result is weird with "array" key
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Table.php/function/Table%3A%3AvalueCallback/8.5.x

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

  // If #multiple is FALSE, the regular default value of radio buttons is used.
  if (!empty($element['#tableselect']) && !empty($element['#multiple'])) {

    // Contrary to #type 'checkboxes', the default value of checkboxes in a
    // table is built from the array keys (instead of array values) of the
    // #default_value property.
    // @todo D8: Remove this inconsistency.
    if ($input === FALSE) {
      $element += [
        '#default_value' => [],
      ];
      $value = array_keys(array_filter($element['#default_value']));
      return array_combine($value, $value);
    }
    else {
      return is_array($input) ? array_combine($input, $input) : [];
    }
  }
}

For me $input already is ready to move into #value. It does not need altering here.
I hope it works well and I do something wrong. But not it seems weird for. Clarify it, please.

My solution is below. It is a weird solution because It requires small changes.

Define a table value callback.

    $form['links'] = [
      '#type' => 'table',
      ...
      '#value_callback' => array($this, 'valueCallback'),
    ];

Implement the callback.

 /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    return $input;
  }

The data has structure as it has been sent. So the standard data processing works badly for my case.


Oracle Weblogic Server My doubts about drupal requirements are:
- Can run Drupal 7 on a Oracle WebLogic Server? How would the integration be?
- Can i use the Oracle driver for this porpuse?

Yes you have to use Oracle Driver.

  This is a driver that allows Drupal to use an Oracle Database instead
  of MySQL as the primary backend.

Refer to these links :

Link 1
Link 2

I hope these links may definitely solve your query.


Which Drupal 6 theme framework is good for creating a responsive web design? Which Drupal 6 theme framework is good for creating a responsive web design? Is it advisable to use Zen starter-kit to develop a responsive theme?

Omega offers good responsive features.
"Fully Responsive Grid layouts based on 960.gs standards."

I have used this for many 7 projects but not tried 6, if this is a new project you are starting I would recommending starting with 7.


Different ways of logging in a user without having them to type anything? I'm on Drupal 8 and currently looking to replicate similar functionality like: https://www.drupal.org/project/urllogin -- They do not have a D8 version yet.

I need to auto login a specific user depending on which URL the user visits. How can this be done on D8? I was thinking of using rules, but there doesnt seem to be an action for "login a user" if Path alias equals X.

Another possible scenario I could just do is create a custom module to auto login a user. Which functions would I need to fire in Drupal 8 to do this?

You just need to use drupal_session_regenerate(), you can see the use of this function here. All you have to do is either play with Uid or if you want to do this for anonymous user then you just create a user xyz and use that ID for session regenerate. You can grab the UID from URL for different users like www.example.com/custom-url-to-login/125 or www.example.com/custom-url-to-login?uid=125

now supposing 125 be the ID of user whom you want to login on visiting the URL.

The code will go something like this:

global $user;
$user = user_load(540); // suppose 540 be UID of xyz account
drupal_session_regenerate();

This is just a suggestion, if it does not work for you please let me the know the correct solution.

Thanks


Can I Run custom callback in site maitenance mode In drupal site maintenance mode all custom menu callback is not working. it redirect into site maintenance page.
But user/login is working.
I need to create menu like user/login. please help me.

If you want to test few menu item when Drupal site is in maintenance mode. You can use Maintenance Exempt module.
From this module's page:

Drupal allows you to set your site into maintenance mode in order to deploy code and database upgrades safely. However, access to the site during maintenance mode is by default controlled by a permission, which is generally only given to administrative users. It's not possible to test the site as a regular anonymous or authenticated user without giving all anonymous/authenticated users the "Use the site in maintenance mode" permission, so you generally have to test those things on the fly after moving the site back to "live" mode.
Until now, that is! This D7+ module (the necessary hook doesn't exist in D6 and below) allows specific people to perform the necessary testing on the site with all role combinations without opening the site up to all of your visitors.


How do you use hook_form_FORM_ID_alter() to alter the USER EDIT form? I'm trying to mark fields on the /user/_uid_/edit screen as disabled.
These are custom fields I've created in /admin/config/people/accounts/fields in D8.

I have this code for another node entity type...

function MODULENAME_form_node_survey_edit_form_alter(&$form, $form_state, $form_id) {
  $form['field_content_type']['widget']['#type'] = 'hidden';
}

This works as expected, and on the node/123/edit screen for a that content type, that field is hidden. (works as expected)

(it gets populated by a migration process, and needs to stay how its set, even if users change other fields...)

My problem is, that I'm trying to disable a field on the USER-EDIT screen, such as /user/123/edit.

I'm trying the EXACT same code structure.

function MODULENAME_form_user_edit_form_alter(&$form, $form_state, $form_id) {
    $form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
}

But it doesn't work.

I've tried throwing in class changes, and other things to alter the input fields, but they don't work.

$form['field_organization_reference']['widget'][0]['target_id']['#attributes']['disabled'] = 'disabled';
$form['field_organization_name']['widget'][0]['value']['#attributes']['disabled'] = 'disabled';
$form['field_organization_reference']['#attributes']['class'][] = 'borkbork';
$form['field_organization_name']['#attributes']['class'][] = 'borkbork';
$form['field_organization_name']['widget']['#type'] = 'hidden';

All as attempts to try and change something on the user edit form.

But nothing is working.

Is user-edit the correct form id?   Is there something else I'm missing

Thoughts? Help? Thank you!

Try:

function MYMODULE_form_user_form_alter(&$form, $form_state, $form_id) {
  // Your code...
}

Inspecting element, I see the form id is user-form, which needs to be translated to the machine-readable name user_form

Otherwise, you can always do a standard HOOK_form_alter():

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_form') {
    // Your code...
  }
}

And always clear cache after adding/changing hook names.