Drop-down menu only works after clicking into the parent page first I am using the Venture theme for Drupal 7.
I have a 'Products' page listed in the main menu with a drop-down list that is a separate page for each product. However, to get the drop-down list to show up, I first have to click on the 'Products' menu link, which will bring me to an empty page.

I would like the drop-down list to display if I hover over the 'Products' menu item so the user can select a child product page right away instead of having to go into the parent 'Products' page first and then having the option to select from the drop down menu like it is doing now..
Ideally, I would like to not have to display the parent 'Products' page at all, and have it just be in the main menu as a way to access the drop-down list items to other pages.

Any suggestions would be appreciated.

Have you checked the "show as expanded" for the parent menu?

Edit your parent level menu and see if it's checked.

Check it if it's not and check the drop down menu again.


what function do i use to print out a menu? the menu was created in the admin i have node that i simply want to display a menu. the menu itself is a list of archived articles, and was created in the admin.

i know how customize the node to do so, page--node--11.tpl.php.

i deleted the print render $content. so now, my pseudo code would look like.

print $archive_menu;

or perhaps i need to call a function? can someone explain how to do this?

thanks

You can use menu_tree_all_data function.

E.g.

$tree = menu_tree_all_data('machine-name-of-menu');
//menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));

For more info go through the function documentation.

menu_tree_add_active_path will be found here. It will be used when you want to add active trail on menu.


How can I identify if a database is D6 or D7? I have been sent site files and a database for a website to review but have had trouble loading it up.  The core and contributed modules are all D7, but when I import the database and run a page on the browser I get a message,

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146
  Table 'example.semaphore' doesn't exist: SELECT expire, value FROM
  {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in
  lock_may_be_available() (line 167 of
  example.com/includes/lock.inc).

I suspect this means that the database I have been given is a D6 one, but need to confirm this.  Is the version declared anywhere, or is the absence of the semaphore the evidence I need?

In Drupal 6 the node revisions are in {node_revisions}, and in Drupal 7 the node revisions are in {node_revision}.  So, you can just check which table exists.  There are some structural differences with the tables, too.  For example there is a status column in D7, but not in D6.


Best way to keep local and remote sites synchronized? I run the same drupal site on a local server (i.e. my mac with mamp) and on a remote server (i.e. my hosting provider). I want to keep the two sites synchronized. My hosting provider does not allow ssh keys. I have already tried the drush aliases way, but with no success at all - I keep getting the message "no alias record could be found for source @.... So please, my question is this: What is the best and easiest way to keep the two versions (local and remote) of the same site synchronized?

For executing drush commands on others server you should have access via SSH, and you only have access via FTP. Your best option I think is doing every day on production a backup and download it and then in your local machine: drush sql-cli < db.sql or mysql db < db.sql

Maybe you can use the module stage_file_proxy so you don't have to copy files


Building EntityForm in Drupal 8 I'm continuously getting the error: Drupal\Core\Config\Schema\SchemaIncompleteException: Incomplete or missing schema for mymodule.myentity.myentityname in Drupal\Core\Config\Entity\ConfigEntityBase->toArray() (line 248 of core/lib/Drupal/Core/Config/Entity/ConfigEntityBase.php).

Here is how I'd implemented the EntityForm:

class MymoduleForm extends EntityForm {
  public function form(array $form, array &$form_state) {
    $form = parent::form($form, $form_state);
    $entity = $form_state['entity'] = $this->getEntity();
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#default_value' => empty($entity->name) ? '' : $entity->name,
      '#required' => TRUE,
    );
    ...
    ...

    return $form;
  }
  public function validate(array $form, array &$form_state) {
    parent::validate($form, $form_state);
    $entity = $this->getEntity();
    //perform validation
  }
  public function save(array $form, array &$form_state) {
    $entity = $this->getEntity();
    $entity->save();
    print_r($entity);
    //throws error here

    $edit_link = \Drupal::linkGenerator()->generateFromUrl($this->t('Edit'), $this->entity->urlInfo());
  }

Doing a print_r($entity) shows two Object results: one showing all the values I'd filed up in the form and the other completely emplty.

That error has nothing to do with your form.

You need to provide a config schema for your config entity, see examples in node.schema.yml and many other places.

See also the configuration schema documetation.


Field widget item form alter for file field I want to alter field widget item form of a file field with cardinality > 1 so that a new form element is added to each row of the file tables. For example, in the attached image, I want to add another text field below the "Description" for each uploaded file, even the one done via Ajax, not just the existing ones. I used hook_field_widget_form_alter() but it doesn't seem to work with the newly uploaded file. Any ideas?

A lot of the build logic for the file field widgets is handled in #process callbacks, so some detailed structures of each individual file's form element aren't really available during hook_form_alter()s.

You might want to preprocess the individual elements with hook_preprocess_file_widget(). Something like:

/**
 * Implements hook_preprocess_file_widget().
 */
function MYMODULE_preprocess_file_widget(&$vars) {
  // Make some alterations to normal file-field widgets.
  $element = &$vars['element'];
  if (isset($element['#file']) && is_object($element['#file'])) {
    // This is an existing file... alter $element accordingly.
  }
  else {
    // This is the actual upload widget... you may want to skip this or alter
    // it in a special way.
  }
}

You could also use hook_preprocess_file_widget_multiple() to specifically target a group of files in a file field that has cardinality > 1. In this case you may need to have some iteration logic to loop through the children elements with element_children().


How can I make individual nodes fieldable? One of the great things about the Entity and Field APIs is the ability to add fields to any entity (nodes, users, etc.) and subsequently any bundle (e.g. node content types).

But is there a way, using the Field API or the Entity API, to make fieldable nodes? That is, have field instances attach to individual nodes instead of content types/bundles. So node 1 might have a file field and a text field, node 2 might have a number field but no text field, etc.

If there isn't, is there any work being done using other concepts that would achieve the same result? The closest I can think of is Webform, but I'm sure that it's not intended to be a way to create content, and it doesn't take advantage of the Field API for its fields.

You could use something like http://drupal.org/project/conditional_fields but that's all done from a front-end point of view, which means Drupal doesn't really know about your structure.

http://drupal.org/project/properties looks interesting and may suit depending on your needs.

I had a similar issue recently and decided to split up into three separate content types instead of just one.


page-node-nid.tpl.php is not used as template file I am using the following code.

function chgakitheme_preprocess_page(&$vars, $hook) {
  if ($vars['user']->uid == 0 && arg(0) == 'user' && (arg(1) == '' || arg(1) == 'login')) {
    array_unshift($vars['template_files'], 'page-login');
    $vars['body_classes'] .= ' userlogin';
  }

  if (isset($vars['node'])) {
   $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);
  }
}

Now I can use page-nodetype.tpl.php, but I can't use page-node-nid.tpl.php because Drupal doesn't see it.

I need all types of template files. I want a template specific for a content type.

What can I do? Can I do this in Drupal 6?

Have a look at the Drupal 6 Template suggestions, The list of suggested template files is in order of specificity based on internal paths. One suggestion is made for every element of the current path, though numeric elements are not carried to subsequent suggestion, order of execution is as below:

page-node-edit.tpl.php
page-node-[node_id].tpl.php
page-node.tpl.php
page.tpl.php

  So basically you don't need to use the "TEMPLATE_preprocess_page" for using "page-node-[node_id].tpl.php" for template suggestion as it is provided by default. May be the problem is of "clearing the cache", try once after clearing the cache.

In Drupal6,  page-node-[node_type].tpl.php is not available by default, to make it work we customize the suggestions in the TEMPLATE_preprocess_page as done by you.

If you want more specific templates than you can customize the template suggestions as your requirement in TEMPLATE_preprocess_page. Example as below:

// Implement TEMPLATE_preprocess_page.
function TEMPLATE_preprocess_page(&$variables) {
  if ($variables['node']->type !== '') {
    // For using "page-node-[node_type].tpl.php" for template suggestion.
    $variables['template_files'][] = "page-node-" . $variables['node']->type;

    // For using "page-node-[node_type]-[node_id].tpl.php" for template suggestion.
    $variables['template_files'][] = "page-node-" . $variables['node']->type . "-" . $variables['node']->nid;
  }
}

After using the above code you can use the additional template suggestion as below:

page-node-[node_type]-[node_id].tpl.php
page-node-[node_type].tpl.php

NOTE: Don't forget to clear the cache after making changes to template files otherwise the changes won't reflect back.


How does routing order / matches effect performance? I have all the following GET routes defined in my_module.routing.yml:

my_module.members_uid:
  path: 'users/{user}'

my_module.members_uid_gid:
  path: 'users/{user}/group/{group}'

my_module.user.content.view:
  path: 'users/{uid}/{bundle}/{gid}'

All of these have the same requirements and options except they upcast different data types, and each has it's own controller.

All of my controllers execute correctly, however is there any benefit to a particular order? Or is there any extra overhead from two matching except one dynamic parameter?

The order doesn't matter, routes are stored indexed by name. The first and the second route have a different component count, so they can't interfere. The second route gets priority over the third, because it has one more fixed component. So in this case the route matching doesn't need any complex calculations. In general route matching rarely affects performance  because successful matches are cached.


How do I override a field template? I am trying to override a field template with my own one. The field is called field_test, so I created a field--field-test--mynodetype.html.twig template file ` in root-theme-directory/templates/, but Drupal doesn't recognize it.

I cleared the cache from the UI, enabled debug mode in settings.yaml, installed the Devel module, and re-generate the theme registry on each request, but nothing seems to help. The field gets always rendered with the default field.html.twig template.

How do I override the field template Drupal uses?

You need to specify the entity type (node, taxonomy_term, ...) in the template name suggestion as you specified, i.e. field--node--field-test.html.twig.

node is the entity type, and field-test is the field name.

If you want to know which template is generating a particular markup element, you can use Twig's debug option. You enable Twig debugging in sites/default/services.yml; set the value of debug in twig.config to true.

I have added the field_test field to the Article nodes, and I got the template suggestions in the HTML source.

<!-- FILE NAME SUGGESTIONS:
   * field--node--field-test--article.html.twig
   * field--node--field-test.html.twig
   * field--node--article.html.twig
   * field--field-test.html.twig
   * field--string.html.twig
   x field.html.twig
-->

After getting the suggestion, I created a template file and kept this in the templates directory of the theme.

Remember to clear the cache.

See Working With Twig Templates for more information.


How to hide particular field for specific role? I have Article page content type with field title,description,ad_article_top,video etc.
Also have one other role writer.writer can create article page content.

My issue is how to hide the ad_article_top field for writer role at the time he create content but if super admin create article page content the ad_article_top field not hidden

Give me some solution for solving this issue.

You can use Field Permissions module.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes.

  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.


How to import a 'Feature'? I have exported certain items with features module and have my *.tar file, where do I go in drupal to import this Feature in my destination site???

I found my answer.
Features creates a module that I need to import in the destination site.


Download library using Libraries CDN Does anyone knows how to programmatically download a library from https://cdnjs.com using Libraries CDN ?

@cilefen is correct: The purpose of the Libraries CDN API module is not downloading a library, but making the libraries found on a CDN available for your site; if then you are using the Libraries API module, it avoid the needs to download the libraries you need.

  Libraries CDN API is an API module to query CDN services to automatically provides libraries on your site.

  t also provides an integration with Libraries API. If your module depends on a library that needs to be downloaded and installed in sites/all/libraries and if this library is also hosted on a CDN, this module allows you to use the CDN version of the library very easily, without the need to download the library.


View is not showing all columns I configured a View showing all groups the user belongs to. I also added the name of the author and his/her role.
In the Preview of the View everything is OK, the same if Im logged as an admin (user1).
But if Im logged as an authenticated user, the view is not showing up the Role column.

Any ideas what can be wrong? Maybe some permissions, but which one?

I think, Role data is not displayed to users other than administrator.
Try with 'Field Permissions' module to edit the field specific permissions.


Add a login form to my module I want to add the login form to a custom page I've created using a custom module, but I dont know how?

Shouldn't there be a form to use like get_drupal_form?

Using Drupal 7.

Drupal comes with a login block you can put in any of your theme regions to have show up on that page.

Or you can use drupal_get_form('user_login') if you want it to show up in your content somewhere.


Move to Online Mode only one site of two multi sites sharing the same code base When I was working on one local site, I used to copy all the folders & files including the "sites" folder into my FTP account in addition to the database in order to have my local site online and be accessible by a specific domain name for example: www.FirstWebsite.com

However, Now I am using multi local sites (Two websites) on my laptop with separated databases, but sharing the same code base...
Which means the code base files for both websites are the same except the following folders which are specific for each website:
C:\DrupalSites\devdesktop\drupal-7.32\sites\FirstWebsite
C:\DrupalSites\devdesktop\drupal-7.32\sites\SecondWebsite

What are the files which I have to upload to my FTP Account in order for example to put only the website name: "Second Website" online ?!

Any help will be highly appreciated,,,
Thank you in advance...
             ---------------------------------------------------------------

Okay, i will rephrase my question...
if you are working locally on one site named "FirstWebsite" and you want to host it online by using one of the hosting server available like for example "HostGator.com", you have only to transfer to the cpanel/file manger all the files and folders of your website .
However, when you want to create LOCALLY another website, you should make a multisite configuration . Whichmeans, all the folders will be used by both websites except the two folders named: "FirstWebsite" (for the existing website) & the "SecondWebsite" (the new folder created for the new website) .
Okay, So let say now we want to host online ONLY the new  website whom all its files are under the "SecondWebsite" Folder without hosting also the existing website whom all its files are under the "FirstWebsite" Folder .
Note: Do not forget that both websites are sharing the same code base.

My question: What folders and files i should transfer to the cpanel/file manager to ONLY host online the new website  whom basically all its files are under the "SecondWebsite" Folder?

Thank you very much for trying to understand my problem even if it is not well explained...

if you mean "update" with "put online" then it is not possible, because - as you pointed out - all sites share the same code base.. updating the sites/all folder will update both. the database updates need to be performed separately.

if you have only one website online that you want to update then just upload the changes from the sites/all folder.. that updates themes and modules.

cheers,
j


How do I calculate the total of a shopping cart? I have the following cart implemented by a custom module I wrote.

The columns are stored in 2 associative arrays.

$jcartItemQty = $_POST['jcartItemQty'];
$jcartItemPrice = $_POST['jcartItemPrice'];

This is what those array could contain:

     [jcartItemQty] => Array
            (
                [0] => 3
                [1] => 1
            )

        [jcartItemName] => Array
            (
                [0] => Armas Jarnefelt - LAULAJAN KOTI
                [1] => Jean Sibelius - Kullervo
            )

        [jcartItemPrice] => Array
            (
                [0] => 110
                [1] => 120
            )

I need to combine somehow the arrays into one that looks like $combined = (3 => 110, 1 => 120) in order to be able to calculate the total.
array_merge() is not working because will only concatenate those 2 arrays.

foreach ($combined as $key => $item) {
  $total += $key * $item;
}

I need to display the total in a form item like this:

foreach ($jcartItemPrice as $key => $value) {
  $form['jcartItemPrice'][$key] = array(
    '#type' => 'textfield',
    '#value' => isset($value) ? $value : '',
  );
}

$form['total'][$key] = array(
  '#type' => 'textfield',
  '#value' => isset($value) ? $value : '',
);

Is there a way to do this?

You can use array_merge() to merge two arrays into one.

It looks like you're trying to overengineer things. This is a simple solution:

$combined = array();
for ($i = 0; $i < count($jcartItemQty); $i++) {
  $combined[] = array($jcartItemQty[$i], $jcartItemPrice[$i]);
}


How to create a menu for current book I want to create a menu that will be shown on the node if it is part of a book. For example like this:

That menu should be shown for all books, which means I don't want to have a separate block for each book in the system.

I am not interested in how to implement accordion functionality, I just need a way to get menu items for all book elements of current node.

Book module provides a block with books navigation, but I don't want all books to be visible in this menu.

I was surprised that I couldn't find a contrib module that does this out of the box so I created a simple one.

Here it is on Github too:
https://github.com/balsama/bookoblock (bookoblock = "Book Outline Block")

Info file (bookoblock.info):

name = Book Outline Block
description = "Provides a block containing an outline of the current book."
package = Other
core = 7.x
dependencies[] = book

Module File (bookoblock.module):

<?php
/**
 * Define the Book Outline Block/
 * Implementation of hook_block_info()
 */
function bookoblock_block_info() {
  $block['book_outline'] = array (
    'info' => 'Book Outline',
    'cache' => DRUPAL_CACHE_PER_PAGE,
  );
  return $block;
}

/**
 * Define the contents and title of the block/
 * Implementation of hook_block_view()
 *
 * Returns a renderable block array containing the current book's outline if
 * the node is part of a book.
 *
 * Returns NULL if the current menu item is not part of a book heirarchy.
 */
function bookoblock_block_view() {
  if ($book = bookoblock_is_book_node()) {
    $tree = menu_tree_all_data(book_menu_name($book['bid']));

    // If we pass 1 as the second param, we just get the top level node in the
    // book. Since the key will be the top level mlid, we'll have to use
    // ['p1'] in the $book array (which contains the top mlid) when we use it
    // for the block title.
    $book_name = (book_toc($book['bid'], 1));

    // Build the block title and contents
    $block['subject'] = $book_name[$book['p1']];
    $block['content'] = menu_tree_output($tree);

    // Return the block
    return $block;
  }
  // If the current node isn't part of a book, just return nothing.
  return NULL;
}

/**
 * Checks to see if current node is part of a book.
 * Returns book array if it is part of a book, FALSE is not.
 */
function bookoblock_is_book_node() {
  if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
    $node = menu_get_object();
    if (isset($node->book)) {
      return $node->book;
    }
  }
  return FALSE;
}

Just drop those two files into a folder named bookoblock inside your modules directory and enable the module. You'll now see a new block in the block admin page named Book Outline. That block will only appear on node pages where the node is part of a book. It contains a heierarchical menu of the entire book and it's title is the root node's title.


Form in custom module using Controller: The HTML tag form isn't present in Twig I'm trying to render limited user edit form on custom page using Drupal Controller.
In the routing.yml I defined _controller, I do not want to use _form.
I want to display on the form e.g. only timezone field, but not the rest. And I'm not able to achieve it. I can render this field, other fields like form_build_id, form_id, form_token
But form html tag is not rendered at all.
It works only if I display the whole form with {{ form.form }}.
This is the content of the files I am using.
my_module.info.yml
name: 'My module'
type: module
description: 'my module'
core_version_requirement: ^8.8 || ^9

my_module.routing.yml
my_module.mymodule_controller_view::
  path: '/my-module'
  defaults:
    _controller: '\Drupal\my_module\Controller\MymoduleController::view'
    _title: 'My module'
  requirements:
    _permission: 'access content'

my_module.module
function my_module_theme($existing, $type, $theme, $path)
{
    $templates = array(
        'my_module_form' => [
            'render element' => 'form',
        ],
    );

    return $templates;
}

MymoduleController.php
namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;

class MymoduleController extends ControllerBase
{

    public function view()
    {
        $data['header'] = [
            '#type' => 'markup',
            '#markup' => '
HEADER
',
        ];

        $user = User::load(\Drupal::currentUser()->id());
        $formObject = \Drupal::entityTypeManager()
            ->getFormObject('user', 'default')
            ->setEntity($user);

        $form = \Drupal::formBuilder()->getForm($formObject);

        $data['form'] = [
            '#theme' => 'my_module_form',
            'form' => $form,
        ];

        $data['footer'] = [
            '#type' => 'markup',
            '#markup' => '
footer
',
        ];

        return $data;
    }
}

my-module-form.html.twig

TWIG TEMPLATE

{{ form.form.timezone }}
{{ form.form.form_build_id }}
{{ form.form.form_token }}
{{ form.form.form_id }}
{{ form.form.actions }}

This is not working, you can't use a form template in a controller. You have to assign the template to $form['#theme'] when building the form or in a form alter hook. Then it gets used by formBuilder()->getForm() automatically.
See for example seven_form_node_form_alter():
$form['#theme'] = ['node_edit_form'];

and the corresponding twig file for a two column layout:
core/themes/seven/templates/node-edit-form.html.twig
{#
/**
 * @file
 * Theme override for a node edit form.
 *
 * Two column template for the node add/edit form.
 *
 * This template will be used when a node edit form specifies 'node_edit_form'
 * as its #theme callback.  Otherwise, by default, node add/edit forms will be
 * themed by form.html.twig.
 *
 * Available variables:
 * - form: The node add/edit form.
 *
 * @see seven_form_node_form_alter()
 */
#}

    {{ form|without('advanced', 'footer', 'actions') }}

    {{ form.advanced }}

      {{ form.footer }}
      {{ form.actions }}

Form modes
A different approach would be to configure a form mode in UI containing only the field you want and then use it in your controller:
    $formObject = \Drupal::entityTypeManager()
        ->getFormObject('user', 'custom_form_mode')
        ->setEntity($user);

See How do I load a form with a specific form display (form mode)?


How to print out bootstrap menu? I am using the Bootstrap module. In the code I can see this:

<?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>
      <div class="navbar-collapse collapse">
            <nav role="navigation">
                <?php if (!empty($primary_nav)): ?>
                    <?php print render($primary_nav); ?>
                <?php endif; ?>
                <?php if (!empty($secondary_nav)): ?>
                    <?php print render($secondary_nav); ?>
                <?php endif; ?>
                <?php if (!empty($page['navigation'])): ?>
                    <?php print render($page['navigation']); ?>
                <?php endif; ?>
            </nav>
        </div>
    <?php endif; ?>

The problem is, I can't get it to print it for any other menu. For example, i created a menu called "web design menu". I am able to make it appear as follows:

print drupal_render(menu_tree_output(menu_tree_all_data('menu-web-design-menu')));

However, this doesn't give it the styling of bootstrap or any of the nice bootstrap benefits. How do I render it so that it renders it the same way the above code does. I.e. with all the correct bootstrap styling and executed javascript etc.

In the boostrap theme there is a file

  theme/menu/menu-tree.func.php

This file contains a function

  bootstrap_menu_tree__primary

This function wraps the menu as following:

'
' . $variables['tree'] . '
';

So you have to give the wrapper of your menu those classes and make sure the structure is exactly the same as the primary menu.

Hope this helps you out.


combining two taxonomy fields into one exposed filter dropdown I have created two taxonomy fields (home team and away team) with a content type.

I have created a views to display the list content of content type. In view, I have added taxonomy filter for home team and away team which is showing two taxonomy filter in the views page.

I would like to combine both taxonomy filter into single exposed filter.

You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter for taxonomy for 'home' and 'away'
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter "Home taxonomy" and "Away taxonomy" in new filter group.
Select Operator as "Or" in new filter group and save the form.


Drupal 7 - create own login form Is it possible to create own login form? I need to insert it into my basic page. It is campaign for my client and he wants to be able login from specific basic page. I have tried to use block from classic login, but without success. But it still has many things around (like remember me etc..), and I need only basic username/password

thanks for any help

You should be able to just retrieve the form and print it on your node template. In your theme's template.php (a custom module would work too):

function MYTHEME_preprocess_node(&$variables) {
    if ($variables['view_mode'] == 'full' && $variables['nid'] == 9 && user_is_anonymous()) {
        $variables['login_form'] = drupal_get_form('user_login');
    }
}

And then in either your theme's node.tpl.php or a specific node template if you're using one:

<?php if (isset($login_form)): ?>
  <?php print render($login_form); ?>
<?php endif; ?>

This will just print the same form you'd find at /user/login wherever you want it. Just make sure to replace the 9 with your node's nid.


webform telephone field validation fails I am using webform-8.x-5.0 and created a telephone field with international phone numbers support. Before submitting the form if i enter some number like "+91fdfgdfg45646" it shows "Invalid phone number" (which i am not sure if it is a valid number or not). But when I submit the form it gets submitted. The issue is if it is invalid, the form should not have been submitted. Please suggest a solution. The form should not be submitted if it is invalid number.

Thanks in advance

Image for reference:

The international phone number element is only a client-side enhancement which is using the International Telephone Input library.

To validate the phone number via server-side validation you would need write custom code and to use a PHP library like https://github.com/giggsey/libphonenumber-for-php


Alphabetical case insensitive grouping of results My question is about grouping results alphabetically in a case insensitive way in Drupal 8. I have a view displaying people's names alphabetically grouped by last name. My problem is the following: I have some people with last name that starts with upper case D and other whose last name starts with lower case d (Example: de XXX). Right now the upper case D and the lower case d are grouped separately. I need to be able to group them together.

To group all of your results by Last initial, capitalized:
First, under Format > Settings > Grouping field X, make sure you check the box to "Use rendered output to group rows".
Second, update the field settings for the field you're using to group the results - under Rewrite Results, check "Trim this field to a maximum number of characters," and enter 1 for the length.
Finally, again under Rewrite Results, check the box to "Override the output of this field with custom text". You can use twig in the custom text field and leverage twig's upper filter to convert the entire string to uppercase. You'll have to check the Replacement Patterns for the correct field name to use in your case, but the end result should look something like:
{{ field_last_name|upper }}

The result is your view results grouped by last initial, capitalized (whether they actually start with a capital letter or not).


How do I do per-item shipping based on the number of products? I'm doing a favor for a family member by helping set up their store. I've never worked with Drupal before.

They are selling one item, but they want the shipping cost per item to change based on the number of items purchased.

1 item - $3.50 shipping
2 to 9 items - $2.75 shipping PER ITEM
more than 10 items - $2.00 shipping PER ITEM

After a few hours of research I half-understand the rules system, but I can't figure out how to combine rules like this. Can anyone point me in the right direction?

Pontus Nilsson has the right idea, just shared it as a comment instead of an answer?

I decided this was a good teachable moment (this also turned out to be a head scratcher at more than one turn), so below is the screencast of how to do this and a step-by-step:

https://www.youtube.com/watch?v=trLydGpimD4

STEP BY STEP

Install https://www.drupal.org/project/commerce_shipping and https://www.drupal.org/project/commerce_flat_rate
Create three different flat rates (I recommend you keep the "Title" different, but change the "Display Title" to be the same, so the rate change is transparent to the user)
Configure each flat rate component to have a condition on "Total product quantity comparison" so that only the appropriate rates show up based on number of products. Note this will only work if you use the standard line item type "Product" ... if you have custom line item types, you will have to create a component that does the comparison/counting that you need.
In order to count the number of eligible products, we will need to create a component rule that has a "line item" parameter and has an "number decimal" provided called "is_a_product".

This component simply needs to have a condition on entity bundle for "Product" and needs an action that "sets a data value" ... the is_a_product ... to the line-item:quantity.

Next, we will need to create a pricing rule for your first "Medium" level shipping price calculation.

A. Once you discover where to create the shipping price calculation rule you will need to create two conditions:

Entity has field (it should have the shipping service field)
Data Comparison (the shipping service field should equal the medium shipping service)

B. Now you will need to count the number of products. Let's add an action "create a variable" for an number decimal called "num_products"

C. Next you will need to loop over all the line items in the order.

D. Next you will add an action for the component you created in step 4.

E. Then you will need to "Calculate a value" by adding the "num_products" and the "is_a_product" (through some testing I confirmed the integer is zero by default) and then save the result by "setting a data value" and setting "num_products" to the result value

F. Finally, you will need to "Multiply the unit price by some amount" and select the num_products as the multiplier
Repeat step 5 for each breakdown of product quantity rate change


Display the total weight of the order in the basket I installed the module https://www.drupal.org/project/physical in my cart view, I'd see the total weight of the order. How to do this ?

You need to add weight as a field to the product entity type first. Then you can see. Then you need to install this module, make a view and calculate the total.

Hope that helps.


Restrict access to text formats for certain role For every user with role company manager i have made tab My company(in user profile) where user can see node_edit of their company(node). And i need to set default format to plain-text and hide text-format drop down list only for this role. Ofc. i can do this for every user, i can change settings in my content type field settings, but this way the other users will not see it too.

Any suggestions? how can i achieve this?

Alternatively, you can use the Better Formats module, it gives a lot of possibilities to you to control text format selection.


How can I display a list of users who have the same taxonomy term The setup:

A Taxonomy Vocabulary called "Area of work".

The vocabulary has the following associated terms: A, B, C, D, E, F, G, etc.

During registration users have to choose a department from the taxonomy list to associate themselves with.

The challenge:

I would like to create a single page view or multiple page views if necessary that displays the users that work in each department.

Another requirement is to display each list of users page using the following the path pattern: people/staff/A/, people/staff/B/...

Current status:

So far, I have managed to create a generic list with all users that have selected one of the departments in the following path: people/staff, but I can't figure out how to display single lists for each department.

Any help will be much appreciated!

First of all, thank you very much to @leymannx, @GiorgosK and @prkos, because without the three contributions I wouldn't have achieved the desired result.

These are the steps I have followed to display a list of users who have the same taxonomy term in a page with a specific path pattern: people/staff/A/, people/staff/B/...

As @leymannx initially suggested, in my view a wildcard in the path was missing. So, instead of people/staff/, I have changed it to people/staff/%
As @GiorgosK illustrated with his screenshot, I have included a Relationship field_staff_area: Taxonomy term, and then a Contextual filter on Taxonomy term: Name using this relationship.
Finally, as @prkos precisely described, to show the actual term name in the URL I also needed to configure the Contextual as follows:

a. When the filter value is NOT in the URL: Select the option Display all results for the specified field

b. When the filter value IS in the URL or a default is provided: Select the option Specify validation criteria. Then, select Taxonomy term name in the dropdown, and, finally, check the vocabulary we intend to use (Areas in my case).


Drush field-clone with specified label The following command clones the field with the same label.

drush field-clone field_tags newtags

As you see, the cloned field has the same title Tags.

So how can I clone the existing field with desired label?

Based on the help for this command I'd say it is not possible:

$ drush help field-clone
Clone a field and all its instances.

Examples:
 field-clone tags labels                   Copy 'tags' field into a new field 'labels' field which has same
                                           instances.
 open `field-clone tags labels`            Clone field and then open field edit forms for refinement.

Arguments:
 source_field_name                         Name of field that will be cloned
 target_field_name                         Name of new, cloned field.

Edit: This GitHub issue can confirm it.

But you can always go to Manage Fields, edit the new field and change its name.


How to remove blocks as a Context reaction? I must be missing something here, I hope someone can shed some light on this, but I can't see how to remove blocks when using the Context Reaction - Blocks on the context configuration screen.

I can add blocks using the checkboxes and the add buttons, and I can remove them once added but how do you remove blocks that are already being rendered?

thanks

Jack

@jack, you can't remove blocks that are already being rendered, but you can show them only on specific pages, which will effectively do what you need.

For example, I had a footer contact form which I want to show on all pages on the site except on the contact page. I used the following steps:

Added a new context called "except_contact".
On the new context editing screen, added a path condition with the path negation operator, "~" (which is specific to contexts):  "~contact/info" will activate the context in all paths except contact/info.
Added the global contact block to the footer region.

This does what you need - show the block in all pages except the designated page where the block is effectively removed.


Create User Picture Field I accidantly deleted the user picture field while development. Now the app is production and a new feature should provide user pictures.

How do I get back the user picture field?

You'll find the configuration files of the user picture field in the standard profile. You can export the complete config, add the yaml files of the field and reimport again.

Or if you want to import the field in UI, go to admin/config/development/configuration/single/import, select the configuration type Field storage and import the content of

core/profiles/standard/config/install/field.storage.user.user_picture.yml

The same for the configuration type Field and the content of

core/profiles/standard/config/install/field.field.user.user.user_picture.yml.


Problem in rendering double-field in other node I think I have a problem with keys and values of a list field in the rendering phase (on Drupal 7).

Let's me go in detail.

Model part:

We defined a CCK "double field" for a "profile2", with multiple values allowed.
This field is composed by a select and a text-field, but I'm interested only to the "select" part in this moment (its behavior seems to be the same of a simple list field).
Then we defined values in the list as K1|V1, K2|V2, etc.

Render part:

We defined a theme template for this field; there we verifies values by comparing the key: $val = $item['first'] (to take it) and if ($val=="K1") {...}... and everithing works fine, because tamplate receives keys of the list (inside first key of the #object array of the renderable array).
In a node page I have to show the same information and I would like to use the same template file (instead of replicate the code). So I tried to use render( ) Drupal function, and it needs for a renderable array... but the only function I found to get it was field_view_field( )... and it doesn't work as I expect.

The problem is that this function doesn't return field keys (e.g. K1), but values (e.g. V1)... so templates is not able to work properly.

I know I can write differently my template (e.g. if ($val=="K1" || $val=="V1"), but I think this is can't be the right solution, because code should alway depend from keys (and not values, that may change over time).

So I'm wondering what is the Drupal way to achieve a renderable array in which there is the keys and not the values of a list element.

Thank you

Try to change format for that field in 'Manage display' in back-office. 'key' option should be there. This option available for select list, but for "double field" try to set "unformatted list", style "simple", and text format "-none-".


Drupal 7 ajax callback never ends I'm trying to do an ajax callback on page every load with drupal to get some info. The problem is that when the ajax callback is done and the data processed, Drupal continues calling the ajax function once and over again adding the typical "Please wait..." text repeatedly.

The javascript:

(function($){

  Drupal.behaviors.myModule = {
    attach: function () {
      var settings = {};
      settings.url = '/my_module_ajax_callback';
      settings.event = 'onload';
      settings.keypress = false;
      settings.prevent = false;

      var base = 'myModule';
      var ajax = new Drupal.ajax(null, $(document.body), settings);
      Drupal.ajax[base] = ajax;

      $(ajax.element).trigger('onload');
    }
  }

})(jQuery);

The php:

<?php

function my_module_init() {
  drupal_add_library('system', 'drupal.ajax');
}

function my_module_menu() {
  $items['my_module_ajax_callback'] = array(
    'page callback' => 'my_module_ajax_callback',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function my_module_block_info() {
  $blocks['my_module_block'] = array(
    'info' => t('My Module Block'),
  );
  return $blocks;
}

function my_module_block_view() {
  $block = array();

  $block['content'] = '
This data must be replaced by ajax
';

  return $block;
}

function my_module_ajax_callback() {

  $commands[] = ajax_command_replace('#my_div', '
This data has been replaced by ajax
');

  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);
}

Seems the ajax callback is never complete.

In misc/ajax.js:

complete: function (response, status) {
  ajax.ajaxing = false;
  if (status == 'error' || status == 'parsererror') {
    return ajax.error(response, ajax.url);
  }
},

I don't know what I'm doing wrong. I really appreciate your help. Thanks.

I've found a solution myself. Seems after the ajax callback the attach function is called again, so I surrounded by a jQuery .once() method:

(function($){

  Drupal.behaviors.myModule = {
    attach: function (context, settings) {

      $('#my_div', context).once('my_div', function () {
        var elem_settings = {};
        elem_settings.url = '/my_module_ajax_callback';
        elem_settings.event = 'load';
        elem_settings.keypress = false;
        elem_settings.prevent = false;

        var base = 'myModule';
        var ajax = new Drupal.ajax(base, this, elem_settings);
        Drupal.ajax[base] = ajax;

        $(this).trigger('load');
      });
    }
  }

})(jQuery);

This prevents calling the ajax once and over again.

https://drupal.org/node/756722#jquery-once

https://drupal.org/node/2192041


Upgrade Status module reports PHPUnit\Framework\TestCase is not an interface Our site is running Drupal 8.8.13 and we want to move to Drupal 9. I've installed the Upgrade Status module v3.3. When I scan a module, like Admin Toolbar, it reports the problem:
web/modules/contrib/admin_toolbar/admin_toolbar_search/admin_toolbar_search.module

Internal error: PHPUnit\Framework\TestCase is not an interface
Run PHPStan with --debug option and post the stack trace to:
https://github.com/phpstan/phpstan/issues/new?template=Bug_report.md

Lots of other modules have the same problem.
Is this warning legit? or is there a problem with the configuration of Upgrade Status module?

Are you using the latest versions?
Upgrade Status recently released a new version (3.3) a couple days ago, and it seems something is wrong with PHPStan.
Testing on Drupal 8.9.13 with Upgrade Status 3.3 and Admin Toolbar 3.0, after scanning Admin Toolbar, I get only this issue:
web/PHPStan failed  0   PHP API deprecations cannot be checked. Reason: Array ( )

Which is linked to the bug report listed above.
In any case, regarding your error, if you go to the Admin Toolbar module page on drupal.org, you'll see that both the 3.x and 2.x versions are marked as compatible with Drupal 9.
In general, it's safe to trust modules that say they are compatible with Drupal 9 on their module pages whose most recent release is after the release of Drupal 9.0 (June 3, 2020).  Maintainers of some modules that were last updated earlier in 2020 marked their modules as compatible with Drupal 9 while it was still in alpha or beta, and then Drupal 9 changed before the release, breaking compatibility with those modules.


Setting up local dev, "call to undefined function" from a module that I uninstalled a few months ago I'm attempting to set up Acquia Dev Desktop with a database dump and git repo from Pantheon.

I was using the Computed Field module in this project but I rewrote the code in my own custom module and uninstalled Computed Field a couple months ago (uninstall from modules page and removal from my git repo afterwards).  I had no errors on the Pantheon site related to this, and I just made the db and code dump yesterday.

However, when I import into Dev Desktop, I'm getting the following error:

  Call to undefined function computed_field_entity_property_callback()
  in
  /Users/pk/dev/mysite/sites/all/modules/contrib/entity/modules/field.info.inc
  on line 30

computed_field_entity_property_callback() is a function defined in the Computed Field module, which shouldn't exist on my site anymore.  So somehow there is a "ghost" left in my db somewhere-- how can I locate where this error comes from, because I can't even get a page to load-- all I'm getting is this error.

Most of the time this a cache problem.

First try to clear the cache via Drupal (Clear cache button). Or use Drush (drush cc all).
You can clear the cache tables by truncating them. Check all the tables with cache_ prefix.
If #1 and #2 didn't fix the problem then check if you have Memcache or similar installed. Flush the cache as well.
Another thing could be APC or similar opcode cache.


Payment method to cart page I need to move the payment method from the checkout page in drupal commerce and embed it into the cart page. is that even possible? I have been finding some resources and it does not lead me anywhere.

I believe I will need a custom module for this and which hook should I used for presenting a payment option in the cart page and when hitting 'checkout' button it will just go and review everything. so payment is processed in the cart page also.

thank you

It's actually very straight forward! If you want to not completely override the /cart url (basically, leaving the /cart in tact, but simply link key user interface elements directly to checkout) then you can skip to step 2...

Step 1: Overriding the cart view

You will want to do three things:

First, you'll want to "alias" the "/cart" to "/checkout" (see screenshot above) ... this will ensure all system links that go to cart actually just link to "/checkout"
Second, you'll want to override the system path "/cart" and have it redirect to an appropriate location. (code below)
Finally, you'll need to disable the view "Shopping cart form" (otherwise our hook_menu_alter may not work).

See verified code below (as in I checked to make sure this works).

<?php
function mymodule_menu_alter(&$items) {
  $items['cart']['page callback'] = '_mymodule_redirectcart';
}
function _mymodule_redirectcart() {
  global $user;
  $account = $user;
  $cart = commerce_cart_order_load($account->uid);

  // if user doesn't have a cart, go to <front>
  // else if user's cart is empty
  if ($cart == false || count($cart->commerce_line_items) == 0) {
    drupal_goto('<front>');
  }

  // go to checkout
  drupal_goto('checkout/'.$cart->order_id);
}
?>

Don't forget to disable the shopping cart form

Step 2: Making a one page checkout

I borrowed the step-by-step from an excellent "Express Checkout" blog.

From http://www.example.com/admin, click on the Store link, then Configuration, then Checkout settings
Drag the Review item out of the Review order section and into the disabled section
Drag the Payment item out of the Review order section and up into the Checkout section
Click Save Configuration

Step 3: Modify the title and button

This step is optional, but useful. Basically, we just use hook_form_alter to change the "Continue" button to indicate that payment will be taken and we modify the page title to "Cart" to further our ruse that this is the cart page and not checkout.

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    drupal_set_title("Cart");
    $form['buttons']['continue']['#value'] = t('Proceed with purchase');
  }
}
?>

Step 4: Your new cart checkout

This is not really a step, but it is the result of your effort. Now your new "cart" has a checkout/payment pane. Only thing you would be missing from the original cart is the ability to modify your cart (remove products) and that is where this process would fail you.

Other Thoughts

If your customers will need to be able to modify the cart (most likely the case), then you will need to link to a clone of the commerce_cart_view at a unique url (perhaps /cart-edit?) and then add a link called "Edit Cart Contents" in the footer of your cart contents view to indicate that they can remove items, but they have to click a link to do it.

The view you want to clone is called "Shopping cart form" and the clone option can be found at /admin/structure/views
Make sure you edit the path in your cloned view to "cart-edit" or some variation.
Edit the footer of the "Shopping Cart Summary" view found at /admin/structure/views/view/commerce_cart_summary/edit to look like the below:

The reason you can't modify cart items in checkout is that "forms within forms" is not a straightforward thing to implement, but linking to a view to edit your order is pretty simple and everyone wins with a 10 minute change.


Theoretical limits of CCK (Field API) unlimited Multi Value Field - 170 000 values I plan to have a large multi value field, in my case a node reference field, around 170 000 values.

I guess on node view I can hide the field, and just put in a Views block so the node can be viewed. Editing the node manually will be impossible, as the multi value fields have no paging and Drupal would just load the entire 170 000 values onto the screen. Any tips on solving this?

What I plan on having this is a content type "list" and a content type "item". In the items I will load an dictionary word lists, and in the "list" content type I will group them in different lists. I could use taxonomy as well, but nodes have a better permission control.

No chance, hiding doesn't help, drupal will still load all values even if the field is hidden.

You could add the reference field on the item type and then load them through a view.

Or use the relation project, but it's ui might break too.


Best way to place hard coded link in template in multi lingual drupal 8 My website (drupal 8) was first in one language. Now I switched to multi langual.

Most of the settings i did find (translate content, webforms, strings,...).

But at the moment stuck on the hard coded links I use in the template (theming).

So I'm looking for the best way to let my hard coded links work for more languages.

At this moment this is what i got (and ofcourse this is not working well):

{{ 'DIENSTEN ON SITE'|t }}

This link doesn't bring the visitor to the correct link (en/ or fr/ is missing). Translate on the string works already :).

My current settings for detections are visible in the image:

Thanks for reading!

Kristof

For translated links you can use the path function

 {{ 'DIENSTEN ON SITE'|t }}


Populate node image field with files submitted by webform? Just wondering if this can be done in any way.

I have a block webform which is shown in a give node, let call this node Page-1.

The Page-1 node has a multivalue image field.

You can attach files to the webform (using https://www.drupal.org/project/webform_multiple_file).

Now let's say I submit the webform with 3 images attached, then my question: is there any way to populate the image field of the Page-1 node with those images?

Any issues with using: hook_webform_submission_insert and copy these images to current viewing node?

If node ID isn't available in webform submission, you can always put hidden field to webform with a NID.


Render View with title in twig template? Is there a version of drupal_view (or alternative) that will render a view with the title? It's a pain to hardcode titles or preprocess individual views just to get a title to render that is already configured per display from the views interface.

You should develop a custom twig extension for that.
I developed a simple module twig_views for that purpose check it out.

Example of use:

 {{ render_view('view_machine_name', 'display_name') }}

if you use 8.2.6 drupal version, and twig_xdebug Module
you may have some error like:

  The website encountered an unexpected error. Please try again later.
  Symfony\Component\DependencyInjection\Exception\LogicException: Service 'twig_xdebug' for consumer 'twig' does not implement Twig_ExtensionInterface.

Those steps in this comment will solve your problem.


How to submit a field collection from a form into a created node I would really appreciate if somebody could help me with this :)

I have a field collection called field_formations. Inside it I have 2 fields:

field_technologies - (reference to a taxonomy).
field_diploma -(how it's also a field collection which contain 2 other   fields:
field_name(reference to a taxonomy)
field_establishement (text plain)
               ).

I've created a form with 3 field forms
technology
diplome_name
establishement

and into the submit form i would like to submit values of this forms into  the node created at first.

I tried to setValues like this :

$node->field_formations->field_technologies->setValue($values['technology']);

but it dosen't work
Can any body have a suggetion??

PS : I'm using drupal 8

You need the id of the field collection item (grand one) which you can find inside the node object. Then you load the field collection by that id as an entity. Edit this field collection and save it as an entity. The point is that you have to load the field collectin entity, make changes and save it.


Default installation of D8 treatment of .gif accesses? If I request a non-existent URL, say, /ddddd I get Page not found (as expected). If I do th4 same with an unusual extension /dddd.xcf I also get Page not found.

BUT if I request /ddddd.gif there's an Apache error as opposed to a 404?

I'm guessing this has something to do with security, but can someone clarify this?

By default drupal serves a different 404 page to save computational effort if it  is matching the following regex:

'/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'

You can configure this in the settings.php (Fast 404 pages) or in the config('system.performance')->get('fast_404.paths');


Storage API stream wrappers Traffic Usage In my Drupal 7 Project I have configured Storage API stream wrappers in order to save all public and private files over ftp server.

everything works well and files in public and private are copied into ftp server correctly.

Imagine that my base server is domain.com and my ftp server is ftp.com

As you know, public files will be shown with direct link to the source for example

http://ftpdomain.com/public-file.png

and private files are not shown with direct links for example

http://domain.com/system/storage/serve/private-file.rar

Now my question is: when a user try to download private-file.rar via above link, what happens really?
is private file from ftp server being copied to the main server temp folder at first and then download starts?
Or private-file.rar is downloaded directly from ftp server to the client machine despite the URL starts with "http://domain.com/.... "

It is very important for me because of shared server rules in file download limitations , I have to purchase one PHP host for running Drupal script and one download host for placing files folder in order to run a Drupal project commerce file shop.

I want to be sure, download traffic only relate to download server not PHP server.

Thanks a lot for your guidance.

If you look into the Drupal core's routing config, you can find the controller responsible for delivering private files. It's abstracted through the BinaryFileResponse object, but you can see in its sendContent method how the data is prepared for delivery.

It uses PHP's stream_copy_to_stream function to copy from your input stream (your private path) to the php://output stream, the HTTP body delivered via PHP/web server.


Is there any module for importing news from a WordPress site? When we install Drupal, the first thing we do is importing content from other engines that we used.

Is there any kind of similar converters from other engines, for posts, user accounts, and comments?

For Drupal 7 try WordPress Migrate:

  wordpress_migrate supports migrating WordPress blog exports (WXR
  format) into Drupal using the Migrate module. Import of posts, pages,
  comments, attachments, tags and categories is supported. Imports can
  be rolled back completely.

and Wordpress Import if you are using Drupal 6:

  This module imports a WordPress blog into Drupal from a WordPress
  eXtended RSS (WXR) file.


Getting the nodequeue id from the nodequeue name? I want to get the nodequeue qid from the nodequeue  name.

Suppose I have a node queue with the name of "Slider". I want a function so that I pass it the name of the nodequeue and It returns the qid or sqid of that nodequeue.

Is it possible?

There is a function of the same name as in the excepted answer included in current versions of the nodequeue module.

$queue = nodequeue_load_queue_by_name($name);

It returns the queue definition, or an empty array if no queue was found with the given machine name. So the id would be found at:

$queue->qid;


Which module to use for tracking pages browsed by users? My requirement are:

most viewed pages
most 404
most 403
most referring pages
most visitors

In addition provides charts and HTML table view for those data.

Could someone give me any advice?

The best tracking out there is google analytics and its not a module. You simply add the javascript provided by google to every page in your site and access all the info and much much more on google's analytic dashboard.

To add the javascript provided by google to your site other check the drupal module Google Analytics or add it yourself through a template file or drupal's add js function


Drush command to delete content going out of memeory. What can I do? I have implemented drush hooks to build a drush command that deletes a lot of legacy nodes. It basically does a node_delete on a lot of nodes in a loop. However, I have the memory limit set to ~380MiB in settings.php and when I run the command to delete large number of nodes, say 100 000, drush terminates abnormally with an error indicating that it ran out of memeory. This happens by the time it deletes 20000 nodes. I have looked around and checked the definition of node_delete. In the definition there is a comment about the possibility of going out of memory.

I tried unsetting variables, and I tried doing node_load(NULL,NULL,TRUE)-- as suggested one drupaler on this forum-- hoping to release some memory every number of iterations but this did not work. So is there anything I can do? I am trying to avoid breaking it into chunks for ease of release.

If you look at the code for node_delete_multiple() it does a node_load_multiple().  While this seems strange, it has to do this so that it can invoke all of the proper hooks so that other modules have the full $node object in order to do their thing (eg, delete the attached field data).

Because Drupal uses aggressive static caching to avoid redundant database accesses, memory usage can swell.  This can't be freed or disabled.  If this becomes an issue, you can do temp edits to the EntityControllers to comment out the static caches.  You could also make a temp edit to drupal_static() to effectively disable it.

I would come up with a good EntityFieldQuery to get the list of nodes to delete.  This will just give you back the nids.

Suck out the nids, and trim the array to some limit.

Call node_delete_multiple() on the result.

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', $bundle)
  ->addCondition(...)
  ->execute();

$nids = array_slice($entities['node'], 0, 1000);

print 'Deleting ' . count($nids) . ' nodes ... ';

if (!empty($nids)) {
  node_delete_multiple($nids);
}

print "done\n";

Put this in a standalone PHP and execute is from drush, eg

drush -u 1 scr nuke_everything.php

Run it until everything is gone.

The above solution is for Drupal 7, but the approach is essentially the same for Drupal 6.  You would do a db_query() to get the nids, and then loop through and call node_delete() on each.  However, Drupal 6 also does a full node_load(), too.  In this instance, it does bypass its static cache, but this doesn't mean that modules aren't also doing any static caching.  For Drupal 6, you would need to chase all of the possible hook_nodeapi('delete') and look for static caching and static caching in any functions that get called, and do temp edits.


Can a subgroup of a public group be private and hidden? I'm building my first Drupal Organic Groups site, and running into problems.
Problem:
My goal is to have top-level Groups that are visible to the public, but only members can participate in them. There will be public subgroups too. Additionally, there must be invisible private groups that only members can see. All non-members, even logged-in site users, should not even see the group exists.
Since OG doesn't support sub-groups in the core and the OG subgroups module is an alpha release,  I tried making my own sub-group solution. (see description below)
A browser session not logged into the site does not show the private subgroup, as needed. However, a logged in user who is not a member of the group can see, not only the group name, but the member list and description (body field). The content is successfully hidden, stating "There is no content in this group."
Does OG support what I am trying to accomplish?
I have read these and other pages:

https://drupal.org/node/2014987
How to make a OG private?

My configuration matches what is shown on those two references.
(See screen captures below)
System and method description:
Fresh install of Drupal 7.26 and OG 7.x-2.5.
I created a new content type called "Subgroup" and assigned it all the OG fields (group_access, og_roles_permissions, group_register, group_content_access, group_theme), and marked both "Group" and "Group Content" in the Organic Groups tab in the Content Type creation form. The Subgroup content type also has an Entity Reference field type named "Parent Group." That is set to Target type "node"; Entity Selection -> Mode = Organic Groups; Target Bundles = Group; no sorting; OG membership type = default.  "OG behavior" is checked under "Additional Behaviors.
To test, I created a Subgroup node titled "Drupal theming (PRIVATE)", with both Group Visibility and Group Content Visibility set to "Private - accessible only to group members". Other OG settings were: "Override default roles and permissions" (since my site OG default is to be public) and "Do not show on registration page." The site is using the default OG Node template panel for Groups.
I verified that the "non-member" role of the private subgroup has no permissions boxes checked in Subgroup > Group tab > Permissions panel.
In case it may be a clue, whenever I try to save an update to a Subgroup content type node, the system displays this error:

Notice: Undefined index: field_mode in OgBehaviorHandler->validate()
(line 254 of
/my/domain/path/sites/all/modules/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php).

I recently experienced this same "Undefined index: field_mode in OgBehaviorHandler..." error when trying to set the og_group_ref field widget to select list. It appears that it doesn't work if it's not set to "OG Reference". In the "Additional behaviors" field, you can set it to select there, but the widget needs to be left as the default value. Try that and see if it's of any help.


entity_reference field widget as select instead of autocomplete Is there a select widget I can use instead of autocomplete for referencing entities? Right now I am using this in my baseFieldDefinitions function:

->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
  ))

but I need to have a select widget instead. Any ideas?

I was able to change the widget from the field config page. The key used by drupal was options_select, so I updated the type to:

'type' => 'options_select'


How to set a taxonomy term programmatically for a node? I created taxonomy terms and assigned it to a content type 'Article' using term reference field. I created nodes by programmatically but how to set taxonomy terms for the nodes?

The taxonomy terms are created already. I want to set the taxonomy term for a node programmatically.

Use this function to get ID from Termname

function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
   else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}


How to handle complex redirection requirement? I have a content type defined with a field storing the URL for accessing an external web resource and am looking for a way to have my Drupal 7 instance manage the redirection to this external site based on the nid contained in the incoming request path (ie. mysite.com/resource/123 redirects to the location stored in field_data_field_url where nid = 123).

The driver for this requirement is that our partner sites need to publish links to these resources that will not be subject to change. Drupal will house the database of resources and I am hoping to provide an endpoint that handles the redirect without further action from the user.

I have begun exploring the Services module in attempting to solve this problem but am not making headway in figuring out how to ultimately perform a redirection. I would appreciate input on whether this is an appropriate case for this web service approach or should I be looking at another way to tackle this problem within the Drupal framework?

You could use Services, you dont have to.

1) To have remote resources you need to create a url in drupal to consume data sent to it (Services can indeed do this). eg, mysite.com/secret/submit-a-resource-location. You could make this in a custom module with hook_menu, it could store values in a table with NID, and RESOURCE_URL as the columns.

2) If you goto some path on your site like mysite.com/passthrough/NID you could look at the NID passed in and in the hook_menu page_callback function and use drupal_goto to go to your remote url.

Eg:

function mymodule_menu() {
  $items['secret/submit-a-resource-location'] = array ( /* ... */ );
  $items['passthrough/%'] = array( /* ... */ );
  return $items;
}

function mymodule_passthrough_page_content($arg) {
  $result = db_query("SELECT resource_url FROM {external_resources} er WHERE er.nid = :nid", array(':nid' => $arg))->fetchCol();
  drupal_goto($result['resource_url'], 302);
  // implicit exit here by drupal goto.
}


"Is all of" view search doesn't work with the module "Better exposed filter" Drupal version :  8.2.0
Module "Better exposed filter" version :
8.x-3.0-alpha1

In short :

I created a view with an exposed filter. When I use the operator "is all of" from my exposed filter, all works. My exposed filter shows some tags in a select/option html list. I downloaded and installed the module "Better exposed filter" for display my exposed filter in checkbox instead the select/option html list. If I configure my exposed filter for it display checkboxs, then the view displays no result.

In detail :

I created 3 simples contents of type 'articles' :

Recipe one (tags 'ingredients' : salt, sugar )
Recipe two (tags 'ingredients' : super, pepper )
Recipe three (tags 'ingredients' : pepper, salt )

I created a very simple view :

When I do a search, I get two of my articles if I select the tag "sugar" with the exposed operator "is all off" : (look the Query, only one "INNER JOIN")

Tags exposed filter is an html select/option list. I want to change this style by a list of checkboxs. So, I configure the filter style with the "better exposed filter" module :

When I do that, my view works when I search with the filter exposed operator "is one of". But when I use the filter exposed operator "is all off", no result displayed !

In the new query, I noticed there are two "INNER JOIN". The second uses an id = 0, the error must be here.

My questions are :

Do I forget something in my configuration ?
Is a bug in the module "better exposed filter" ?
What should I do to operate the operand "is one off" when I display it in list of checkboxs ?

No, It's a bug with the Better Exposed Filter module. From the looks of it, something is causing a '0' value to be added as a part of the WHERE clause.

You can see this in action by toggling the Allow multiple selections filter option; when the option is off you can select a non - Any - value to filter the view as expected; when the option is on any selection appends '0' value to the filter.

From looking at your linked issues, they look potentially related but not the same. You should look through the BEF module issue queue and if it's not posted yet, post it there to be reviewed.


Node Access Product Module (nap) - Really embarrassing error message I have built an Ubercart site, using the Node Access Product module, that sells only two products, one of which is access to a single node. Everything works correctly, but after the customer makes a successful purchase the following errors are repeated all the down the completed order page:

"Notice: Trying to get property of non-object in nap_save_purchase() (line 1508 of /home/mysite/public_html/sites/all/modules/nap/nap.module)"

and

"Notice: Undefined index: type in drupal_write_record() (line 7025 of /home/mysite/public_html/includes/common.inc)"

I have been everywhere looking for an answer. Can anyone help?

This error is thrown when an object is empty, and you attempt to determine the value of a property. In this case the following code is responsible:

 // Go through each of the products purchased.
  for ($i = 0; $i < count($product_nodes); $i++) {
    // Easy referencing.
    $node = &$product_nodes[$i];
    $settings = nap_get_nap_settings($node->nid); <- Throws error

My guess is that $product_nodes is empty.

Try wrapping the for loop as follows:

 // Go through each of the products purchased.
  if (!empty($product_nodes)) {
    for ($i = 0; $i < count($product_nodes); $i++) {
      // Easy referencing.
      $node = &$product_nodes[$i];
      $settings = nap_get_nap_settings($node->nid);

      ..rest of loop code ...

    } //End of for loop
  }

This should work. You should also bring this up as an issue on the project page.


Display batch operations messages I have defined a batch, everything works ok, but I want to understand how the messages are displayed. So I have this batch:

$batch = array(
  'title' => t('Generate reports'),
  'operations' => array(
    array('create_report_callback', array($time_min, $time_max)),
  ),
  'init_message' => t('Starting report generation...'),
  'progress_message' => t('Generating report. Operation @current out of @total.'),
  'error_message' => t('Error detected. Please try again!'),
  'finished' => 'create_report_finished',
);

What I want to know is how to change the progress_message to something else than Operation @current out of @total. I don't know where the @current and @total come from

Thank you.

The placeholders @current, @total, etc are described in the file includes/form.inc in the description of the batch_set() function.

  progress_message: Message displayed while processing the batch.
  Available placeholders are @current, @remaining, @total,
  @percentage, @estimate and @elapsed. Defaults to t('Completed
  @current of @total.').

You can add custom placeholders by using the t() function like this:

$my_custom_variable = 'contents of my custom variable';

$batch = array(
  'title' => t('Generate reports'),
  'operations' => array(
    array('create_report_callback', array($time_min, $time_max)),
  ),
  'init_message' => t('Starting report generation...'),
  'progress_message' => t('Generating @my_custom_placeholder report. Operation @current out of @total.',
     array(
       '@my_custom_placeholder' => $my_custom_variable,
     )
  ),
  'error_message' => t('Error detected. Please try again!'),
  'finished' => 'create_report_finished',
);


I have a query tagged QueryAlterableInterface that I need to add an item to the IN clause I want to alter the term_access query and it's tagged in QueryAlterableInterface. There are items I want to add to an IN clause that's been altered before my module.

I've tried something

$query->condition('ga.gid', $new_items, 'IN');

But that just adds a new db_placeholder_n to the arguments array without altering the query itself.

Query is:

SELECT DISTINCT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, base.uuid AS uuid, v.machine_name AS vocabulary_machine_name
FROM {taxonomy_term_data} base
INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid
LEFT OUTER JOIN {og_membership} ga ON ga.etid = base.tid
AND ga.entity_type = :entity_type
AND ga.field_name = :field_name
WHERE  (base.tid IN  (:db_condition_placeholder_1)) AND( (ga.gid IS NULL ) OR( (ga.group_type = :db_condition_placeholder_2) AND (ga.gid IN  (:db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) ))

Ok here's what happened. Basically, I had to unset the conditions and then just rewrite all of them. Any better solutions I will accept as the answer but this is how I solved it.

$where =& $query->conditions();

if(empty($where[1])) {
  return;
}

unset($where['1']);
$list = my_custom_function_to_get_groups();

$groups = array();

foreach($list as $group) {
  if(!empty($group->nid)) {
    $groups[] = $group->nid;
  }
}

$query->condition('ga.gid', $groups, 'IN');


System settings form data access validation I have created system settings form for an image using managed_file.

$form['my_image'] = array(
  '#type' => 'managed_file',
  '#name' => 'Upload Image',
  '#title' => t('Upload Image'),
  '#default_value' => variable_get('my_image', ''),
  '#description' => t("Here you can upload setting image!"),
  '#upload_location' => 'public://my_image/',
  '#upload_validators' => array(
  'file_validate_extensions' => array('jpeg png svg jpg'),
  ),
  '#required' => TRUE,
);

How can I add the file view/download access on this file based on role?

It looks like the Field Permissions module is the answer to your case.

UPDATE: You could also use '#access' in your field definition, see this post


Multiple condition in Conditional Field doesn't work I am using Conditional Fields Module to show and hide fields according to the condition selected.

At first, I have a Select List with 3 Values (Mind, Body, Soul)

When I select Body the two fields (Body, What are your diet Plans?) shows up, like in Picture:

When I select Soul another Two fields Show up:

But When I select Mind, I get only one field, even though I have configured it to show two fields.

My Conditional Field Configuration is:

The issue here is, What are your prayers? field is configured to show when either Mind or Soul is selected from that Select List

I have configured it correctly using OR in the field condition but it(what are your prayers?) only shows while selecting Soul from the select list.

Any ideas what is wrong here?

I was in the same trouble.

I just found that you can use one condition and use "Values input mode" to  Only one of these values (XOR) and Set of Values to the ID or Text of the value of the field you want.

Check that : http://www.interworks.com/blogs/gbivens/2010/06/04/tricking-drupal-webforms-allowing-multiple-options-same-key-value

EDIT : Here a picture


Node reference + i18n - How to display only referenced nodes for the current language? I have two content types with multilingual content (French/English), Publications and Profils.

I have set up a node reference on Publication content type to link any Publication with the concerned Profil.

Unfortunately all Profils appear in listing, which is very confusing for the user. I would like to only display french Profiles when editing/creating a french Publication (and same for english content).

I just discovered the module i18n node reference synch (https://www.drupal.org/project/i18n_node_reference), but unfortunately this module doens't provide this kind of feature.

If it would be an option for you to switch from using node reference to entity reference, then you could try to use the Translated Entity Reference module. From its project page:

  ... brings better i18n support to Entity Reference field selection widget.


Import image with migrate tools changing its name I’m trying to migrate some data from a remote rest/api (json) using the plugin source url. My problem is in the json i consume the image name field comes with an incorrect value.

In imageName comes '0_3.jpg' and the correct name is '0_3.png', for example

So i have the following code trying to transform the name:

  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - imageName:
            plugin: str_replace
            source: imageName
            search: "jpg"
            replace: "png"

but this gives the following error:

  TypeError: Argument 2 passed to Drupal\Component\Utility\NestedArray::getValue() must be of the type array, null given

Anyone has any idea?

Two options:

_image_fixed:
  - plugin: str_replace
    source: imageName
    search: "jpg"
    replace: "png"

source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - @_image_fixed

Or:

source_full_path:
  - plugin: concat
    delimiter: /
    source:
      - constants/source_base_path
      - imageName
  - plugin: str_replace
    search: "jpg"
    replace: "png"


How to display drupal 7 Ubercart product attribute options in views filter? I want to display drupal 7 Ubercart product attributes(for eg: size - Medium, Small, Large) as views filter in the products listing page. I have searched on google but did not find any solution for that.

Add "add to cart form" field in view. we can see all attributes in view which are added for this product


Javascript link in theme.info not working Drupal 7 Why is my jquery.js file not found when I use this code in my theme.info?

Im using drupal 7.

scripts[] = js/jquery.js

I got this code from the drupal page and I'm 100% sure its the right path.
what did i do wrong here?

Thanks for helping!

Clear your cache. I think it may work for you.


How to change front page template based on url alias? I have many homepages and template file for every homepage and also a custom template for the front page the problem is when I change the default front page in admin/config/system/site-information to any other alias the page still have the page--front.tpl.php styles not the custom node style page--node--68.tpl.php , any help please ?

In Drupal 7, template suggestions are added/modified in the preprocess function, in this case HOOK_preprocess_page().

Add this to the template.php file in your theme root directory; you may need to create this file.

The problem is that the page--node--id suggestion is weaker than page--front and does not get used. We need to move the page--node--id suggestion to the end of the theme_hook_suggestions array, so it overrides page--front.

Add this snippet. I have added comments to explain what each line of code does. Replace ThemeName with your theme name.

/**
 * Override or insert variables into the page template.
 */
function ThemeName_preprocess_page(&$variables) {

  // Check if this is the front page and a node is the front page.
  if ($variables['is_front'] == TRUE && isset($variables['node'])) {

    // Foreach over the theme_hook_suggestions array.
    foreach ($variables['theme_hook_suggestions'] as $key => $value) {

      // Does the suggestion match the current node?
      if ($value == 'page__node__' . $variables['node']->nid) {

        // Match, unset the template suggestion.
        unset($variables['theme_hook_suggestions'][$key]);

        // Push the template suggestion onto the end of the array, this will give
        // it precedence over page--front.
        $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;
      }
    }
  }
}

I think this is the easiest/quickest way to move an array item to the end, where it will override page--front.


How do I use '#attached' to attach a style sheet? I know that drupal_add_css is depreciated, and that we should use #attached instead to attach a css style sheet to a module.

I am trying to replace the following (which works):

drupal_add_css(drupal_get_path('module', 'mymodule') .'/mymodule.css');

with #attached.  But haven't found exactly where and how to add it.

Here is my second attempt (it still does not work):

/**
 * Implementation of hook_block_view()
 */
function mymodule_block_view($delta = '') {
  if ('mymodule' == $delta) {
    $render = array();
    $list = mymodule_fetch_from_info();
    foreach ($list as $element) {
      $render[] = array(
        '#type' => 'markup',
        '#markup' => $element[0],
        '#weight' => $element[1],
      );
    }
    $blocks['subject'] = t('Mymodule');
    $blocks['content'] = $render;
    $blocks['#attached'] = array (
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/mymodule.css',
       ),
    );
    return $blocks;
  }
}

You cannot use #attached inside your hook_theme implementation. Instead, you should add it when you're building a render array:

$blocks['content'] = $render;
$blocks['content']['#attached'] = array (
  'css' => array(
    drupal_get_path('module', 'mymodule') . '/mymodule.css',
  ),
);

As kiamlaluno already pointed out in the comments, in your code example $blocks['content'] is the render array, so the #attached element must be part of that array.


How do I disable the password recovery link? How can I disable, in the standard login form, the link for password recovery? I need it for my custom theme.

You can use hook_menu_local_tasks_alter().

E.g.

/**
 * Implements hook_menu_local_tasks_alter().
 */
function MY_MODULE_menu_local_tasks_alter(&$data, $route_name) {
  if($route_name == 'user.login') {
    $data['tabs'][0]['user.pass']['#access'] = FALSE;
  }
}

Note: Make sure to replace MY_MODULE with the actual name of your module.


Install other modules from hook_install Is it possible to run command of the same functionality as drush pm-download from hook_install or hook_update_n? If not, what other alternative solutions do I have to automatically download and install modules and dependencies from a custom site deployer module?

Is it possible to run command of the same functionality as drush pm-download from hook_install or hook_update_n?

If the web server user has permissions to write to the modules folder (which is in itself a security risk), then yes, you can do that. Writing it wouldn't be trivial, of course, but you can get a lot of the necessary code from Drush.

If the web server user doesn't have permissions to write to the modules folder, then no, it's not possible.

  If not, what other alternative solutions do I have to automatically download and install modules and dependencies from a custom site deployer module?

If your web-server is properly secured, then your only option is to invoke the script (whatever form that may take) as a user with sufficient privileges.


Command to list all media entities in console? I have an issue in my site which is not allowing me to visit the /en/admin/content/media page.

I'm looking for an approach to list and delete media entities on the command line.

When I run drupal debug:entity media I get an error:

[ERROR] Notice: Undefined index: media in Drupal\Console\Command\Debug\EntityCommand-&gt;execute() (line 79 of /home/ubuntu/site/vendor/drupal/console/src/Command/Debug/EntityCommand.php
         ).
Drupal\Console\Command\Debug\EntityCommand-&gt;execute(Object, Object)
         (Line: 255)
         Symfony\Component\Console\Command\Command-&gt;run(Object, Object) (Line: 971)
         Symfony\Component\Console\Application-&gt;doRunCommand(Object, Object, Object) (Line: 248)
         Symfony\Component\Console\Application-&gt;doRun(Object, Object) (Line: 185)
         Drupal\Console\Core\Application-&gt;doRun(Object, Object) (Line: 64)
         Drupal\Console\Application-&gt;doRun(Object, Object) (Line: 148)
         Symfony\Component\Console\Application-&gt;run() (Line: 89)
         require(&#039;/home/ubuntu/site/vendor/drupal/console/bin/drupal.php&#039;) (Line: 4)

The docs of this command is also really uninformative.

What's the best approach to list and delete media entities on the command line?

If you use Drush, you can try drush sql-query like this :
 drush sql-query "Delete from name_table weher condition"


Webform get all submission for a node by date I am using webform_get_submissions to get all submissions, I have a requirements to get only one day back submissions.

Is there any way to get this results?

It seems it's not possible directly. See webform_get_submissions date range filter issue.

From taht issue:

  We now have built-in range functionality in #1237660: Add date range
  or "last X submissions" to CSV/Excel download. That patch just uses
  the existing ability of webform_get_submissions() to filter by SIDs,
  which would probably work in your situation too as long as you can
  retrieve a list of SIDs by date.

So you have to build a query to retrieve a list of SID's bty date and then pass it to webform_get_submissions.


Append image style to an inline image in CKEditor With views, for example, I'm able to set the image size which is to be loaded (using image styles). Is it in any way possible to do such thing in CKEditor?
At the moment, Drupal is loading the original image and scales it down in the browser.
I need to set an image style so all the inline images are resized to a width of x pixels.

Use insert module

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

  This module was previously known as FileField Insert.

  Features

Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain

  text areas.
      Insert images using ImageCache presets
      Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
      Per-field insert configuration

I used that on drupal 7 in several projects and it's what you want.I don't used Drupal 8 version yet,but hope works well.

Hopefully, in Drupal >= 8.8 it's on the core.

https://www.drupal.org/docs/8/core/modules/media-library-module/embedding-media-with-ckeditor


Node add form set entity reference default selection based on content from another type node I wrote module with hook_form_alter to modify node_forum_form, i.e., node/add/forum form. One forum field is a taxonomy entity reference, field_topic. I want to set the field_topic selection based on the value from a specific node (NID=77) of type current_topic, which also has field_topic as an entity ref.

field_topic is ref to Topic taxonomy.

After loading node 77, I got the TID of the current_topic field_topic, loaded the term, and then got the term name. Name is displayed on the form above the title using $form['title']['#markup'].

Problem:  Before returning the form, how can I set the form default selection to be that same field_topic value?

use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id != 'node_forum_form') {
    return FALSE;
  }
  else {
    $nid = 77;
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); //get the TID
    $term = Term::load($current_topic_id);
    $the_topic = $term->getName();

    $form['title']['#markup'] = t('
The Current Topic is:  ' . $the_topic . '
');

    // REPLACE THE NEXT LINE WITH CODE TO SET THE CURRENT TOPIC
    $form['field_topic']['widget']['#options']['_none'] = 'Click & Select the Current Topic';

    return $form;
  }
}

I suppose with

  set the form selection

you mean the default value of the taxonomy term reference field?

If yes, in the code above try this:

$form['field_topic']['widget']['#default_value'] = $term->tid();

Btw. you also want to change your implementation from MYMODULE_form_alter to MYMODULE_form_node_forum_form_alter, because the former hook will be called for all forms, whereas the latter is just called when the forum node form renders.


How to store a single array value into a session variable? I have

Array ( [0] => cid [1] => TN201501HP )

Now I want to store "TN201501HP" into some session variable. How to store this value to a session variable?

<?php
//If you want store the value in a session, you need first start the session
session_start();
//I suposse that your array is named $array,
//then if you want get the position 1 use the following line
$_SESSION['var'] = $array[1];
//checking the stored value
echo $_SESSION['var'];

?>

Output:

  TN201501HP


custom js in bootstrap sub-theme is loaded, works in console, but doesn't actually work in browser I have a bootstrap subtheme with scripts[] = script.js in the .info file.  When I go to the site and view html source of the page I can see that drupal is including the file <script src="http://site/path/to/subtheme/script.js?ox2bif"></script> and if I click on that link and I see the expected contents of the file:

jQuery(document).ready(function(){
  jQuery('p').click(function(){alert("hello");});
});

The js works, the  links to the actual file.  What else is there?

If I paste jQuery('p').click(function(){alert("hello");}); into my browser's js console then, obviously, clicking any paragraph opens an alert popup window.  But what am I missing that it's not working in the Drupal theme?

Additional info:

Drupal 7
Bootstrap base theme 7.x-3.15
Using Bootstrap CDN (not the SASS or LESS starterkits) with version 3.3.7
Using jQuery version 2.1

switching to jQuery 2.2 or 3.1 doesn't not help

Currently doing:

function winprevent_custom_page_build(&$page) {
  $themescript = drupal_get_path('theme', 'winprevent') . '/script.js';
  drupal_add_js($themescript, array('group' => JS_LIBRARY, 'weight' => -10));

...in a custom module to load the script from the theme.  Notice the 'group' => JS_LIBRARY; this was necessary to get the file to load before admin_menu module's js.  Disabling admin_menu stops it from breaking.  The presence of admin_menu.js also breaks the animation of Bootstrap's collapse feature.

So scripts[] = script.js actually does work in the theme but only for anonymous users, it breaks for the authenticated users (who all have access to the admin menu).

what am I missing that it's not working in the Drupal theme

You're not using proper jQuery Drupal syntax

(function ($) {

     //code starts
     $('p').click(function(){
        alert("hello");
     });
    //code ends

}(jQuery));

See Working with JavaScript and jQuery for an in-depth explanation.


How do you theme specific fields in on a content type? Currently I want to theme a taxonomy field in my content type and expose the TID and the Term name with link. The default sections only give me one or the other. Is there a setup where I can expose the TID, Term name, and Link?

Below is a screenshot of the teaser view display mode.

You could use field.tpl.php

If your field is called field_series then you will need to create:

/mytheme/anyfolder(optional)/field--field-series.tpl.php

If you inspect the variable $element then it will contain everything you'll need (tid, name, see drupal_get_path_alias for the link)

Don't forget to clear the cache once the new template has been created.


Module for HR and vacancies Is there a module for Drupal that can be used for job postings, with specific access limited to people from HR / system admin?

You can achieve your all requirements by installing Recruiter Drupal distribution.

  Recruiter is a Drupal distribution for building Drupal based
  e-recruitment platforms. Users can register either as recruiter and
  post job classifieds or they can register as applicants and fill out
  their resume. A faceted search helps users to find jobs and possible
  job candidates.


How do I pass a PHP variable to Drupal.settings global javascript? Javascript works fine, but i need to get my_var variable from module. At the moment its not working.

Clear my page cache and browser cache several times.

The variable 'my_var' is showing value on front end but not on backend/admin side.

Front end theme is Bartik; the admin theme is Seven.

All other variables are available on Admin side from Drupal.settings, except the one I pass from my custom module.

This works well on both themes.

alert(Drupal.settings.basePath);

This is my code.

MY_MODULE.module

/**
 * Implements hook_page_build().
 */
function MY_MODULE_page_build(&$page) {
    ctools_include('modal');
    ctools_modal_add_js();

    // HERE it is calling the js
    drupal_add_js(array('MY_MODULE' => array('my_var' => 'MY_VALUE'),), 'setting');
    drupal_add_js(drupal_get_path('module', 'MY_MODULE') . '/js/MY_MODULE.js');
}

MY_MODULE.js

(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context) {
        alert("test");
        alert(Drupal.settings.MY_MODULE.my_var);
    }
  }
})(jQuery);

On front end, it alerts with test followed by MY_VALUE, but on admin side, it shows test; Firebug then shows me:

  Uncaught TypeError: Cannot read property 'my_var' of undefined

How can I fix this?

calling drupal_add_js in hook_init is a fairly standard response to this kind of question, as is hook_boot.

hook_init is used for setting up things required by the page - but doesnt run on cached pages.

hook boot is used for code that has to run on cached pages as well as uncached pages.

The way I usually debug this kind of thing is with the javascript console. In chrome, open the console and type

Drupal.settings

hit enter and it should print out the whole settings object for you to inspect. This will let you see what you have.

I suspect the problem may be down to when hook_page_build gets fired on admin pages if Im reading your question correctly.

Uncaught TypeError: Cannot read property 'my_var' of undefined

means that

Drupal.settings.MY_MODULE

evaluates to undefined. It could be at any level.
so try the javascript console trick and see what you find (is Drupal there.. is drupal.settings there).

you could also try

(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context,settings) {
    alert("test");
    alert(settings.MY_MODULE.my_var);
   }
  }
})(jQuery);

which is more keeping with how it is documented for behaviours on drupal.org