How to update a field on menu_link_content (added using menu_item_extras module) entity from node form I have a checkbox field added to one of the menus using Menu Item Extras module. By default, the checkbox is checked and works as expected when I create a menu item via menu admin UI. however, when I create a menu item via node, the field doesn't get the default behavior (checkbox checked). I also checked the table (menu_link_content__[field_name]) and there is no entry for the menu item added via node/add form.

There are couple of problems here:

The node form has the menu fields hardcoded. See menu_ui_form_node_form_alter() and menu_ui_form_node_form_submit() for more details.
Turns out the root cause of the field issue is that the Menu Item Extras module updates the bundle value to menu name which happens on pre_save hook of menu_link_content entity. Without menu_name as bundle, the entity wouldn't have any fields associated.

One way to solve this issue is to implement a hook_form_node_form_alter() hook and update the bundle details before trying to update the custom field. Here is the code:

1. mymodule/mymodule.module

/**
 * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = [
        \Drupal::service('mymodule.menu_link_content_helper'),
        'nodeSubmit',
      ];
    }
  }
}

2. mymodule/src/MenuLinkContentService.php

<?php

namespace Drupal\mymodule\Services;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

/**
 * Class MenuLinkContentService
 *
 * @package Drupal\mymodule\Service
 */
class MenuLinkContentService  {

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * MenuLinkContentHelper constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   Entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * Form submission handler for menu item field on the node form.
   *
   * @param array $form
   *   Form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function nodeSubmit(array $form, FormStateInterface $form_state) {
    if (!$form_state->isValueEmpty('menu')) {
      $values = $form_state->getValue('menu');
      if (!empty($values['entity_id'])) {
        // There is no bundle by default for menu_link_content entity.
        $menu_name = 'menu_link_content';
        if (!empty($values['menu_parent'])) {
          list($menu_name) = explode(':', $values['menu_parent'], 2);
        }
        $entity = $this->nodeSaveMenuLinkContent($values['entity_id'], $menu_name);
        // If no  menu item with given bundle, load and update bundle.
        if (!$entity) {
          $entity = MenuLinkContent::load($values['entity_id']);
          $entity->set('bundle', $menu_name)->save();
          $this->nodeSaveMenuLinkContent($entity->id(), $menu_name);
        }
      }
    }
  }

  /**
   * Updates additional field on menu link content entity.
   *
   * @param int $entity_id
   *   Entity ID.
   * @param string $menu_name
   *   Menu name.
   *
   * @return \Drupal\Core\Entity\EntityInterface|mixed|null
   *   An Entity. NULL, if no entity with given ID and bundle found.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function nodeSaveMenuLinkContent($entity_id, $menu_name) {
    $storage = $this->entityTypeManager->getStorage('menu_link_content');
    // Using loadByProperties() as loading without bundle wouldn't bring the
    // custom field.
    $entities = $storage->loadByProperties([
      'bundle' => $menu_name,
      'id' => $entity_id,
    ]);
    $entity = reset($entities);
    if ($entity) {
      $entity->set('field_searchable', TRUE);
      $entity->save();
      return $entity;
    }
    else {
      return NULL;
    }
  }

}

Note: my checkbox field is field_searchable.


How to do a lookup of existing nodes in the input form? I want to create  in Drupal 8 a content type called Book  with some fields you'd expect to be associated with it.  Title, Author, Date, ISBN, URL

(I want two other content types: "Book Review" and "Book Author.").

I expect to do a lot of different things with books; it's much easier to have a separate content type for it which I can reuse.

The user (or the admin) would initially use the input form to publish  the "Book" (i.e., To Kill a Mockingbird, Great Gatsby, etc)

Next a user having the "Book Reviewer" role would have an input form to publish his review (Title, a text field containing the review, a summary, rating) and publication date.

Here's the thing I don't understand.

Tom (who has the Book Reviewer role) would log on, select "Add Book Review". For this to work, Tom would need some  way in the input form to look up the available book titles already inputted by users in order to choose the specific book he wants to review.

Can you accomplish this in Drupal 8? What is this functionality called? Could this reverse lookup be easily done from the Book Review input form? I'm  unsure exactly how to implement this. I've seen explanations about how you can look up a specific user in the input form, and maybe from the DB point of view, all nodes are the same. But I'm not sure if looking up users is a special case.

Some more details:

I have seen that relationships are a way to connect fields from two
    different content types. But I'm unsure if you could display this
    kind of lookup function in the input form!
I can' predict how many books will be added or need to be looked up
    (maybe 50-1000?). But is there any hard limitation on book nodes you
    could search through?
Is this something you could do through Drupal core without needing
    to make a module?

R3: You don't need to write any code :-)

R1: The relations are managed with the field Reference by content (provided by core) take a look inside the Add a reference field to content type
section in How To Reference Nodes in Drupal 8 + Views Relationships Display

Then you can go to configure your content type display mode and form display mode to change the widget if you want another different from the default widget. See Exploring the New Drupal 8 Display Modes and How "form modes" work in Drupal 8 and how to add and edit them

R2: You can have 1000 books without problem, in this case I recomend to use the autocomplete widget.

If you want to add more functionalities to your relation you can use the following modules:

Entity Reference Views Select

  A module for those who need their Entity Reference Views fields to be
  displayed as a select list, checkboxes or radio buttons in forms.

Inline Entity Form

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


How can I export the raw body of a node? I set up a CSV view with views_data_export. I'd like to export the raw body of nodes. So I want to keep both the raw markdown and the raw HTML in the CSV.

Is there a way to do this that I have overlooked? Should I add a formatter that does nothing? If so, how can I do that?

I thought I had solved it by checking "Rewrite the output of this field" and using [body-value], which is the raw value.

And this gives me the raw markdown but still doesn't give me the raw HTML.

Under FORMAT, click on Settings, check mark "Keep HTML Tags"


How to replace a Token in the PHP evaluation of a Rule? I'm trying to grant Userpoints to users with a Rule. The Rule first calculates two integer values 'New value' and 'Old value'. Debugging these numbers shows that there's no problem with them. Naturally, I tried awarding the points with an action "Grant points to a user" and I'm using the following code in the PHP evaluation:

if ($value > 5) {
  return 0;
}
else {
  return token_replace('[new-value]');
}

where the default $value is old-value.  As the [new-value] token is available in the data selectors of the 'Points' section of the action, I suppose that one can use it in the PHP evaluation too. Therefore, after reading Token Replacements, I thought my code should work, but it doesn't: the Userpoints aren't granted to the user.

There's definitively something wrong with the Token, because the Rule is executed correctly when I use 1 instead of token_replace('[new-value]').

What am I doing wrong and how can I solve this?

I still don't know what went wrong, but I've solved the problem in an alternative way. Everything works fine when you follow the steps underneath.

Save the integers Old value and New value as variables.
Add a third variable Result. Thanks to step 1, one can use $old_value and $new_value in the PHP evalution of this variable. I've used this code:

if ($old_value > 5) {
  return 0;
}
else {
  return $new_value;
}

Convert Value to an integer Final value.
Award Final value Userpoints to the user of your choice.


How to get user permissions for the role Administrator? I need to get permissions for all user roles, which are used. The code looks something like this:

$anonymous = Role::load('anonymous');
$anonymousPermissions = $anonymous->getPermissions();

The code for anonymous (and also for authenticated) returns an array of permissions, but the same code for administrator returns null:

$administrator = Role::load('administrator');

How can I get permissions for the role Administrator? (The machine name of role Administrator is administrator and also in the database is nothing suspicious.)

I have tried also:

$administratorPermissions = user_role_permissions(['administrator']);

It returns:

array(1) {
    ["administrator"] =>
        array(0) {
    }
}

If I try:

$roles = Role::loadMultiple();
foreach ($roles as $role => $rolesObj) {
    $role_list[$role] = $rolesObj->get('label');
}
print_r($role_list);

Then I get:

Array
(
    [anonymous] => Anonymous user
    [authenticated] => Authenticated user
)

See the Role::getPermissions() method code:

  /**
   * Returns a list of permissions assigned to the role.
   *
   * @return array
   *   The permissions assigned to the role.
   */
  public function getPermissions() {
    if ($this->isAdmin()) {
      return [];
    }
    return $this->permissions;
  }

So, if the user has all permissions the returned value is an empty array.

Why? I really don't know and I can't find the answer, maybe other user knows Why Role::getPermissions() method return an empty array for admin users?.

The good news is that you can get all the Administrator permission with this code:

array_keys(\Drupal::service('user.permissions')->getPermissions());

Test this code (You'll need the Devel module to use dpm()):

$administrator = Role::load('administrator');
if($administrator->isAdmin()) {
  dpm(array_keys(\Drupal::service('user.permissions')->getPermissions()));
}


Views Block displaying above node content I created a block using Views which is displayed on some particular content. However the block is being displayed before the main content. I tried changing the row weight for the block but this was no use.

All I need is to display the block after the node content.

Try out the below images step by step, i believe you are the evolving this step before you do with other blocks and pages

And see if that

Show block on specific pages are in

All pages except those listed or

Only the listed pages..

Make that to All pages except those listed and check that out..


hook_form_alter hiding field only in the form I have a content type with fields added from the core module and I want to hide some fields in the edit form, but not in the page node.

I've tried with

$form['my_field']['#access'] = FALSE; in my custom module, but that hides the field in the node page too.
Is there any other way to hide the field only in edit form?

My approach was to wrap some fields into a two columns. Here's what I've tried:

  <?php
    /*
     * Implements hook_form_alter().
     */

    function my_module_form_alter (&$form, &$form_state, $form_id) {
         switch ($form_id) {

          case 'custom_node_form':

          $form['column_left'] = array(
          '#prefix' => '
',
          '#suffix' => '
',
            );

           $form['column_left']['custom_field'] = $form['custom_field'];
           $form['custom_field']['#access'] = FALSE;
         break;
       }
    }

Unfortunately it's disabling into the page node too. I'm using Display suite for the full content and I'm pretty much sure that the field is not hidden from there.

Have you checked

admin/structure/types/manage/my_content_type/display

Your field is probably hidden here.

Otherwise, hook_form_alter is only for form you are right

An other attribute is :

$form['my_field']['#disabled'] = TRUE;


How can you have Composer install the site in the project root not in web/? I have downloaded Drupal 8.8 through composer drupal/recommended-project. The downloaded files structure is diff than previous download. Now core and other files are stored in web folder and vendor is out of core.

So my question is how to setup site in public_html/. I have uploaded files entire files under public_html/ but site not works. I also tried to access example.com/web but does't work.

How can I fix that?

If the server you are using uses public_html as document root, and not web as drupal/recommended-project expects, you need to follow what reported in Using Composer to Install Drupal and Manage Dependencies.

  If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the --no-install flag when running composer create-project. For example, it is possible that you want to rename the subdirectory 'web' to something else.

  To do that:

  Run composer create-project drupal/recommended-project my_site_name_dir --no-interaction --no-install
  Change directories to my_site_name_dir and edit the composer.json file to suit your needs
  Run composer install to download Drupal 8 and all its dependencies.


How to set product price with rules on checkout I want to set the product price for a special SKU in checkout.
Because i calculate the price based on the cart value this is needed.

I tried all rules but none is changing the price, how can this be done?

You must be using the product pricing system, which requires a rule assigned to the "Calculating the sell price of a product" event. Rules on this event can make use of a variety of Line item related actions to manipulate the unit price of the line item, and you'd just add conditions to your rule to only apply pricing based on the product SKU.

See the FAQ on Rules data selection for information on checking the product SKU:

https://drupalcommerce.org/faq/rules-field-data-selection


How to send system mails in html format (with Swift Mailer)? At Account settings page (/admin/config/people/accounts) I can edit system mails Drupal is sending (Welcome, Account activated, Account blocked and so on).
I also installed and configured Swift Mailer module. At Message settings page (admin/config/swiftmailer/messages) I selected HTML for message format.
Then I edit some message template and enter html content there like:
<!DOCTYPE html>
<html>
  <head>
    <title>Your account at [site:name] has been activated.</title>
  </head>
  <body>
[user:display-name],

Your account at [site:name] has been activated.

You may now log in by clicking this link or copying and pasting it into your browser:

[user:one-time-login-url]

This link can only be used once to log in and will lead you to a page where you can set your password.

After setting your password, you will be able to log in at [site:login-url] in the future using:

username: [user:account-name]
password: Your password

--  [site:name] team
  </body>
</html>

However in mail I receive I still got Content-Type: text/plain; and I see it as plain text.
At that Swift Mail Message settings page it says:
"You can set the default message format which should be applied to e-mail messages."
But I don't see that option anywhere? How to change this default message format (to "text/html")?
An update:
I found out that if I uncheck "Respect provided e-mail format." on SwiftMails Message settings page I do get text/html content type in mail header. However all the tags I enter in mail template are stripped out and new rows are automatically converted to paragraphs?
I expected that there will be "HTML email" text format at Text formats page (/admin/config/content/formats) where I can set filters, but there aren't any.

My edit to the accepted answer got reverted, so I'll contribute it as a separate answer, for two reasons: 1) several grammatical and formatting errors in the accepted answer make it hard to read and understand and 2) the comments to the accepted answer (and the "Update" section) explain why the proposed solutions do not work. This answer adds an additional working solution, credited to the author of said approach, at the very bottom of the post.
The Swift Mailer Drupal module works in combination with the (contrib) Mail System module.
1. Setup Mail System

Check the settings here: /admin/config/system/mailsystem

Make sure Swift Mailer is set as the Default Mail System > Formatter.

Select the theme you wish to render your HTML emails — typically your front-end theme — where you have the ability implement a custom swiftmailer.html.twig template with any wrapper HTML (eg email header and footer text that appears on all templates) and sub-templates.

Alternatively, under Module specific configuration, add the user module to explicitly use Swift Mailer as the Formatter for the User module. Hint: Leave the key field empty to affect all emails from the specific module. This way, other system or contrib module emails are not affected.

2. Configure Swift Mailer to use HTML for Core User Templates

Swift Mailer lets you choose the HTML format to use from a list of Text Formats you have defined in Drupal on the Message settings page: /admin/config/swiftmailer/messages.
So you could theoretically create a new Text Format yourself, such as "HTML Email", but this setting does not let you output any meaningful HTML because the text format needs the "Display any HTML as plain text" filter activated (see Issue #3122389: Bugs with format conversion).
In short, this option in the UI is a red herring and is only intended for upgrading Plain Text to a basic HTML format, by converting line breaks to
s and URLs like https://example.com to clickable links like https://example.com.

Alternatively, you can create a custom Twig template per module, like swiftmailer--user.html.twig, or per email key, like swiftmailer--user--password-reset.html.twig and replace {{ body }} with your HTML message, however you will not have access to the same Drupal Tokens that are available to the user account email templates in Drupal's admin UI. For a list of all user mail keys, see the $op parameter of _user_mail_notify().

Therefore, the currently known best approach is to enter your custom HTML into the Drupal administrative UI, then use hook_mail_alter to add text/html to the Headers and convert the text to a valid Markup object.

use Drupal\Component\Render\FormattableMarkup;
/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {
  switch ($message['key']) {

    // User module templates from admin/config/people/accounts
    case 'cancel_confirm':
    case 'password_reset':
    case 'register_admin_created':
    case 'register_no_approval_required':
    case 'register_pending_approval':
    case 'register_pending_approval_admin':
    case 'status_activated':
    case 'status_blocked':
    case 'status_canceled':

    // Contact module templates from admin/structure/contact/manage/sitewide
    case 'page_mail':
    case 'page_copy':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      foreach ($message['body'] as $key => $body) {
        $message['body'][$key] = new FormattableMarkup($body, []);
      }
      break;

  }
}

Hat tip to blog post from flocondetoile.fr for the code snippet.


Programmatically set Panelizer View Template on Node I have panelizer installed so that I can panelize the full content views on a node by node basis on my content types. For example I have a news content type but I have a default panelizer view mode and I have a 'press release' version meant for the news nodes that are considered press releases.

I'm attempting to perform a query on them so I can programmatically set the view modes in bulk instead of having to go through each node and do it manually, but I'm having trouble. The machine names of the views are 'news' and 'press_release' and I'm attempting to change them like so

$node->panelizer->view_mode = 'press_release';
$node->save();

But it doesn't seem to have any effect. How would I programmatically change the panelizer view mode on a node?

UPDATE:
I used $node->panelizer->getValue(); and this is what I received.

string(4) "news"
array(2) {
  [0]=>
  array(3) {
    ["view_mode"]=>
    string(4) "news"
    ["default"]=>
    string(4) "news"
    ["panels_display"]=>
    array(0) {
    }
  }
  [1]=>
  array(3) {
    ["view_mode"]=>
    string(4) "full"
    ["default"]=>
    string(13) "press_release"
    ["panels_display"]=>
    array(0) {
    }
  }
}

It seemed like instead of getting the view_mode that is set I got every view mode which made me think Iwas on the wrong path.

It turned out the output of $node->panelizer->getValue(); was giving me a clue that I missed.

I had forgotten that there were different panelizer templates for different view modes.

I was able to accomplish what I needed with

    $panelizer_arr = $node->panelizer->getValue();
    for ($i = 0; $i < count($panelizer_arr); $i++) {
        if ($panelizer_arr[$i]['view_mode'] == 'full') {
            $panelizer_arr[$i]['default'] = 'test_display';
        }
    }
    $node->panelizer = $panelizer_arr;
    $node->save();


How do I programmatically log in a user? I am looking for the API that will let me login a user by passing it the username and password.
Does anyone have experience with this?
To clarify, I am trying to make an AJAX login box that appears as a popup on the home page, and do not refresh the page in case of wrong credentials, but only if the log in is correct. So here is what i have done so far:
Update
I now load the login form on my homepage, then on submission I launch an AJAX request that sends credential to this script:
function user_login_submit_try() {
  global $user;

  $uid = user_authenticate($_POST['name'],$_POST['pass']);
  $arr = array ('name'=>$_POST['name'],'pass'=>$_POST['pass']);
  if ($uid){
    $user = user_load($uid);
    user_login_finalize($arr);
  }

  echo drupal_json_encode($uid);
  exit;
};

So far it works, but my worries are (as mentioned by googletorp) security issues; it seems that none of the API I used in this script sanitized the data in anyway.
Would anyone see a better way to do so?

This might help someone:

function mymodule_user_login_credentials($username, $password)
{
    if(user_authenticate($username, $password))
    {
      $user_obj = user_load_by_name($username);
      $form_state = array();
      $form_state['uid'] = $user_obj->uid;
      user_login_submit(array(), $form_state);
      return true;
    }
    else
    {
        return false;
    }
}

A better version based on the comment:

function mymodule_user_login_credentials($username, $password)
{
    if($uid = user_authenticate($username, $password))
    {
      user_login_submit(array(), array('uid' => $uid));
      return true;
    }
    else
    {
        return false;
    }
}


What module handles links of the form ? I'm maintaining a website with drupal 6 and recently did an update. I have some links of the following form:

 …
 …
 …

Since the update, every link of that form is dead (since the navigator just tries to open the url "internal:forum", which is completely invalid as is)

It may be a module I forgot to enable again after the update, but I have too much of them to test them one by one, and none of them seems related to that sort of link at all.

What are those links? What is handling them and what do I need to make them work again?

As @Clive suggested in the comments, I was searching for a module involving links when I should have searched for some kind of text filtering.

I've found the responsible module : Path Filter, and I indeed forgot to enable it again after the update.

The internal:forum pattern is written in a node's content, and is changed to a valid path in the final page.


Views Table with Taxonomy Terms for Columns and Rows I have a content type for manuals that has a vocabulary for "Model Year" and another for "Model Name" with a file upload that is for owners manuals for the specific Model Name + Model Year.

I want to push this content type into a view to provide a table where the years are columns and the model names are rows with the resultant cells having the download link.

---------------------------------------
        | 2016     |  2015   |  2014   |
---------------------------------------
Model 1 | download |download |download |
---------------------------------------
Model 2 | download |download |download |
---------------------------------------
Model 3 | download |download |download |

I've been wrestling with the views all night and the table. I can't seem to get close to what I want. I've tried making sure all the taxonomy terms were added as a relationship.

If I use fields and bring the content of the year and the model forward I can display them, but not as columns, only rows and not as rolled up results in a year - so 10 2016 column instead of one 2016 columns with 10 rows.

I've tried the Views Flipped Table module, but that didn't solved the problem.

The Forena module can be used for this type of reporting. More specifically by using its facility to create a Display of a table in crosstab format.

A crosstab table is a table with a special layout. It is formatted as a grid, with:

the rows representing one or more (combinations of) facts, such as countries or regions, names of persons (or users) like employees / salespeople (or user IDs / user names), names of Models, etc.
the columns representing one or more other facts, such as periods (months of a year, years, etc), available types/flavors of something (like types of errors), etc.
the intersections of rows and columns containing the actual information (data), such as summarized information (counts of something), timestamps, etc. and which might (optionally) include a hyperlink to a drill-down report.

Below is a sample of such crosstab report (including drilldown links also, i.e. the numbers in red in it):

Refer to my comment in the Forena issue queue for more details about the above screenshot. And/or have a look at the video about How to generate crosstab reports with graphs (Forena also supports charting of those data, a typical related requirement ...).

In this specific case, if I was to create such crosstab table, for "the resultant cells having the download link" I'd create a hyperlink which would actually mention the number of manuals corresponding to the selected combination of Model Name and Model Year. And by following such link, you'd get a drilldown report with links to the actual manuals.

Disclosure: I'm a co-maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


How to automatically create nodes from a bulk file upload I've got a hundred or so files (mixed types: pdf, ppt, doc, etc). I want to be able to upload these to my server, and then point my D7 site to the directory on the server that contains all of these files so that the site automatically creates a node for each file, with a single, different file attached to each node. Is there a module that will do this for me?

Using Bulk File Nodes you can create unlimited number of nodes at once .

  Bulk File Nodes allows a user to upload or import many files at once, and have many individual nodes created, one for each file . Where this module significantly differentiates from other modules like Bulk Media Upload is that after uploading/importing the file(s), the user is given the opportunity to edit all of the fields for each node in a single form.

This module creates a node for each file and you can edit the fields of each node after uploading.

Solution 1

You are right, Bulk File Nodes works only with images. since you need to create nodes programmatically and assign the files to the nodes you can use the following code to create a node without a file field

$uid = SOME_USER_UID
$values = array(
        'type' => 'THE_CONTENT_TYPE',
        'uid' => $uid,
        'status' => 0,
        'comment' => 0,
        'promote' => 0,
        'language'  => 'en'
);
$entity = entity_create ('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->title->set('THE_TITLE');

$ewrapper->save();

But from Attaching image files to nodes programmatically in Drupal 7
 you can use the following code to attach the file to the above node

$filepath = drupal_realpath('misc/druplicon.png');
 // Create managed File object and associate with Image field.
 $file = (object) array(
'uid' => 1,
'uri' => $filepath,
'filemime' => file_get_mimetype($filepath),
'status' => 1,
  );

// We save the file to the root of the files directory.
$file = file_copy($file, 'public://');

$ewrapper ->field_file[LANGUAGE_NONE][0] = (array)$file;

This code should be above $ewrapper->save(); line.

Solution 2

You can also create the nodes without file fields as described above. and for each node with $node variable Programmatically Attach Files to Node.

// We have complete file path.
$file_path = '/whatever/path/to/file/sample.pdf';

$file = new stdClass;
$file->uid = $node->uid;
$file->filename = pathinfo($file_path, PATHINFO_BASENAME);
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;

// Save file object to make it a 'managed file'.
file_save($file);

// We will save file under this location.
$destination = 'public://PDFs/';

// Make sure destination directory exists before moving files to that path.
// This will create directory if it does not exists.
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);

// Now attach file to the file field.
$node->field_pdf[$node->language][0] = (array) $file;

// Default file type field comes with this extra properties.
$node->field_pdf[$node->language][0]['display'] = 1;
$node->field_pdf[$node->language][0]['description'] = 'Our special PDF';

// Save node to make the attachment effective.
node_save($node);


Creating a custom 3up layout view? On the homepage of my website, I would like to have a block which displays 3 links to inner pages like so:

Each would have the Title of The page, a teaser image that I would like to select to represent each of these links (Since none of the inner pages have images used on them), a small summary and a link to the page.
What's the best course of action for me to take in creating this?
Would I create a custom view block to display this? If so, are any special settings needed and is there a way for me to select which picture is used through the views settings (overrides?)?

I feel as if this is quite the simple thing to achieve, yet I seem to be overthinking it as I can't come up with a proper solution which would make sense to me.

Multiple ways of doing this depending on what you feel like doing.

Custom block type

Create a custom block type, add the fields you need, add them to a region and set to the homepage. Theme the twig files that relate to this block type.

Paragraph type

You can set up a paragraph type to build this into the node itself. Create a paragraph type that has title, image, summary, and link - then a reference field on the host node that limits the cardinality to 3 total. Theme up the twig files that relate to this paragraph.

Entity reference field on the node

You can even simply set a reference field to other nodes and let the editor enter what nodes they want to reference, and set the field formatter to a display mode (for example 'Call to Action' or 'Card'), and theme those twig files. Simply printing {{ content.field_foo_reference }} will render them as their view mode set in the field formatter. Fields like 'summary' can live on the referenced node - perhaps even a body field that is trimmed (look at adding Smart Trim for better trimming options on long formatted text fields).

Personally, I would go with the third method - it is the quickest of the three to do. I think you can even achieve this with core alone - something you can't do with the second method. It also puts all the work into the node form, instead of require editors to fool with the block system overview and create blocks to do this. Of course, you can also add this reference field on a block type and employ the same method - however since the homepage for me is almost always a node, I like to contain it in the same spot.


Geofield (geocode from another field) - database entry not created On a Drupal 7.63 site, I have a content type with a "Postal Address" field (address module, v7.x-1.3) (mandatory) and a "Geofield" field (geofield module, v7.x-2.4). The geofield field has no input interface: it uses the "Geocode from another field" widget and is configured to use the Postal Address field as a source. Its information is then used to render a small map using Google Map ("Geofield map").

My issue is that when creating new nodes, the geofield field remains empty and no map is rendered. And when updating the address on existing nodes, the map isn't updated (it still shows the old point).

I checked directly in the database (table field_data_field_geofield), and can confirm that the rows corresponding to the new nodes are not there. So it seems the data is never created in the table, but I don't know why.

I see no error message on the edit page of the nodes or in the recent log page (admin/reports/dblog).

The addresses used for those nodes are correctly formed and stored (I checked the field_data_field_adresse table); they are rather simple and can easily be found on Google Maps. (Example: Grand-Rue 5, 2900, Porrentruy, Switzerland)

I tried applying the patch provided in this issue, but it didn't solve my problem, even when creating new content (I have since rolled back this change). Maybe it's not the same problem.

Update: after more research, this issue seems to describe my problem. However:

applying patch #29 doesn't solve the problem
applying patch #41 doesn't solve the problem
downgrading geocoder to v.1.3 doesn't solve the problem either.

Any suggestion on what is wrong would be greatly appreciated. What else should I check for?

(It's on a website that has used this system for several years and it's the first time I see this problem.)

(I created a request support ticket on the geofield page last week, but so far I haven't received any feedback.)

So in the end the problem actually had two causes, which made it more difficult to solve than it should have been:

a bug in the geocoder codebase (solution: apply this patch)
the Google Maps API key used in the geocoder configuration was actually invalid for this type of operation, and so I had to generate another key specifically for geocoding operations. (I noticed the problem via a geocoder error saved in the recent log entries pages.)


Default all entities to English At some point we will be enabling translations on all entities in Drupal 8. However, we are not ready yet so in the meantime we would like to set all of the entities (content types, taxonomy terms, paragraphs, menus, blocks) to be defaulted to English language. We want to do this because we do not want any entity to have a language code of undefined (or und).

I am unable to find the setting that will allow us to default all entities to just English.

How can we set the default for all entities as English?

You probably want to write this as an update hook, something like this should work:

function MY_MODULE_update_N() {
  foreach (\Drupal::entityTypeManager()->getDefinitions() as $entityType) {
    $entities = \Drupal::entityTypeManager()->getStorage($entityType)->loadMultiple();
    foreach ($entities as $entity) {
      if ($entity->langcode->value != 'en') {
        $entity->set('langcode', 'en');
        $entity->save();
      }
    }
  }
}

This loops through all entity types and loads all entities for the given entity type, then it updates the language if it is not set to english.

You might want to create a batch process if you have many entities to update.

For more info about how to do that, look here.


How to replace "default" with website domain name during drush user-login When I run drush user-login username, drush prints a url like http://default/user/reset/1/32323933.... How do I replace default with the actual website name?

You can use option --url:

  -l <http://example.com:8888>,             URI of the drupal site to use (only needed in multisite environments or when running on an alternate port).
   --uri=<http://example.com:8888>

$  drush uli -l yoursite.dev

Or create a record in your aliases.drushrc.php file:

$aliases['yoursite-dev'] = array(
  'root' => '/vhosts/yoursite.dev',
  'uri' => 'yoursite.dev',
);

Now you have an alias @yoursite-dev and can use it:

$ drush use @yoursite-dev
$ drush uli

Update:

Now I prefer to create sites/default/drushrc.php file for each Drupal folder:

<?php
$options['l'] = 'http://yoursite.dev';
$options['r'] = '/vhosts/yoursite.dev';

More info about drushrc.php: https://github.com/drush-ops/drush/blob/master/examples/example.drushrc.php


Taxonomy term based content how do I get taxonomy based node content through custom query? I have taxonomy terms displayed using drupal api function. Now I need to fetch content based on terms id or name from database? Can any one please help me.Either using entity field query or SQL?

$tree=taxonomy_get_children(1);
 foreach ($tree as $term)
 {
 $item[] = $term->name;
 $child_term = taxonomy_get_children($term->tid);
 if (!empty($child_term))
 {
 <a href="?name=<?php print $term->tid; ?>">
 <?php
 print $term->name."
";
 ?>

 foreach ($child_term as $child)
 {
 $item[] = $child->name;
 <a href="?tid=<?php print $child->tid; ?>" name="tid">
 <?php
 print $child->name."
";
 ?>

 <?php
 $nodes = taxonomy_select_nodes($child->tid);
 $node = node_load_multiple($nodes);
 $nidd=(int)$node->nid;
 foreach($node as $node1):
 $tids = field_get_items('node', $node1, 'field_product_sub_cat');
 foreach ($tids as $tid){
 if($tid['tid'] == $child->tid){
 print $node1->title;
 print render(field_view_field('node', $node1, 'body'));
 }
 }
 endforeach;
 else
 print $term->name."
";

You can get nodes as shown below:

$nodes = taxonomy_select_nodes($tid); // $tid is term id
$nodes = node_load_multiple($nodes);

Ref: taxonomy_select_nodes -> https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_select_nodes/7

Update #1

To get some fields out of $node object use following:

foreach($nodes as $node):
    $tids = field_get_items('node', $node, '<TERM_FIELD_NAME>');
    foreach ($tids as $tid){
        if($tid['tid'] == <SELECTED_TID>){
            print $node->title;
            print render(field_view_field('node', $node, 'body'));
            print render(field_view_field('node', $node, 'tags'));
        }
    }
endforeach;

To render complete node you can use node_view function. In order to render multiple nodes you can use node_view_multiple function as shown below:

$content = node_view_multiple($nodes, 'full');
print render($content);


It is correct to change unit_price of commerce_order_item programmatically under several conditions? I am developing a module that allows you to select additional options for a product that is not a product or a purchase entity. It's like commerce_option but for D8.

My inspirations come from Product Attributes shipped with Drupal Commerce. So I have mostly the same two entity types:

Product Option (config entity type) - bundle.
Product Option Value (content entity type) - the actual option with price field.

The options can be attached to commerce_order_item types as entity references. Then add to cart form display them as options to select.

The confusion comes at the part when these options come to commerce_order_item and actual order.

At the current moment, I've created a new field type with three properties: option (textfield), option value (textfield), price (commerce_price). This field automatically filled when commerce_order_item added to the cart.

Next, the most obscure part. What's the correct way to handle those additional and their prices?

I see several ways:

(current implementation) My current field type + commerce_order_item adjustments. The problem here I see, there is a bit mess with cart and other stuff. I need manually use getAdjustedUnitPrice() to get real product price. It can be affected by tax and other stuff, so this becomes a mess in the future. Plus, in this way I don't see the proper way to add a discount for this line item. Since the promotion applies to unit_price or total_price, but this amounts in adjustments. It can be solved, but may be tricky.
My current field type + override of unit_price. In this way the discount and tax problem disappear. But rises another problem. The manager, when editing order item, must take product options into account when editing it, since their price will be already included.

Maybe you can advise another approach? I also think about special commerce_order_item type + entity_reference (much complicated I think). But here all the problems of the first approach raise again.

Is it good to edit unit_price directly on order_item save\update? Or it is not expected behavior, when some event will change order_item price by adding the amounts? Also, how this must work on second and so on saves? E.g. order_item price $10, and selected option $5. When order_items saved, the current_price will become $15. When some changes are made, how to detect those options already included? The way I see, recalculate the new unit_price by grabbing the price from purchased_entity. But what if this price was manually overridden by the manager from $10, to $8? The only solution I see now, is to store price before it affected by options in the data field. Is this also correct or I miss something?

The reason because I create special field to store values is almost the same as order_item existence. The option prices can be changed, or even deleted, so order_item doesn't know anything about it and store the raw results values.

As a proof of concept a module with this functionality already exists. Unfortunately, it's not published yet because that requires a couple of final touches with a time frame allocated for this kind of work.

https://github.com/drugan/commerce_oiaddon

The price adjustment is taken from a pseudo-price field added to some entity type and then the order item price recalculated at the event of an order item added to or removed from a shopping cart. So I am not sure why you can't get the same result as in the commerce_oiaddon module. Just do the same as it shown in the example and it should work.


Users, subusers, and assigning subuser to multiple users I want the following functionality in Drupal 7: Create a few parent users/business representatives (e.g. Google, Microsoft); these business representatives will add their business profile, and add employees of that specific company, add/edit/delete them. An employee can be from multiple companies and all business representatives can edit/delete employee's profiles.
Employees can also log in, and manage their own profiles.

Which modules should I use?

There is a Subuser module to create subusers and a Profile2 module to create user profiles for every user.


What rule to use to redirect users, unless already redirected? I'd like users with certain roles to be redirected to the page /civicrm when they login, unless they've already been redirected elsewhere. For example, an email might have a link that directs them to the page /elsewhere.

When I tried the module 'login destination' I can only achieve one or the other, never both - either the redirect works but a regular login doesn't redirect to /civicrm or the other way round.

From browsing in Drupal Answers, I'm pretty sure that Rules could do this, but I've tried and failed so far.  The rule needs 2 conditions to be satisfied - user is one of the roles, and they are not already being redirected - then they should be directed to /civicrm.

Can anyone please suggest how a rule might achieve this?

Make a flag on users: 'flag_user_has_logged_out', you will need more than one rule, first rule: react on: user has logged out, and flag the user with this new flag, on another rule: react on logged_in: first validate your roles, then validate if user is 'flagged' if so, redirect to /whatever, and unflag user has logged out. if not, the other redirect will take control. This kind of rules i use a lot, i make many calculations on user has logged-out and i do not need to recalculate things again when user loggs in, it work both ways, maybe user just clossed browser and did not made a logged-out, so a evalutate that when loggs in and i do not duplicate my calculations. i hope you understood me and help you. is just a pointing directions on what you can do. Examples how your rules will look like:


How to implement different landing pages for different countries? How can I get Drupal 8 to use different landing pages for different countries?

I can create the pages but how do I tell Drupal which page to show for each country? Is geo location the only way, or is there another way?

First thing is, how are you identifying your user's country?

You could use JS and the geolocation API
Or you could use the IP of the user and use a database

Id depends on how accurate you need this.
Once you translate the information to an actual country. Then you can decide what to show.

Something to keep in mind is the penalty for this. Instead of showing a different page per country, you might consider showing the same page and maybe via some JS modify an element once you have the location.


How should I validate field values against an external service? I am looking at how to update a module that validates field values against an external service. Currently, it uses hook_form_alter().

I assumed I should:

Write a service that handles external communications and returns a Boolean value
Write a Constraint and a ConstraintValidator class that uses the service
Attach the ConstraintValidator object in hook_form_alter()

I assumed I would find a similar implementations in the code of the ReCaptcha or ReCaptcha V3 module. Neither of them uses that approach. I found the Field Validator module that is using constraints.

Is using a constraint validator the correct way, or are there other approaches?

As you want the field value to be validated, I would use a constraint, This ensures that the value is validated regardless of how the field value is saved - whether through a Form, an API (REST/JSON etc) or programatically.

As you didn't create the entities and fields yourself (I'm assuming you mean they're provided by a module or core, and not just that a former developer created them), you'll have to attach your constraint in hook_entity_bundle_field_info_alter() as explained in this post: How do I add a custom validation handler to an existing form/field?

Note however that this will mean anytime your entity has saved, and this field value has changed, your remote API will be called. If this is going to happen regularly, you may want to create some kind of caching system that caches the responses from the remote API.


Two columns on frontpage with a CCK form and a node list I want to show a simple frontpage that contains a content creation form (cck) on the left side and a list of nodes on the right side. With a head and a footer, the page looks like this:

I have looked into doing this with the Panel module, but it seems like overkill and I don't think it plays well with the grid layout I use.

I have also looked on doing this with the Views module and the Context module, but I don't really understand how I can execute the code for rendering the content creation form with this approach.

A third solution is to override the template for the page-front and hard code the rendering there, but a drawback would be that I then need to maintain multiple page templates.

So what is a good solution for this do you think? I would like to involve as little complexity as possible and my head is already spinning with all these modules for such an apparently simple problem.

Appreciate guidance from someone who is fluent with View, Context, CCK and Panels.

Administering panels has a huge overhead, however, since panels are highly cached there is actually a performance boost to use them over plain blocks. It's discussed in this article, Assembling Pages with Drupal.

If this is some type of survey or questionaire you can make the node edit form the front page by using using the site configuration feature assigning the font page path. With Views you then can create two blocks that you use to show on the right column in either the block administration page or the panels administration page. However, for surveys the standard is to use the Webform module.


drupal commerce conditional checkout panes I have used the following module to add a custom checkout pane to get some additional information from the user regarding the order.

https://drupal.org/project/commerce_fieldgroup_panes

I now need to apply a condition that if the order contain a product of specific product type then display this pane else hide it.

Can some one please guide me how can I do this.

I have found the following code from https://drupal.org/node/1807092 but I don't know how to modify it according my need. Looking for some help on how to modify & use this code.

<?php function commerce_conditional_panes_commerce_checkout_pane_info_alter(&$checkout_panes, $form, &$form_state) {
global $user;
foreach($checkout_panes as $pane_name => &$pane_data) {
    // load current order
    $order = commerce_cart_order_load($user->uid);
    // retrieve the value of controlling field
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    $control = $order->field_make['und']['0']['value'];
    // Perform switch to see what to do with each aircraft make
    switch ($control)
    {
       case "value1":
         break;
       case "value2":
         break;
       case "value3":
         break;
       case "value4":
         break;
       case "value5":
         break;
       case "value6":
         // ...we only need to override one of them
         if($pane_name == 'commerce_fieldgroup_pane__conditional_pane' && $pane_data['enabled']) {
           // the pane is enabled by default, so we need to disable it
           $pane_data['enabled'] = 0;
         }
         break;
       case "value6":
         break;
       case "value7":
         break;
       case "value8":
         break;
       default:
         break;
       }
    }
}
?>

It's surely too late for your project... Anyway, you may use Commerce Rules Extra,  it adds the exact features you need :

  Rules conditions : Total product of type quantity comparison : Total
  of products of specified type and with a specified quantity
  Rules actions : Change pane properties : Change visibility, page,
  weight of a pane

Once you installed it, in checkout settings , set your pane as disabled by default and create a new rule

event: Process checkout pane
conditions: Total product of type quantity comparison

Parameter: Order: [commerce_order]
Product Type: YOUR PRODUCT TYPE
Operator: >, Quantity: 0

action : Change pane properties

Parameter: Id of pane to change: YOUR PANE
Enabled: true
move to : checkout


Does the Data Export module support exposed filters? I am looking to use the Data Export module to export data to CSV files. However, I need the users to be able to filter the data first with exposed filters and then download the filtered results.

From what I can see, the module seems to be an all or nothing module.

Does anyone know if it is configurable?

When you create a Data Export view, there is an option to attach it to another view. You can choose to attach it to another page in the same view and all the filters used would be affected by the export. A new icon would be shown at the bottom of the view to download the exported data.

In the following screenshot, I attached it to a view page.


EventSubscriber returning correct content but status code is 404 As the title says, content is being returned correctly but the status code is 404.
I have checked the .htaccess file and the Apache config file as well. All seems to be fine.
I have the following in my module routing file:
my_module.news_list:
  path: /api/{state}/news
  defaults:
    _controller: Drupal\my_module\Controller\NewsController::index
  methods: [GET]
  requirements:
    _access: 'TRUE'

This is the function that does the redirect in my EventSubscriber
public function redirectRequestToModule(GetResponseEvent $event) {
            $request = $event->getRequest();
            $validPathBegins = ['/men', '/nat'];
            // This is necessary because this also gets called on
            // node sub-tabs such as "edit", "revisions", etc.  This
            // prevents those pages from being redirected.
            $requestUri = $request->getRequestUri();
            if (!in_array(substr($requestUri, 0, 4), $validPathBegins)) {
                return;
            }

            $node = $request->attributes->get('node');

            // get the configured request query parameters for this content type

            $redirect_url = '/api' . $requestUri;
            $kernel = $event->getKernel();
            $response = $kernel->handle(Request::create($redirect_url));
            $event->setResponse($response);
        }

This is what I type in the browser: mysite.com/nat/news/
The content returned is correct but the status code is 404.
P.S There isn't a reachable path on my Drupal website like /nat/news. The path mentioned is supposed to return a list of news articles.

Creating an alias in /admin/config/search/path/add worked. I created an alias /api/nat/news/ to /nat/news
Thanks 4k4 for a much easier solution drupal.stackexchange.com/a/187497/47547


how to filter taxonomy vacobulary using views contextual filters I have taxonomy vocabulary

parent term1 -
  child term1,
  child term2,
  child term3

parent term2 -
 child term4,
 child term5,
 child term6

I will be passing view arguments as parent term1. So the output should be (child term1,child term2,child term3).

Please let me know how to achieve this using views contextual filters

Thank you very much for your help!

You can refer Hierarchical Select module, which allows you to create taxonomy structure like your requirement and also allows to filter accordingly your requirements in view.


Problem with dependency injection (File::load and \Drupal::service) In order to make a managed_file field permanent I did this in my module configuration form:

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class MymoduleSettings.
 */
class MymoduleSettings extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'my_module_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config                    = $this->config('my_module.settings');
    $form['my_module_title'] = [
      '#type'          => 'textfield',
      '#title'         => $this->t('Title'),
      '#description'   => $this->t("Enter the title"),
      '#maxlength'     => 64,
      '#size'          => 64,
      '#required'      => TRUE,
      '#default_value' => $config->get('my_module_title'),
    ];
    $form['mymodule_icon']   = [
      '#type'              => 'managed_file',
      '#title'             => $this->t('Icon'),
      '#description'       => $this->t("Upload the image file for the icon"),
      '#upload_location'   => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg'],
      ],
      '#default_value'     => $config->get('my_module_icon'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('my_module.settings')
      ->set('my_module_title', $form_state->getValue('my_module_title'))
      ->set('my_module_icon', $form_state->getValue('my_module_icon'))
      ->save();

    // First we just grab the file ID for the icon we uploaded, if any.
    $icon_field = $form_state->getValue('my_module_icon');
    $file_id    = empty($icon_field) ? FALSE : reset($icon_field);

    if (!empty($file_id)) {
      // Make this a permanent file so that cron doesn't delete it later.
      $file         = File::load($file_id);
      $file->status = FILE_STATUS_PERMANENT;
      $file->save();
      $file_usage = \Drupal::service('file.usage');
      $file_usage->add($file, 'my_module', 'file', $file_id);
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'my_module.settings',
    ];
  }

}

but I'm getting warning to use dependency injection principle in this case:

File::load calls should be avoided in classes, use dependency injection instead

and

\Drupal calls should be avoided in classes, use dependency injection instead

I looked through Dependency Injection for a Form but still not sure that I really get it.

Can someone explain me what I need to do in this particular case so I can get a better view on this issue and figure it out?

If you are extending FormBase you can use create to inject dependencies. In this case what I think you want is the entity_type.manager service and file.usage.

  /**
   * Class constructor.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, FileUsageInterface $file_usage) {
    $this->entityTypeManager = $entity_type_manager;
    $this->fileUsage = $file_usage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('file.usage')
    );
  }

See this docs page for more examples.

The create method sends arguments to the constructor, and then you set those to instance variables, and voila, there are your dependencies. Be sure to update your file with the necessary use statements and declare your protected members (entityTypeManager and fileUsage) at the top of the form class.

Therefore, you can remove the static ::service call and use:

$this->fileUsage->add()...

Also, the reason I am passing entity type manager service, is because you would replace File::load with:

$this->entityTypeManager->getStorage('file')->load($id);

If you need more than that object returns, you may need to use a different service but I don't know that off the top of my head.


Limit views exposed filter options to terms with associated nodes of content type X I have a module which limits the options in a views exposed filter to terms which have associated nodes. The code is based on this answer: How can I limit the exposed filters to only display values for which content exists?
Code:
if (isset($form['area-of-law']['#options'])) {

  foreach ($form['area-of-law']['#options'] as $key => $value) {

    if (is_numeric($key)) {
      $query = \Drupal::database()->select('taxonomy_index', 'ti');
      $query->fields('ti', ['nid']);
      $query->condition('ti.tid', $key);
      $nodes = $query->execute()->fetchAssoc();

      if (!$nodes) {
        unset($form['area-of-law']['#options'][$key]);
      }
    }
  }
}

This works, but all node types are returned. I would like to limit the filter further to only show those of content type X.

$query = \Drupal::database()->select('taxonomy_index', 'ti');
  $query->condition('ti.tid', $key);
  $query->join('node', 'n', 'n.nid = ti.nid'); // join node table
  $query->condition('n.type', 'x'); // filter by type
  $query->fields('n', ['nid']); // add filtered nids
  $nodes = $query->execute()->fetchAssoc();


How to make question answer content type with answer as a separate node? I want to create a "question" content type, but is it possible to make the answer a separate node?

Because I want to use Views with user relationships module to show answers to friends or followers.

If you don't want to reinvent the wheel, you should have a look at the Answers module. Here are some details about it (from its project page):

  Answers enables the implementation of a Question & Answer system in a Drupal site. Users can post questions and other users can answer them.

Head over to its project page for more details.

At its core, this module exists of 2 typical content types:

Question.
Answers.

The "Best Answer" submodule can be used so that the question author can "accept" one of the answers as the best one. And you could make the Rules module to either trigger all sorts of subsequent things to happen "when an answer gets marked as best answer", or to add all sorts of validations when posting an answer (or question).

The Answers module comes with integrations with other modules such as the Rules module and the Userpoints module and supports voting.

Demo

Have a look at the (new) demo site of the Answers module. This link shows various menu options within the block with title Answers Menu, i.e.:

Questions (= a view):

All: of all existing questions (= default tab).
Answered: all questions which have a "best" (= accepted) answer (= sub-tab).
Unanswered: all questions which do not yet have a "best" (= accepted) answer (= sub-tab).

Answers (= a view): lists all existing answers for any of the existing questions and which does not (yet) have any submenu options (implemented as tabs).
Rankings (= a view): contains a list of users with their actual ranking (= reputation points implemented via user points), and with each user a link to either the questions or answers from that user.
Ask Question: to post a new question (the equivalent of node/add/question), which is only shown for authenticated users though.

Disclosure: I'm a (co-)maintainer of this module.


Error in file_save() I have a config page in my module were you can upload a file and change a few other settings.  It works fine IF you do upload a new file when you click save however if you don't upload a file and just try to change a setting I get this error:

Argument 1 passed to file_save() must be an instance of stdClass, boolean   given, called

The message references an error in the following piece of code:

function background_audio_form_submit($form, $form_state) {

  // The file is automatically uploaded and saved in the default
  // validation process so you just need to load the file object at this  point,
  // mark that you want to keep it, and save it again.
  // The file ID is contained in the $form_state['values'] array
  $file = file_load($form_state['values']['background_audio_file']);
  file_save($file); <-- THIS IS WERE THE ERROR OCCOURS

  variable_set('background_audio_upload_path', $file->filename);
  variable_set('background_audio_height', $form_state['values']['background_audio_height']);
  variable_set('background_audio_width', $form_state['values']['background_audio_width']);
}

Can I do something like if $file is changed then execute it if it is NOT changed ignore it?    If so how would I do that?

The $form_state array variable contains all the information about the current state of the form. print_r($form_state) to find out the array key corresponding to the upload element in the form. If there is no new upload, this array key should have an empty value, or maybe the array key won't exist at all. If for example $form_state['upload_element'] is populated, then you can call file_save($file);.


d7 link two pages within a (draggable) view by image I'm trying to set up an image gallery that needs to be sortable in D7. So I installed the Views and Draggable-Views modules. Now I have one view with three pages: Gallery, Sort Gallery and Single Image. (Single Image being a view with one larger image and a previous/next link)

All of this works but I can not find a way to link an image in the Gallery-grid to the Single Image view. In the properties of the imagefield I can set up a link, but only to "content" and "file". I need to link that image to that image in my Single Image page. How can I do that?

Any ideas or solutions would be greatly appreciated!!

thanks

I guess you must be taking nid as contextual filter in the single image view
if yes then in your grid view you can rewrite the output for the image field and check the output as link field and link path will be the path of your single image view with nid of current node containing image
Please check the screenshot


Is the AJAX from image fields and multi-line fields breaking my JavaScript? We have added tooltips to our node form using this method: https://inclusive-components.design/tooltips-toggletips/

It includes a JavaScript/jQuery snippet that works perfectly except...

If the tooltip is inside an image file upload, it works, but if you upload an image and that field updates, then the tooltip no longer works.
If the tooltip is inside a multi-line field, it works, but if you add a new item, the tooltip no longer works.

The other tooltips keep working. It's as if those tooltips were removed from the document.querySelectorAll. Would this have something to do with Drupal 8's AJAX updating those fields?

Here is the JS:

(function ($) {

  $(document).ready(function() {
    console.log("dom is ready");
    // Get all the toggletip buttons
    var toggletips = document.querySelectorAll('[data-toggletip-content]');

    // Iterate over them
    Array.prototype.forEach.call(toggletips, function (toggletip) {
      // Get the message from the data-content element
      var message = toggletip.getAttribute('data-toggletip-content');

      // Get the live region element
      var liveRegion = toggletip.nextElementSibling;

      // Toggle the message
      toggletip.addEventListener('click', function () {
        console.log('clicky');
        liveRegion.innerHTML = '';
        window.setTimeout(function() {
          liveRegion.innerHTML = ''+ message +'';
        }, 100);
      });

    // Close on outside click
    document.addEventListener('click', function (e) {
      if (toggletip !== e.target) {
        liveRegion.innerHTML = '';
      }
    });

    // Remove toggletip on ESC
    toggletip.addEventListener('keydown', function (e) {
      if ((e.keyCode || e.which) === 27)
        liveRegion.innerHTML = '';
      });
      // Remove on blur
      toggletip.addEventListener('blur', function (e) {
        liveRegion.innerHTML = '';
      });
    });
  });
})(jQuery);

Note: I know absolutely nothing about AJAX other than it seems to be what's updating the fields's HTML.

Would this have something to do with Drupal 8's AJAX updating those
  fields?

Yes, you need to add

Drupal.behaviors

In order for your Drupal JS code to be able to run after AJAX.

  using the functionality of Drupal.behaviors and once(). If used
  properly this will ensure that your code runs both on normal page
  loads and when data is loaded by AJAX (or BigPipe!)

  Any object defined as a property of Drupal.behaviors will get its
  attach() method called when the DOM has loaded both initially and
  after any AJAX calls.

I suggest you read the Javascript API Overview.

Alternatively, If you don't want to use Drupal.behaviors, I believe if you change all the .addEventListener to .on that will also do.


Trouble adding JavaScript inside a custom module I’ve got a question about module development that I need some help with.

I’m building a module which needs to have multiple JS files connected to it. The first file, which has the same name as the module works just fine.
But the rest of the JS files, attached the same way are being ignored.
For example:

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule.js');
  drupal_add_js(drupal_get_path('module', 'mymodule2') .'/js/mymodule2.js');
}

I’m not sure what I’m doing wrong, if anyone has a suggestion or can point me to some documentation it would be appreciated.

Thanks
Stephanie

It looks like it's due to the second implementation of drupal_get_path().

You're passing through mymodule2 as the argument, where it should just be mymodule.

e.g.

function mymodule_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule.js');
  drupal_add_js(drupal_get_path('module', 'mymodule') .'/js/mymodule2.js');
}

On another note, if the JavaScript needs to be added on every page (as I'm guessing it does with the implementation of hook_init) then you might be better off adding your scripts in using scripts[] in the module's .info file

  scripts (Optional)

  You can now add Javascript in the module's .info
  file if it should be added on every page. This allows Javascript to be
  aggregated in an optimal way, and is the preferred method of adding
  Javascript that most visitors will need on a typical site visit

Source:  Writing module .info files

References:

drupal_get_path(); API Docs

Managing JavaScript in Drupal 7

Writing module .info files


How to add current user field to view field list, when it has no relation to the content? Is it possible to add the current user-id in the rewrite results of a View Field ?

I have created a view of fields of a custom content type "Document". My goal is to rewrite the Document: Title-field to a hyperlink of the following format:

http://mysite.com/download.php?u=[user-id]&docid=[document-fid]

where user-id is the id of the currently logged-in user, and [document-fid] is the id of the file in the records of the view.

I know full well that before you can use a certain field in a rewrite, it needs to be added to the fields list of the view, and it has to be placed before the field you want  rewritten. But here is the problem. When I click "add" in the fields list, I don't see a User, or a User: Current-field.

Please bare in mind that User: Current has absolutely NO relation to the author of the item, or any other user related to the document. Therefor I cannot use the Relationships, under the Advanced section in views.

Please advise.

This is an answer for Drupal 7.

You can

use Views template system and rewrite output of the field (will work only for Views) or
create own formatter for file field (will work everywhere for fields with this formatter) or
alter any file path in hook_file_url_alter (will work everywhere without settings)

I will show how to create field formatter. It will correctly work with standard node rendering, Views, Panels, etc.

/**
 * Implements hook_field_formatter_info().
 */
function YOURMODULE_field_formatter_info() {
  return array(
    // Our own formatter for 'file' field
    'YOURMODULE_file_link' => array(
      'label' => t('Special download link'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function YOURMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  global $user;
  // Now just hide field if user not logged in
  if (user_is_anonymous()) {
    return;
  }

  switch ($display['type']) {
    case 'YOURMODULE_file_link':
      foreach ($items as $delta => $item) {
        // Some title
        $title = isset($item['description']) ? $item['description'] : $item['filename'];
        // Theme link (http://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_link/7)
        $element[$delta] = array(
          '#theme' => 'link',
          '#text' => $title,
          '#path' => 'download.php',
          '#options' => array(
                        'attributes' => array(),
                        'html' => FALSE,
                        'query' => array('u' => $user->uid, 'document-fid' => $item['fid'])
                      )
        );

      }
      break;

  }
  return $element;
}

Add this code to your module (replace YOURMODULE with your module name), enable module, clear the cache if needed. New formatter will be available in Views field settings and in standard content type display settings.


How to extends %module_x/templates/xyz.html.twig? My module has a template which would like to extend another module's template. Is there any shortcut like we have in Symfony2?

{% extends 'path_to_module_x:templates/template-x.html.twig' %}

As of https://drupal.org/node/2143557 (committed January 24, 2014) you can now do this:

{% extends "@node/node.html.twig" %}

Note that the 'templates' directory is automatically included.


How to remove RSS Feed-icon? I am using Drupal 8.1.1. I have made a copy of the Bartik theme and enabled that theme and using that as default theme.
I want to disable the RSS feed-icon. I was hoping to find some control/code in the templates folder to disable the RSS feed icon, but could not find anything like that. (Though there is some reference to feed-icon in theme.libraries.yml).

Can someone suggest how to remove the RSS feed icon in Drupal 8.1.1?
Thanks.

if you don't want to disable the feed, but just remove the icon.

According to FiNeX comment in Disable RSS icon in Drupal 8 via Views > Frontpage

  A better way to remove the icon leaving the RSS feed active is to
  simply disable the feed attachment option.

  1) Structure > Views > Frontpage Edit

  2) Click on "Feed" tab display

  3) Click on "Page" next to "Attach"

  4) Uncheck "Page"

  5) Save

Now if you want to disable RSS, then

According to couturier in Disable RSS icon in Drupal 8 via Views > Frontpage

  Go to Structure > Views > Frontpage > Edit

  Then click on "Feed" at the top. In the second drop-down box, select
  "Disable Feed." Then "Save" the change.


How do I create a directory in webform for uploaded files I wanted to use the 'file' field type in webform for file submission on my website, but I was getting this error message:

  The save directory could not be created. Check that the webform files
  directory is writable.

Any suggestions?

First go to "Administer -> Site Configuration -> File System -> File System Path" configuration page. verify your file path and temp path given no error.

change permissions(writable) to files folder under "sites/default/files".


How to add a local image file to an image field programatically I have serveral image files in the folder /sites/subsite.example.com/files/blog.dir/1/gallery1, and I need to add these files to a node programatically. I think this is the right code:

 use Drupal\node\Entity\Node;
 use Drupal\file\Entity\File;

  $node = Node::load(1);
  $uri = 'public://image.jpg'; <--- this is my problem

  // check first if the file exists for the uri
  $files = \Drupal::entityTypeManager()
    ->getStorage('file')
    ->loadByProperties(['uri' => $uri]);
  $file = reset($files);

  // if not create a file
  if (!$file) {
    $file = File::create([
      'uri' => $uri,
    ]);
    $file->save();
  }

  $node->field_image[] = [
    'target_id' => $file->id(),
    'alt' => 'Alt text',
    'title' => 'Title',
  ];

  $node->save();

What I don't know is how must be the $uri I need to put when my files are in a subdomain directory in a mulitsite drupal installation.

public:// is the Public file system path that you can set in /admin/config/media/file-system.

In your case it would probably be sites/subsite.example.com/files.

To get the image you must then use, public://blog.dir/1/gallery1/image.jpg, where public:// is the same as sites/subsite.example.com/files.


How to customize drupal_mail() error messages How can I customize drupal_mail() error messages? I 've switched off the display of error messages, but this config does not seem to affect to the management of email messages, which insists on displaying the status of the delivery in the navigator screen.

drupal_mail() uses drupal_set_message() to push error messages on mail failure. The only way to suppress those messages is by altering drupal_set_message() output. Depending on the how/why, there's a couple of tacts to take.

One way to do this is a blanket suppression via the Disable Messages module that lets suppress messages based on a few different criteria.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.

Another, more surgical way, is to manipulate the $_SESSION['messages'] variable which contains the array of pending messages to render, following the execution of drupal_mail().


How to include fragment (#) in the URL computed by redirect? I want to redirect the user to an internal path that includes a fragment (the part of the url that is introduced with a #), e.g.:

/comment/19#comment-19

I know how to build the path without the fragment portion. If $cid is the comment id, this will do it:

$this->redirect($comment->permalink()->getRouteName(), array('comment' => $cid));

But how can I add a fragment to the path?

The fragment is stored in the options of the url, also the cid in the parameters. So you'll find all information you need in the url permalink() returns:

  $url = $comment->permalink();

  $this->redirect($url->getRouteName(), $url->getRouteParameters(), $url->getOptions());


How do I add PHP to full nodes? Is it possible to add PHP bits to nodes? I would like to achieve something like this:

Some paragraph I blablabla blablabla blablabla blablabla...

<?php Some PHP code I with echo statements ?>

Some paragraph II blablabla blablabla blablabla blablabla...

Some paragraph III blablabla blablabla blablabla blablabla...

<?php Some PHP code II with echo statements ?>
...

If yes, how can I achieve this?

You would use the PHP Filter, but I would highly recommend AGAINST it as it doesn't restrict anything, and with it, your users could enter things far more "exciting" than just echo statements...


Regarding Filter HTML input option I want to allow one more tag in Filter html Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
<blockquote>.

I want to add <table> in this list. How can I edit this and in which hook I can modify this.

Anyone can help me?

You don't need any hook for this. Go to Configuration > Text formats (path may vary slightly, but it is available in versions 6 to 8) and simply add tags to the list:


Drush command needs higher bootstrap level - Pantheon Drush Alias Setup I just setup pantheon for one of my websites. So far I've done the following and the site works fine:

Version Drush: 5.3
Local Dev: Ubuntu 12.04

Git clone the repo to my local desktop
Copy the pantheon.aliases.php file to the .drush directory at ~/home

Now when i do a drush @pan.chouse.dev pm-list I get the following error.

~/websites/pan-chouse$ drush @pan.chouse.dev pm-list

Command pm-list needs a higher bootstrap level to run - you will need    [error]
to invoke drush from a more functional Drupal environment to run thiscommand.

The drush command 'pm-list' could not be executed.                       [error]
The directory /home/drupalpro/websites/pan-chouse does not contain a     [error]
valid Drupal installation

I also did a drush @pan.chouse.dev status and I get this:

  ~/websites/pan-chouse$ drush @pan.chouse.dev status  PHP
  configuration   :
  /srv/bindings/a59cd0c1631747ef8cda2b5e88fc5124/php.ini
                          /srv/bindings/a59cef8cda2b5e88fc5124/php.ini    Drush
  version       :  5.10.0
  Drush               :
  /srv/bindings/a59cd8cda2b5e88fc5124/drushrc.
  configuration          php

I'm not exactly sure what I'm doing wrong as it should technically work.

While sites on Pantheon don't require a settings.php file in order to serve web requests, due to the fact that database credentials are dynamically injected, they will still need a settings.php configuration file present in order to enable the remote execution of Drush commands. With Drush 5 installed locally, there is unexpected behavior with Pantheon aliases run from inside a local Drupal docroot. In addition, the --strict=0 option needs to be appended to most commands when using Drupal 6 on your local dev environment.

Source: Drush error “Could not find a Drupal settings.php file” or missing system information from status


Provide variable to page.tpl.php to mark page as Access Denied or 404? Ideally I'd like to provide new classes to the body tag such a access-404 or access-denied, but unfortunately I'm not really aware of how to capture these.

I don't mind to identify these pages from the Page Title itself from template_preprocess_page, however it seems that $vars['title'] does not exist in D7? How can I access the page title from within a template_preprocess function?

SOLUTION: Thanks to DeeZone:

In my template.php:

function template_preprocess_html(&$vars){
  $status = drupal_get_http_header("status");
  switch($status){
  case "403 Forbidden":
  case "404 Not Found";
    $vars['classes_array'][] = 'drupal-page-error';
    dsm($vars);
    break;
  }
}

If I uderstand your question perhaps try: Drupal 7 Custom 404 Page Template - use this method to setup a custom page template (tpl) file for your 404 page. This will give you a specific page template that you can hard code classes you're wanting - "access-404" or "access-denied" in the body tag.


Content types do not get listed When I am logged-in as administrator, I click on content, then add content, and I get a message saying I have no content types created, and I must create new ones. In fact, though, I have several content types, and I have been using them for days to build my site.

Do you have any idea on where the glitch is?

It would appear that this is a very good candidate for your issue:

http://drupal.org/node/997444

Assuming you have altered your navigation menu, which many people will do when they are new, you may have inadvertently removed your access. Re-enable this access and you should be good to go. If this does not solve the problem I do not know what it would be.


Drush without SSH access on remote server Following my previous question, I plan to duplicate my website so that I have a production website and a staging site. I am going to have the staging site on a local version on Ubuntu, and it was recommended that I use Drush to keep them synced. Installing Drush locally should be no problem since I will be the full, and only, administrator. However my production site is hosting using shared hosting and the hosting company do not allow access to SSH, I have asked. Is it still possible to use Drush to sync the sites, and if so, how?

If however it is not at all possible, I would appreciate if you could suggest an alternative way of achieving the same thing please.

I'll admit that I'm diving in at the deep end here. I think I pretty much know what it is, however you can't say I'm too familiar with it.

Thanks in advance

Things are pretty rough without shell access.  You'd have to do a lot of work to make this function correctly.  First, take a look at the implementation of the drush rsync command.  You're going to need to build something similar that uses sftp, or whatever your host allows access to, to transfer files.

Next, you're going to want to take a look at the file examples/sync_via_http.drush.inc.  This shows how you can use the Drush sql-sync command, but use an http GET to fetch your database.  Dumping the database and putting it in a location that it can be served up by the web server (securely!) is left as an exercise for the reader.  You also have to make sure that your Drush alias records define the 'database' record for your remote site; if you don't, Drush will try to fetch it via a remote ssh call to Drush on the remote system.

Once you have this, you can use your sftp command to push your code to your hosting site, and drush sql-sync to pull your database to your dev site.  You'll have to run updatedb manually through the admin interface whenever you push new code.

However, you will find that whatever you think it's going to cost you to switch sites, you'll probably find that the cost is worth it in terms of your time savings.


How do I set a validation error on a component inside a composite component? I have a webform with a composite component that allows multiple rows to be added. The structure is something like this, in case that makes it clearer:

webform
  sample_details - composite component which allows multiple 'rows', containing:
    sample_ref
    date_sampled (field I want to set the error on)

I followed 'method 2 - webform handler' on this guide. I'm able to do the validation itself and set an error on other components, but not on sub-components in the composite one.

This post addresses a similar problem, but the technique hasn't helped me.

I've tried

$form_state->setErrorByName( 'date_sampled', $this->t( 'must not have a sample date in the future.' ) );

and

$form_state->setErrorByName( 'sample_details][date_sampled]', $this->t( 'must not have a sample date in the future.' ) );

and a few other things but it seems like I'm missing something. It seems that setErrorByName can't work on sub-components because they don't have a standard #parents array? Is there a way of achieving this without having to switch to 'the old way'?

The element name "sample_details][date_sampled]" specified in the first parameter of setByErrorName is not correct.

It should be

// $key = your multi field array key eg 0,1,2,3
$formState->setErrorByName('sample_details][items][' . $key . '][_item_][date_sampled', $this->t('must not have a sample date in the future.'));

You can find out the exact element name by two methods:

$formState->getUserInput() will give you the exact array pattern to use for setting error by name.
Inspect the element from the browser and use the value of name attribute.


Openlayers Feature Popups I am trying to use the Openlayers Feature Popups module  for my map.

Just ran into some issues which I am yet to find a solution. Under the behaviors tab of the map I have tried to adjust the settings so that the popup can have the name of the node on the popup all I get is a blank popup on click and .undefined on hover.

How do I get the node title and any other field for that matter to show up on the popup just for a starting point at least.

Did you create a Data Overlay with the fields you need in Views? In Views, when you create a Data Overlay that you decide to later use in your map, you define the fields you want to pull from the node (Title, location, etc.) and then assign them inside the Data Overlay dialogue.


Views contextual filter - Contains search with taxonomy field I am searching with taxonomy terms, is there a way to do the search with anything that contains what i am searching for will be returned?

For example if i search Amer nothing will return, but i would like America to return in the results. I know that there is an option when you are just searching by a field, but i don't see it for taxonomy. Does anyone have any ideas??

---EDIT---

I do have the search set as an exposed filter too...

As per my understanding exposed filter works for this requirement. So maybe you can try combining contextual filter with exposed filter.

You can use the Views Filter Harmonizer module for that. Here is a quote about it (from its project page):

  Views Filter Harmonizer solves an operational foible with the Views
  module regarding filtering.

  Normally, when a Views field has been assigned both an exposed filter
  and a contextual filter, then both filters get applied to the View's
  results set -- always. This is not configurable behaviour. It's
  hard-coded.

  As a consequence, contradictory search clauses easily occur, causing a
  counter-intuitive user experience with some White Screens of
  Disillusionment. Since the contextual filter sets the "bounds" for the
  page, any filtering by the visitor through the exposed filter on that
  page can only narrow down the results set, not broaden it. In other
  words the exposed filter appears not to be working properly.

  This small module allows you to have a contextual filter argument
  apply only when there is no corresponding regular (exposed) filter
  value present.

  This is most common on initial page load. After that the contextual
  filters will silently retreat and let the exposed filter values as
  selected by the visitor do their thing without interfering.

  This means that you can take advantage of friendly URLs using
  contextual arguments instead of ugly and verbose query parameters. Put
  the URLs anywhere on your site, in emails and in newsletters to take
  visitors to tailored Views pages. Having arrived there, visitors may
  then further filter these pages to their heart's content using the
  View's regular filters you exposed. And they won't experience any odd
  behaviour.


Good looking contributed themes for Drupal 6 I am looking for good looking contributed themes fro Drupal 6. Drupal.org is filled with themes, although several of them lack support even for the most used modules (taxonomy, search, comment) and many are table based or written through bad and horrible practices.

What I would like to see are modern themes with great typography, grids, good coding practices, based on starter themes, making good use of CSS3 features, supporting other modules. I know it's hard to see a theme with all of those qualities, but try to match at least two of these.

While not definitive, looking at the list sorted by number of installs is probably a good place to start regarding coding standards, and wide support.

Further filtering this list using some of your keywords like 'starter', 'css3', 'html5', etc should help you find what you are looking for.


Is it possible to change the field type in a node form afterwards? I have an instance here where an existing textfield in a node form should be limited to enter only three possible values. I though it might be possible to alter the field to #type => 'select' and attach my '#options' as well. So I altered the form to:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD']['#type'] = 'select';
    $form['field_MYFIELD']['#title'] = 'Enter a value';
    $form['field_MYFIELD']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
  }
}

But when I now try to create a form like that, all I get is this error:

Fatal error: Cannot create references to/from string offsets nor overloaded objects in /Users/Shared/www/drupal.dev/includes/common.inc on line 6606

Is it even possible to change an existing field type like I want with a small custom module? Do I have to alter the submit function then as well? Please help!

The answer is: Yes! It is possible. All I did wrong when altering the form is that I changed the '#type' of the container instead of changing the type of the textfield itself. I had to go one level deeper:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYCONTENTTYPE_node_form') {
    // dpm($form);
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#type'] = 'select';
    $form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#options'] = array(
      1 => 'Value 1',
      2 => 'Value 2',
      3 => 'Value 3'
    );
    // #select doesn't need #size and #maxlength
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#size']);
    unset($form['field_MYFIELD'][LANGUAGE_NONE][0]['value']['#maxlength']);
  }
}


Unable to get the cycle 2 plugin I have installed Views Slideshow module 7.x.3.1.  Also, inside the sites/all/libraries I downloaded the cycle2 plugin.
I placed jquery.cycle2.min.js into the jquery.cycle2 folder, so it is at sites/all/libraries/jquery.cycle2/jquery.cycle2.min.js.

When I tried creating a view using Format : slideshow, I encountered the following error:

  CYCLE OPTIONS You need to install the jQuery cycle plugin. Create a
  directory in sites/all/libraries called jquery.cycle, and then copy
  jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find
  the plugin at http://malsup.com/jquery/cycle.

Even after installing the cycle plugin in the libraries folder, I could not see an option for cycle2.

Along with with views slideshow, I need  pager effect and continuous effect, with vertical effect instead of horizontal effect.

Readme says

1) Assure that you are using Views 3.x. http://drupal.org/project/views

2) Upload/install the Libraries API module. http://drupal.org/project/libraries

3) Upload/install the ctools library. http://drupal.org/project/ctools

4) Create a sites/all/libraries directory on your server.

5) Create a directory within sites/all/libraries named jquery.cycle.

6) Locate/download the jQuery cycle plugin. http://malsup.com/jquery/cycle

7) Upload/install the jQuery cycle plugin: place it inside the jquery.cycle
   directory.
8) Enable the Views slideshow and Views Slideshow: Cycle modules

9) You should now see the new views style option called "Slideshow"

You need to install cycle plugin not cycle 2. Try installing using cycle plugin and follow above instructions.

There is a sandbox module available if you want to use Cycle 2 plugin.

You can download using git commands.

git clone --branch master http://git.drupal.org/sandbox/BenYoung/1832338.git views_slideshow__cycle2

cd views_slideshow__cycle2

Follow the installations instruction in project page for the same.


How can I make db_query SELECT LIKE case insensitive? I'm querying for an email address where I can't force the case of the search term or the data in the table. It's an API thing.

How can I convert this query to be case insensitive?

$results = db_query(
 'SELECT email_address
  FROM email_address_table
  WHERE (email_address LIKE :mail)',
  array(':mail' => '%' . db_like($mail) . '%')
)->fetchAll();

The typical way to accomplish this is to compare a lower-case version of you search string against a the lower-cased variant in the table. See below for an example using strtolower() and LOWER():

$mail = strtolower($mail);

$results = db_query(
 'SELECT email_address
  FROM email_address_table
  WHERE (LOWER(email_address) LIKE :mail)',
  array(':mail' => '%' . db_like($mail) . '%')
)->fetchAll();


Display multiple node edit forms on one page with one submit button Is there a module allowing to edit nodes as a list, like in a spreadsheet, not one by one? For example, display a list of nodes on a page (e.g. 100 nodes) with each node having input boxes instead of displayed fields, or a mixture of both. Each input box is associated with a field, if the field has value then this value is already inserted in the input box and available for editing. After making changes press "Save" and it would update all those nodes with relevant field values. It's like editing a spreadsheet.

This can be done with Views and Editable Fields. You then create a page view with the Editable fields for the nodes and your all set. Keep in mind load times and performance by narrowing down the number of WYSIWYG fields and reference fields.


Difference between #type and #theme in Render API I am reading this theming article http://themery.com/dgd7/advanced-theming/render/manipulate and I have a question.

This article has the following code:

$page['highlighted']['new_stuff'] = array(
'#type' => 'container',
'#attributes' => array('class' => 'my-container'),
);
$page['highlighted']['new_stuff']['heading'] = array(
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => t('Heading'),
'#attributes' => array('id' => 'my-heading'),
);
$page['highlighted']['new_stuff']['list'] = array(
'#theme' => 'item_list',
'#items' => array(
  'First item',
  'Second item',
  'Third item',
),
);

I see that when you provide the #theme property you are telling the Render API to use the theme_item_list, and you pass it the #items variable. But isn't that exactly what you are doing when you set type to #html_tag, you're using the theme_html_tag and passing it variables?

The purpose is a little different:

'#type' is telling to the render API to merge what returned from hook_element_info()
'#theme' is saying to the render API which theme function to use

In the example you are making, the theme function used is theme_html_tag() because system_element_info() returns the following data.

  $types['html_tag'] = array(
    '#theme' => 'html_tag',
    '#pre_render' => array('drupal_pre_render_conditional_comments'),
    '#attributes' => array(),
    '#value' => NULL,
  );

If '#theme' were set to 'tag_html', theme_tag_html() would be the theme used by the render API.


vbo action without selecting row (in other mean all rows) Is there any option available to apply bulk operation on all rows of views result, which means no need of selecting any rows?

A good example is in GMail's Delete all spam messages now which deletes all rows (spam mails) without complaining about row selection.

The closest thing to this is Enable "Select all items on all pages" in Bulk operations settings.

It presents itself as a button to select all items in the view which you select the "select all" checkbox on the current page.

It's not exactly what you describe, but you're not going to get that without custom code to modify VBO.