Display and Modify CSS variable ? (Module) I'm developing a basic module that allows site admin to have the NavBar for mobile and Administration menu for the desktop view.

This can easily be done by adding this CSS.

#navbar-administration {
    display: none;
}

@media only screen and (min-width: 0px) and (max-width: 959px) {

    #navbar-administration {
        display: block;
    }  /* show it on small screens */;
}

#admin-menu {
    display: block;
}

@media (max-width: 960px) {

    #admin-menu {
        display: none;
    }
}

I'm using hook_page_build() to display it on every page. Now I want user to be able to change on an administration page the 960 width which is the default line break to changes menu to their desired value.

My question  how can I display  the default variable value (960) on a text field and it can be modify the css once the number on the text field is been change.

You have many options:

Make a system settings form that stores the value to a drupal variable. Read that value from your (themes) css. Then when that form is submitted in your theme form submit handler have code clears the cache:   cache_clear_all("{$theme}:css:*", NULL, TRUE);. Where $theme is your theme name. The CSS should be re-generated on page load.
I believe the LESS module allows you to easily make CSS variables applied to your files (in Less-3.x or greater for drupal). If you're not currently using LESS, then this is less helpful (pun NOT intended!)

If you make the menu 100% wide inside the div and use jquery resize by dragging it should auto adjust the menu when dragged.

example of div resizing when dragged


How can I make changes to "people" page? Drupal have a list of users with following link - my_site/admin/people
I have some boolean field for every user and I want to show on this page users, who have true value of this field.
How can I manipulate the content of people page.

Easiest way to do this:
enable Administration Views, this would provide you with a view for "/people" page.

  Replaces administrative overview/listing pages with actual views for
  superior usability. Filter users by name, ban/blocked status, or user
  roles.

Use a filter setting boolean field to "true" or expose this filter to allow admins to filter people by "true" or "false"

On url my_site/admin/config/people/accounts/fields you have the possibility to add extra fields to the user account. If you add the field there it will appear on the people page.


No route found for custom REST resource I'm trying to create a custom REST GET resource for a specific node type, and I have the class created and enabled via the REST UI module settings (using the current 1.x-dev release so configs are generated w/o me having to manually create a routing.yml file). For reference, here's the class code:

<?php
/**
 * @file
 * Custom Rest resource for video nodes.
 */

namespace Drupal\video_export\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource for database watchdog log entries.
 *
 * @RestResource(
 *   id = "video_export_source",
 *   label = @Translation("Video Export Source"),
 *   uri_paths = {
 *     "canonical" = "/videos/feed/{site}"
 *   }
 * )
 */

class VideoExportResource extends ResourceBase {
  /**
   *  A curent user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
    * @param array $configuration
    *   A configuration array containing information about the plugin instance.
    * @param string $plugin_id
    *   The plugin_id for the plugin instance.
    * @param mixed $plugin_definition
    *   The plugin implementation definition.
    * @param array $serializer_formats
    *   The available serialization formats.
    * @param \Psr\Log\LoggerInterface $logger
    *   A logger instance.
    * @param \Drupal\Core\Session\AccountProxyInterface $current_user
    *   A current user instance.
  */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }

  /**
    * Responds to GET requests.
    *
    * Returns a list of video nodes to be imported into the target site.
    *
    * @return \Drupal\rest\ResourceResponse
    *   The response containing a list of bundle names.
    *
    * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
  public function get($site = NULL) {
    $response = ['message' => 'Hello, this is a rest service'];
    return new ResourceResponse($response);
  }
}

However, when I access my URL via http://mysite/videos/feed/sourcesite?_format=xml, all I get is this error:

  No route found for "GET /videos/feed/newsbusters"

and my debugger doesn't even hit my get() function. In reading the RESTful Web Services API overview docs it appears that I might be missing the second part of the uri_paths setting in the class annotation. However, the example doesn't make sense to me for my use. if the canonical url is just /videos/export/{site} (where {site} is a parameter), what is the correct second part? Just http://myite.com/videos/export?

Or,

Thanks.

As far as I can see, the REST UI module is just thought to change the content of the YAML files for the REST resources. It is up to the module correctly define the URL to use.

In your case, the annotation of the class should contains:

 uri_paths = {
   "canonical" = "/videos/feed/{site}",
   "https://www.drupal.org/link-relations/create" = "/videos/feed"
 }

I am not sure the placeholder makes any difference, but all the examples use {id}.


How can Drupal be made to serve with root-relative paths? I'm trying to avoid serving pages that load css and js resources through URLs that specify either http or https.  (I'm trying to find a workaround for the problem described in this question, in case a real solution cannot be found.)

Because Drupal is specifying http:// for the href for all the CSS and JS files, when the server erroneously switches to https, as described in the aforementioned question, the browser seems to be ignoring all these files, and I get an unstyled page.

Instead of

<link type="text/css" rel="stylesheet" href="http://www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

(etc.)

I'd like to serve

<link type="text/css" rel="stylesheet" href="/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

or even

<link type="text/css" rel="stylesheet" href="//www.example.com/sites/default/files/css/css_pbm0lsQQJ7A7WCCIMgxLho6mI_kBNgznNUWmTWcnfoE.css" media="all" />

Can I make Drupal serve URLs that don't specify protocol?

You can use a template process (YOUR_THEME_process_html) hook to rewrite all resource urls (js and css) using a regular expression.

Here is an example which transforms all http:// or https:// to //:

function YOUR_THEME_process_html(&$vars)
{
    foreach (array('head', 'styles', 'scripts') as $replace) {
        if (!isset($vars[$replace])) {
            continue;
        }

        $vars[$replace] = preg_replace('/(src|href|@import )(url\(|=)(")http(s?):/', '$1$2$3', $vars[$replace]);
    }
}

We had that same issue with a website we were developing and could not come to a resolution on why some of the paths would be https while others would be http.  The work around, which you may not like the answer, was to use the Pathologic module which turns everything from an absolute to relative so your forms would use a /path-to-form instead of http://www.whatever.com/path-to-form.


How do I add multiple custom CSS classes to Views rows? This is a kind of follow up to this question:

I have a view where I added taxonomy tags as custom CSS class for rows of a unformatted list:

I did that using Replacement Pattern [tags] as row class.

The problem is that I need to filter by tags and so every taxonomy tag should be added as a separate class. I would need spaces instead of - so the output would be something like that:

Is this possible with Views GUI or do I have to use Views preprocess function?

if you're using multivalue class token, this bug report may be of interest for you. There's also a patch as a workaround available.

  Currently if a views field token contains multiple space-separated class names, these classes will be combined into one class when the string is run through drupal_html_class(). Attached is a patch to split token classes before they are sanitized for HTML.

Under "Format" in the left column of the view, you click on "Settings" near the format you choosed, for example "Unformatted list".

In the popup you can edit the row classes.


How to display user form and hide some fields? I'm building a website which has a member section. People subscribe and complete the "user" form (username, email, password and some other fields).

For an additional fee, they can be part of the "dating" part of the website, where they can meet new people.

After paying, I would like them to complete a form about them (height, eyes, etc.). Those fields are already in the user form.

I'm displaying the user form this way :

global $user;
module_load_include('inc', 'user', 'user.pages');
return drupal_render(drupal_get_form('user_profile_form', $user));

How would i go about hiding some fields that I don't want them to see/modify?

Thanks!

You should alter the form before rendering it.

$form = drupal_get_form('user_profile_form', $user);

// Uncomment this line to inspect the structure of the form array (needs devel module)
//dpm($form '$form');

// hide field.
unset($form['field_name']);

return drupal_render($form);

I would implement hook_form_alter() and perform modifications there. The advantage of doing it in the form alter hook is that these changes will be applied whenever that form is requested (such as on other pages where you may also want to call it), and not just a single spot.

Additionally, don't use unset() to remove form elements, as other modules may depend on them being present, which will cause errors. Instead, set the element's access to FALSE:

$form['element_name']['#access'] = FALSE;


How to update/change anonymous author to authenticated current user upon logging in? This is the case:

Anonymous user can create nodes
Anonymous user will leave their email address
Anonymous user must register with the same email to "claim" the contents they created
When that user logs in, the contents with anonymous author but same email address will update then the author will change from "anonymous" to current user.

I created a rule:

I've read some posts that I just need to add events on rules, there are no "AND" "OR" to events then rules will trigger that event but I noticed that it doesn't trigger the event "user logged in".

I tried testing this rule. changing Action, setting the value of author to ="1" ("admin") and removing condition of data comparison.

It does change the author to "admin" when saving new content either logged in or not.

When I saw that was working I returned the data comparison for the email.

Then If a user with the same email address logged in it does not change/update the author.

I tried placing the when user logged in first before the event after saving new content, as a result  I wasn't able to use the [node:etc] on comparison and action. I also tried creating a rule with just one event = "User logged in". same result, I can't find the necessary token/arg I need.

Is there something wrong with my settings? Anyone here could point me to the right direction and steps?

Thank you very much!

Try using the trigger 'after saving a new user account'.  You don't want to check for content every time they log in, just when they create an account that matches email addresses with those node.

For security purposes you should probably prevent people from being able to change their email address too or they might somehow steal someone else's content.

As for people who create content when they already have an account but are not logged in: create a rule that checks for accounts when a new node is saved.  So in summary:

New users should claim existing content when the 'after saving a new user account' is triggered.
New content by existing users (that are not logged in) should be automatically claimed by the user account upon saving the node.

Neither of these events require you to check when a user logs in.

I used the updated Anonymous Publishing in the end.


User Reference For a Particular role I am using Drupal 7 . and in a content type i created a field with user_reference,  which is working fine.

And while creating a content it shows all users.

Now i want to show  only User with particular role..

Does anybody tell me how to do this. Is there is any module avialable for this

I would use the Entity Reference module (rather than user reference). I would then create a view (display: entity reference) filtering only Users with that desired role.

In the field settings you can choose the designated View under "Entity Selection" - "Mode": "Views: Filter by an entity reference".

This is at least how I solved this problem in the past. I hope this helps.

For User Reference Module, In Field settings -> already roles are defined know..  User roles that can be referenced


Displaying a list of all the content types I need to display a list of all the content types which links to their respective page, displaying the contents of that type.

I tried a bunch of wild guesses like $row->content and couldn't manage.

How should I achieve this?

I have done something similar using Views and the Summary option for Contextual filters.
I added the Content Type as a contextual filter with the following options:

The end result was a view that displays the following, if you have not specified a Content Type in the URL as an argument:

The only issue I found is that I won't display Content Types that have no content.

create a view for every content type that lists all the contents of that type. now create a web page and make a link for every view.


Rebuild images from image style I have an image style in Drupal 7. I attached several images to a nodes and display the images based on this style. I then changed the effects on this image style but the existing images are not being recreated with the new image style effects. They show with the old image style effects.

If I attach new images, they use the new effects. Deleting an existing image and re-uploading causes the image to use the old effects.

The manual (incorrectly I assume) states that just saving an image style causes a rebuild:
http://drupal.org/documentation/modules/image

I have cleared the cached.

How do I force a rebuild?

Clearing cache, won't flush image styles: http://drupal.org/node/997332

You could:

delete them manually
use image_style_flush
use the command line: rm -rf sites/default/files/styles
use drush: drush image-flush

if u have a custom template and wanna force style for an image field :

 $style='full_content_width';
 $path=$node->my_img_field['und']['0']['uri'];
 $style_url = image_style_url($style, $path);
  print "<img src=".file_create_url($style_url)." >";


Change text in Commerce Kickstart "order total" dynamically I want to change the label in the attached image, that is from Commerce Kickstart. I need to change that text depending on the role of the user.

If the user has role1 then the text will be "order total" & if user has role2 then the text should change to "Quote total". Any idea?

I tried to debug with Devel to see where to change the label but I could not find it.

You can use the hook_commerce_price_formatted_components_alter()
The following example checks if VAT has been applied to the order total and changes the string accordingly:

/**
 * Implements hook_commerce_price_formatted_components_alter().
 *
 * Alters somes text at the checkout form
 *
 * @param $components
 * @param $price
 * @param $entity
 */
function mymodule_commerce_price_formatted_components_alter(&$components, $price, $entity) {
  $pieces = explode('/',current_path());
  if(!isset($components['tax|ch_vat']) && $pieces[0] == 'checkout'){
    $components['commerce_price_formatted_amount']['title'] = t('Order total (excluding VAT)');
  }
}

One way would be to implement hook_entity_view_alter() in a custom module of yours.

<?php
/**
 * Implements hook_entity_view_alter().
 */
function YOURMODULE_entity_view_alter(&$build, $type) {
  switch ($type) {
    case 'commerce_order':
      /**
       * In here implement your alter logic
       */
      break;
  }
}

To determine what exactly to alter, after the 'in here...' comment you can use debug($build); or dpm($build); (if devel installed).

To see the user roles:

global $user;
debug($user->roles);

Similar issue here.


How to set a mini panel to display node fields? I want to load node fields into a mini panel, but when I do what I think that I need to do, the mini panel (= MP) is invisible (because the fields aren't displayed, I guess).

So far I have:

Added a Content Type
Added fields to that Content Type
Created a Minipanel with Required Context = Node
Added my various Node Fields to that MP: Add Content > Node > Field: ___
Moved the MP into my Content range in the Blocks Editor

I don't see my MP anywhere. This user seems to have a similar issue, and solved it with the Context settings but doesn't answer the question at all, just closed it.  Other people seem to have this issue as well:

Can't get a mini panel containing node form fields into a panel page
Node fields and node tokens not showing up in a mini-panel

Can anyone clarify for me how to make my MPs show up with information populated from the node?

As per Beebee comment, you should first try removing the "Node" required context and see if that renders the block. Make it work at the most basic level possible and then add various customisations and contexts.

While you can have nodes in block, you can put it in your panel.

nodeblock
nodesinblock
nodeasblock


Update core keeping other composer packages After upgrading Drupal to the last version with Drush (8.1.15) the other composer.json dependencies (e.g. drupalconsole) are removed.

Are there any way to update Drupal with Drush keeping other composer dependencies?

diff --git a/docroot/composer.json b/docroot/composer.json
index 6089861..b9536cf 100644
--- a/docroot/composer.json
+++ b/docroot/composer.json
@@ -4,28 +4,11 @@
     "type": "project",
     "license": "GPL-2.0+",
     "require": {
-        "ckeditor/fakeobjects": "4.6.2",
-        "ckeditor/image": "4.6.2",
-        "ckeditor/link": "4.6.2",
-        "codemirror/codemirror": "5.27.4",
         "composer/installers": "^1.0.24",
-        "drupal/console": "~1.0",
-        "jquery/geocomplete": "1.7.0",
-        "jquery/icheck": "1.0.2 ",
-        "jquery/image-picker": "0.3.0",
-        "jquery/inputmask": "3.3.7",
-        "jquery/intl-tel-input": "12.0.0",
-        "jquery/rateit": "1.1.1",
-        "jquery/select2": "4.0.3",
-        "jquery/timepicker": "1.11.11 ",
-        "jquery/toggles": "4.0.0",
-        "jquery/word-and-character-counter": "2.5.1",
-        "progress-tracker/progress-tracker": "1.4.0",
-        "signature_pad/signature_pad": "2.3.0",
-        "wikimedia/composer-merge-plugin": "~1.4"
+        "wikimedia/composer-merge-plugin": "^1.4"
     },
     "replace": {
-        "drupal/core": "~8.3"
+        "drupal/core": "^8.4"
     },
     "minimum-stability": "dev",
     "prefer-stable": true,

I've seen that there is a composer project for Drupal but I'm not using it in this project.

If you have a composer based project, you probably should use composer to update it.  E.g.:

composer update drupal/core --with-dependencies

Make sure to keep the composer.json, composer.lock, and docroot/vendor/composer/installed.json files in your repository.

Note:  It's best to go 'all-in' with composer and use it to add and maintain modules as well as core. E.g.:

Add new module:   composer require drupal/module

Update module:  composer update drupal/module --with-dependencies

To manage patches, see the cweagans/composer-patches project.

You can also include various 3rd party libraries (e.g. chosen, colorbox, and the like) using your composer.json file.


Contextual filters taxonomy name I'm adding a contextual filter to a view for a custom content type that has a taxonomy field. The contextual filter allows me to filter by the taxonomy tag id but not by the taxonomy tag name. Meaning with the given tags in the taxonomy:

1  | test1
2  | another tag
3  | taggy
......
99 | coolness

I can generate a contextual filter that will parse a URL like http://mydrupal/myview/3 to display all content that has been tagged with taggy BUT, the URL needs to pass the argument to lookup by tag name instead of tag id, e.g., http://mydrupal/myview/taggy to view all content tagged with taggy How can this be accomplished?

I assume you've added the Content: Has taxonomy term ID contextual filter. You can use taxonomy term names with this filter by adjusting Specify validation criteria settings. here's a screenshot:

Make sure Specify validation criteria is checked and you should be presented with more options. Under Validator choose Taxonomy term. You can optionally select with vocabularies to allow. Under Filter value type choose Term name converted to Term ID and check the Transform dashes in URL to spaces in term name filter values checkbox.

Another way to skin the cat:

I needed the actual taxonomy term name query not converting to term ID.

Here is how to query the taxonomy term name that was passed as a contextual filter:

  To get the name you must add a relationship, either on the field or
  the generic taxonomy relationship. Then you can add any fields for
  that term as a contextual filter, including the name.

  https://www.drupal.org/node/1156022#comment-4469378


How can a field be rendered as a  element? The problem:

I would like to be able to manage custom <meta> elements, on a per-item basis in a custom theme. An example would be for adding open graph and schema tags, but I'm really looking for a generic solution.

I'm aware of custom modules, such as Meta Tags, but I'd rather avoid relying on other modules at this point.

What I've Tried:

After looking at them_field it looked as though I should create a custom theme function for my custom field (field_test being used for this example). The theme function could add a <meta> tag and not return any content to be rendered.

In template.php:

<?php
//I *did* actually use my theme name instead of THEMENAME
function THEMENAME_field__field_test($vars) {
    drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');

    //I figured this would prevent the field from being rendered inline
    return '';
}

Using that code the custom <meta> element was correctly added to the <head>. Nevertheless, the field was still rendered on the page.

If I changed the output to:

return ' ';

The content was no longer rendered to the page, but an unnecessary space character would be output where the field was to be rendered.

Is there a better way to render a field as a <meta> element?
-or-
How can I prevent this themed field from rendering inline?

try to return drupal_add_html_head array directly

<?php

function THEMENAME_field__field_test($vars) {
    return drupal_add_html_head(array(
        '#tag' => 'meta',
        '#attributes' => array(
            'content' => drupal_render($vars['items'][0]),
            'name' => 'test'
        )
    ), 'test');
 }


How can I get the user ID from an order? How can I get the user ID from an Ubercart order?

use Drupal\uc_order\Entity\Order;
$order_load = Order::load($order_id); //Load Order
$ownerinfo = $order_load->getOwner(); //Fetch Owner Info
$ownerID = $order_load->getOwnerId(); //Fetch Owner ID
$ownerEmail = $order_load->getEmail(); //Fetch owner email

$connection = \Drupal::database();
$query = $connection->query("SELECT uc_orders.order_id AS order_id, users_field_data_uc_orders.uid AS users_field_data_uc_orders_uid FROM  {uc_orders} uc_orders LEFT JOIN {users_field_data} users_field_data_uc_orders ON uc_orders.uid = users_field_data_uc_orders.uid");
$result = $query->fetchAll();
foreach ($result as $record) {
  if($record->users_field_data_uc_orders_uid != 0){
     $user = \Drupal\user\Entity\User::load($record->users_field_data_uc_orders_uid); // pass your uid
     $name = $user->getUsername();
     if ($name) {
        $user->addRole('attandee_role');
        $user->save();
     }
  }
}


How to avoid "An illegal choice has been detected" when updating select list values via ajax? I have four entity reference fields to user entity in a form. Host form is node edit form.
Three of them are select lists, last is Inline Entity Form.

After adding a user entity via IEF I'm trying to update select lists values:

function ebep_users_feature_users_list_ajax($form, $form_state) {

  $ief = array_shift($form_state['inline_entity_form']);
  $options = array('_node' => t('- None -'));
  $commands = array();

  foreach($ief['entities'] as $data) {
    $options[$data['entity']->uid] = $data['entity']->name;
  }

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = $options;
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

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

It works, but when I try to add another user via IEF I am getting:

  An illegal choice has been detected. Please contact the site
  administrator.

--- Original answer. Is wrong, check update below.

Just set

$bla['#validated'] = TRUE

On the select that will be updated with AJAX.

Checkout "Illegal Choice has been detected"

--- Update 17 Dec 2019 ---

Actually that was not good advice, that was a long time ago, now I know better.

Ajax callback function is supposed to only return the piece of form that has changed or some ajax commands.

In this case form modification must be made on the form function or a form alter hook. Form building and validation functions are run each time an ajax callback is called. Just check $form_state on your form build or alter function and adjust values accordingly.

See Resolve the error "An illegal choice has been detected..."

In your ajax callback, add:

...

drupal_get_messages();
form_get_errors();

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

As a security precaution, the core _form_validate() function checks if an element's #options key has changed from what what was set in the original build (which they have). By calling drupal_get_messages() and form_get_errors() we basically tell Drupal to ignore any errors/messages while running our ajax request. :)


Views grouping rows case-sensitive, I need to ignore case I have a view which groups rows in a table according to the first letter of the title. Some of the letters are uppercase and some are lowercase. View treats the upper and lower case as separate groupings (see image attached) but I want them to be grouped case-insensitively.

I've checked my db tables are ci and I've tried to alter the query using hook_views_query_alter but haven't managed to find a solution yet.

Thanks

In Drupal 8, this can be done pretty effortless thanks to Twig.
Just override the output of the grouping field with its value plus Twig's built-in uppercase filter (|upper or |capitalize), see screenshot:

Quick and easier way.

If you are using views PHP field, Then convert required field to uppercase using strtoupper() function right there.

Then group views result by this converted PHP field.


Updating node title inside Rules Action I am creating a Rules Action that will update the node title after it is created.

Here is my code, but when I try to create new content using Postman, it keeps loading. I dont get response in Drupal logs.

...
class ContentTitle extends RulesActionBase {

  protected function doExecute(EntityInterface $entity) {

    $entity_id = $entity->id(); // Getting dynamic entity ID
    $controller = \Drupal::entityManager()->getStorage('node');
    $node = $controller->load($entity_id);

    $title = $entity->label();
    $item = $node->get('field_xyz')->value;
    $new_title = "Title is " . $title . $item;

    \Drupal::logger('custom_rules')->notice('new_title: ' . $new_title);

    $data = array(
      'type' => 'custom_content',
      'title' => [
        'value' => $new_title,
      ]
    );
    $node = Drupal::entityManager()
      ->getStorage('node')
      ->create($data);
    $node->save();
  }
}

Im getting the expected output in the logger.

I dont think I am setting the title in $data properly. Any suggestion is greatly appreciated. Thanks!

You can set a node's title with the "Set a data value" action - you don't need to write your own action. I'm going to assume that you're putting this into your own action because there are other things you want to do that you haven't mentioned or because you are learning how to write an action - if this is ONLY about setting the title then I don't see the point of a custom action.
Problems with the approach and the partial solution given in the initial post:

You don't need to get the entity ID then load the entity from
storage, because Rules is already passing you the loaded entity.

You're using entity instead of node, which wrong - Nodes have
titles, Entities in general DON'T.

You're hardwiring in a title taken from a specific field 'field_xyz'.
Instead, you should pass in a string variable which holds the title.
That way the Rule configuration can get the value out of 'field_xyz'
or out of 'field_nlm' or from a thousand other places - writing the
action with a string parameter will make it far more useful.

The EntityManager has been deprecated since Drupal 8.0 and should not be used. You should be using EntityTypeManager instead. But as I said in #1, this isn't even needed.

You don't have to save the node, Rules will handle the saving
automatically.

This really only requires one line of code (plus some boilerplate code, like all plugins...). Here's a complete solution that takes two context variables:

The node to change.
The title to use.

namespace Drupal\my_module\Plugin\RulesAction;

use Drupal\node\NodeInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Sets the title of a content item.
 *
 * @RulesAction(
 *   id = "rules_node_set_title",
 *   label = @Translation("Sets the title of the selected content item"),
 *   category = @Translation("Content"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node",
 *       label = @Translation("Node"),
 *       description = @Translation("Specifies the content item to change."),
 *       assignment_restriction = "selector"
 *     ),
 *     "title" = @ContextDefinition("string",
 *       label = @Translation("Title"),
 *       description = @Translation("The new title.")
 *     ),
 *   }
 * )
 */
class NodeSetTitle extends RulesActionBase {

  /**
   * Executes the action with the given context.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node to modify.
   * @param string $title
   *   The new title.
   */
  protected function doExecute(NodeInterface $node, $title) {
    $node->setTitle($title);
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    // The node should be auto-saved after the execution.
    return ['node'];
  }

}

You can create node like below also:

use \Drupal\node\Entity\Node;

class ContentTitle extends RulesActionBase {

  protected function doExecute(EntityInterface $entity) {
    $entity_id = $entity->id(); // Getting dynamic entity ID
    $controller = \Drupal::entityManager()->getStorage('node');
    $node = $controller->load($entity_id);
    $title = $entity->label();
    $item = $node->get('field_xyz')->value;
    $new_title = "Title is " . $title . $item;
    \Drupal::logger('custom_rules')->notice('new_title: ' . $new_title);
    $node = Node::create([
      'type' => 'content_type',
      'title' => $new_title,
    ]);
    $node->save();
  }
}

In your code "title" should be only $new_title not in the array as value. Even your code also looks fine except that title. I didn't any try of your code but I am suggesting to use above one.


How to specify the correct private file path in a block I have a Drupal site at http://example.org/xyz

Per the instructions here, I have set up a private file directory outside the web root.

So let's say the web root is at /home/public_html/example/xyz
The private directory is at /home/public_html/private

I have that private directory set in the settings.php file and cleared the caches. It shows up correctly here: http://example.org/xyz/admin/config/media/file-system

After clearing the cache, I can indeed confirm there is a valid .htaccess file in /atrium/admin/config/media/file-system

The directory permissions for the private directory are 755.

So now I specify the file location of a link in a block as "/xyz/system/myfile.pdf"

When I click the link, the home page simply reloads (instead of a download window), but the URL now reads:
http://example.org/atrium/system/myfile.pdf

I've tried many other variations, and they all fail.

What am I doing wrong?

drupal will not let you specify a direct link to a private file

If you upload the file using file field (core) then you can use views to display the file in a block using block display and use https://www.drupal.org/project/private_files_download_permission for fine grained permissions on who can download the file

if you want to program this behaviour then you have to look at using file_create_url in a custom module

$fid = 1; //set fid to your file's fid.
$downloadlink = file_create_url(file_load($fid)->uri);

and this link will hide the actual path where you private file is

for more details you can look at

How can I get the URL to the public files directory?

https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_create_url/8.2.x

first of all you must create a private fille in filles filles/private
then create another  private fille not in public_html but in home : /home/private


generate or extract a automatic thumbnail for a video file using Video module in drupal 7 I need to show a video thumbnail of a video file which the admin upload using the video module.

I have a content type called MEDIA.I have created field as with following settings.

   LABEL             NAME           FIELD   WIDGET           OPERATIONS

   Upload Videos    field_video Video   Video Upload    edit    delete

Here The following setting I have set for the Upload videos label

         UPLOAD VIDEOS FIELD SETTINGS

These settings apply to the Upload Videos field everywhere it is used.

    Number of values: 1

   Upload destination
   Public files:checked

Enable auto video conversion:checked
 Convert videos automatically using FFmpeg or Zencoder. You can define presets at preset        settings to automatically convert videos to web compatible formats eg. FLV, MP4. Make sure   to configure your transcoder settings to make this work properly.
Video thumbnails
Automatically extract thumbnails from video (with fallback to manual upload):checked

  If you choose Automatically extract thumbnails from video then please make sure to      configure your transcoder settings to make this work properly.

Here I have checked the Automatically extract thumbnails from video  check box and I have saved it.

I have configure the transcoder  setting as follows.(I am working on windows XP)

  Video transcoder
    FFmpeg:checked
  Select a video transcoder will help you convert videos and generate thumbnails.

    Zencoder is unavailable: The Zencoder API module has not been setup properly.
   PATH TO FFMPEG EXECUTABLE
    FFMPEG:C:/xampp/htdocs/newsite/ffmpeg/bin/ffmpeg

   Absolute path to FFmpeg executable.When you install a new FFmpeg version, please clear the caches to let Drupal detect the updated codec support.
   VIDEO THUMBNAILS
    Path to save thumbnails:videos/thumbnails

    Path to save video thumbnails extracted from videos.
    Number of thumbnails:5

    Number of thumbnails to extract from video.
    Save all thumbnails in {file_managed} table
    Save all auto-created thumbnails to the {file_managed} table. Change file status as PERMANENT

Then I created a new media article where i upload the video from my system and But what happens the video thumbnail is not extracting from the video which I upload.

Can anyone help me.Please forgive me for my english

Are there any messages in your Drupal error log related to video transcoding? Also, try to update to the latest version of the Video module.


Insecure content warning with D7 and SSL I'm running Drupal 7 with Drupal Commerce module. I have SSL enabled on my server. I've confirmed that the SSL is properly enabled (If I replace Drupal's index.php with a simple index.html, Chrome allows me to browse to my domain via https).

I'm getting a bunch of error messages like this:

  The page at https://example.com/ ran insecure content from http://www.example.com/sites/default/files/css/css_TsVRTbLFUpEZAfw-_bWPJu840QT523CPjUVJ5MRWfyk.css

There are about 20-30 of these errors - mostly .js and .css files, some .png etc.
Questions:

How can I configure d7 so that it accesses these files via relative paths
Are there any other workarounds here, to enable https on my drupal install?

Much thanks in advance.

Simply remove $base_url from your settings.php file; Drupal will detect $base_url automatically.

If you must set this value explicitly, you can add a little conditional logic to your settings file, such as:

if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://example.com';
}
else {
  $base_url = 'http://example.com';
}

$base_url=''; worked for me, but note that bootstrap will puke on it, and needs the following change:

/var/www/includes/bootstrap.inc

if (isset($base_url)) {

//change to (should be this way anyway?):

if (isset($base_url) && $base_url!='') {


Live content migration to a separate server for important content My clients are now spending a lot of money daily on creating content on my system. A few hours lost could be quite bad for them, and in turn, for me.

Most of the site is fine on daily backups, but there is a content type I'd like to offload onto a backup server when nodes are created or updated. Is this possible? Preferably sending a node object and related files.

I haven't had an issue in a long time but I'm feeling the stress with their investment.

With the Backup & Migrate module installed, navigate to: /admin/config/development/backup_migrate/schedule to create & manage database or site file backup schedules:

Note that there are options to backup the default Drupal database, all of the site files, or just specific Drupal file directories.

Under "Settings" there is an admin section to configure the destination address for the backups at: /admin/config/development/backup_migrate/settings/destination

Schedule a complete site backup daily with hourly database backups. The Backup & Migrate developers have the NodeSquirrel service available for offsite backups - but this service only works with the D7 module & is unavailable for D8 currently.

With cPanel, there are better options available now with cPanel Backups & Backup Tool:

If you need a more professional backup service, look into Veeam.


Best method to enable/disable modules depending on the environment What would be the best solution to enable/disable modules depending on the site environment (dev, stage or production)?

Created a database dump containing the system table for each installation. Then when deploying I use mysql -uuser -ppass database < dump-<type>.sql where the type reflects the kind of environment.
Created a shell script for each environment, that uses drush to enable or disable needed modules and set specific site settings.
Wrote a small deploy script for each site that looks something like this:

// change working directory to drupal installation path
chdir('public_html');

// define root, include bootstrap.inc and start drupal
define('DRUPAL_ROOT', getcwd());
require_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// modules that should be disabled/enabled on stage site
$modules = array(
   'field_ui' => 1,
   'toolbar' => 1,
   'update' => 1,
   'overlay' => 0,
   'feeds_import' => 0,
   'feeds_ui' => 0,
   'feeds' => 0,
   'menu' => 1,
   'advanced_help' => 1,
   'job_scheduler' => 1,
   'wysiwyg' => 1,
   'views_ui' => 1,
   'dblog' => 1,
);

// enable/disable modules and set site specific variables
foreach ($modules as $module => $state):
  if ($state == 1):
    if (!module_exists($module)):
      module_enable(array($module), FALSE);
    endif;
  else:
    if (module_exists($module)):
      module_disable(array($module), FALSE);
    endif;
  endif;
endforeach;

variable_set('error_level', ERROR_REPORTING_DISPLAY_ALL);
variable_set('preprocess_css', 0);
variable_set('preprocess_js', 0);
variable_set('cache', 1);
variable_set('page_compression', 0);
variable_set('block_cache', 0);

Does anyone have a better solution?

One possible answer is the Environment module (the 7.x dev release works just fine). It allows you to define arbitrary environments (comes configured with "Development" and "Production", but you can have more if necessary). It then provides drush environment-switch to switch between environments. You can then implement hook_environment_switch() to do anything you want when the environment is switched. There's no built-in support for enabling and disabling modules, but that's easy enough to do in code, as you demonstrate above. It's also convenient for doing things like changing variable values and blocking development users.

You then put something like drush environment-switch production in your deploy steps.

This also has the benefit of being able to switch back to Development easily. For instance, I have views_ui disabled in Production, but enabled in Development. If I need to urgently check a view in the ui on the production site, I can switch the environment to Development, do what I need, and switch back.

It's also nice that since it's implemented in hooks, you can keep different types of functionality in different modules, and you can keep these things in the code base and under version control.

For Drupal 7 you can use Tadaa

  Tadaa! is a module aimed at simplifying the process of
  enabling/disabling modules and altering configuration when switching
  between different environments, e.g. Production/Staging/Development.

  The environments and the corresponding configuration is completely
  configurable.


Drupal and its modules kept in two different subfolders -- possible/how? New to Drupal... I was wondering if it was possible to install it with the core and the modules kept in separate folders, rather than in a hierarchy. A bit like with WordPress, so to speak:

/.htaccess <-- site is here, in /, and in git
/drupal    <-- Drupal core, pulled as a git submodules
/content   <-- plugins and themes, each pulled as git submodules

I'm guessing it's possible, but the installation manual and a bit of googling (skeleton, subfolder, enterprise, etc.) led me nowhere. If so, I could use a pointer to get me in the right direction. If not, will it be possible with Drupal 8, which unless I am mistaking is using Symfony components?

install it with the core and the modules kept in separate folders, rather than in a hierarchy

In short, no.

Drupal must be able to expect to find files in a certain location, and that is not dynamically configurable. The very first line of code Drupal executes is define('DRUPAL_ROOT', getcwd());, and file wise, most things are based on that constant.

Symfony, and PSR-0, doesn't inherently change that. PSR-0 only defines the directory structure around files, not where to find them. With that said, I haven't looked in enough detail at D8 to know if there's a simple way to alter where the autoloader looks for files.

If your filesystem (and webserver) supports symlinks, you can work around the problem by symlinking the appropriate directories in place.

try and make a link and see if it works. I have done that for files in drupal and it should work for modules too.


Computed Field not showing I want to use the computed field in my drupal 8 website to calculate the charges for a parking system where I calculate the charge for a vehicle by taking the date of collection minus the date of parking, multiplying by the charge per day. total-charges=(collection-paking)*charge-per-day. However, even before I do the calculation, I tested to see if the computed field is working by assigning the $value='hello' and the assign the $disply_output=$value but its not being displayed in the content of the node together with other fields. Other things done to try to resolve this issue

Change the data type from varchar to text to int and others
Change the settings in the 'manage display' option of the content type. From toggling sanitize on an off, change display of the computed field from above to inline, etc
Resave the node by clicking edit and then saving the node, and even creating a new node of that content type after adding the content field.

Still not working.

After googling, most common solution, which works for drupal 7 guys is to uncheck the option to save the field in the database. But I dont see that option in drupal 8 so that I can uncheck it. Because I do not want to store the value in the database since It changes everyday a vehicle is not collected, so all I want is to calculate the value on the fly and charge the vehicle owner when collecting the vehicle.
How do I make the computed field even display a simple 'Hello World'?

I think it must be a bug, since the computed module is in alpha for drupal 8 at the time of this writing. With the help of Matt, we were able to print a simple 'hello' message by manually creating a new node. This new node will have access to the new computed field. I was using the devel module to generate content for nodes, which for some reason did not have access to the computed field. So if you are experiencing the same problem, set up your computed field, and then manually create a node, or edit and resave a node your previously created manually. That worked for me.

You just need to resave existing data and computed field value will be shown and saved


Display Rate module results via Panels So many of us know that the Rate module does not smoothly integrate with Panels.

I discovered out a way to get the voting widget to show using a custom content with the following PHP code:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print rate_embed($node, 'bias', RATE_FULL);
}
?>

Has anyone had any luck with doing something similar to display only the vote results (i.e. display total percent of that vote)?

I'm not a PHP wizard, but I think there is way by doing something like the following.

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && ($node = node_load(arg(1)))) {
   print get_rate_resluts($node, 'bias', RATE_FULL);
}
?>

But end up getting either blank pages or some fatal database errors. Thoughts?

Update:
I think I figured out that I need to create a custom content to print the output after reading it here. Tried this:

$block['content'] = rate_get_results('bias', $nid, $widget_id) $output['rating'];

But it looks like it does not do anything which is better then seeing a blank page.

print rate_embed($node, 'NAME', RATE_FULL);

Replace NAME with the machine name of the widget; the view mode can be RATE_FULL, RATE_COMPACT, RATE_DISABLED, RATE_CLOSED, RATE_COMPACT_DISABLED.


How do I enable the PHP filter only for webforms? How do I enable the PHP filter only for webforms, and not other content types?

I suggest is in your custom module add more description to your field that user enter php code with Not surround it with<?php ?> then in your submit handler that runs before other submit handler ( add it with array_unshift) use php eval then put your returned data in your field.

  Eval :mixed eval ( string $code ) eval — Evaluate a string as PHP code

  code

Valid PHP code to be evaluated.

The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is

  still possible to leave and reenter PHP mode though using the
  appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon.

  'echo "Hi!"' for example will cause a parse error, whereas 'echo
  "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain

  visible after it terminates.

  Return Values ¶

  eval() returns NULL unless return is called in the evaluated code, in
  which case the value passed to return is returned. If there is a parse
  error in the evaluated code, eval() returns FALSE and execution of the
  following code continues normally. It is not possible to catch a parse
  error in eval() using set_error_handler().


How to query the last 5 nodes of multiple content types? I want to query last 5 nodes of multiple content types, say, typeA, typeB, typeC, typeD.

It was originally only one content type, and I did it using EntityFieldQuery:

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'typeA')
  ->propertyCondition('status', 1)
  ->propertyOrderBy('created', 'DESC')
  ->range(0, 5);

$result = $query->execute();

But now I need to include 3 other content types to the list.

Is there any way to expend this query to include the last 5 nodes of the other 3 content types as well. So that the result will have 5 last nodes from all 4 content types, altogether 20 nodes.

Or should I do it with 4 individual queries?

I think the only thing you need is alter the second line of your EntityFieldQuery to this:

->entityCondition('bundle', array('typeA', 'typeB', 'typeC', 'typeD'), 'IN')

Haven't tested this particular though, but you can query multiple content types this way.

Cheers

EDIT: Maybe this can help you more: https://www.drupal.org/node/2048345

the best way you can do it is to user db_select();
I would do something like this:

Set the array with the content type machine names.

$arrayofnodetypes = array('page','post','poll');

here you select the table

$query = db_select('node','n');
$query->fields('n',array('nid','title','status','type')); // this are the fields your want to fetch
$query->condition('n.status','1','='); // node is published
$query->condition('n.type',$arrayofnodetypes,'IN'); // this is where you call the content types.
$query->orderBy('created','DESC');
$query->range(0,20);

$results = $query->execute()->fetchAll();

Then you have 2 options.

the first:
if you want to fetch all fields in the node, you need to manualy join the fields in the $query see the following resource if you want to learn more: https://www.drupal.org/node/1848348

the second:
the $results variable will have the results of the query.

I would then foreach each result of the array.

like the folowing;

$nodes = array();
foreach($results as $item) {
  $nodes []= node_load($item->nid);
}

then the $nodes array will contain the results you need.


How to get image url in a twig file from a media entity Normally I am able to get an images url by setting the display setting for that field to url and then writing something similar to this in order to print the url

  {{ content.field_image.0['#markup'] }}

However this is not possible in the display settings for a media entity, the only options are -

Rendered entity
Entity ID
Thumbnail
Label

So my question is how to get the url from the image, as I need to use the field as a background image so can't just render it out as normal.

With Twig Tweak module (2.4+) it can be done like this:

{{ node.field_media|file_url }}

I have actually found a way to do this myself that doesn't involve writing custom code. It requires this module Image URL Formatter

This module adds a url formatter for image field. Then you can output image url directly.

Create a view mode for your media and.. I called mine Image URL
Go to your media type and edit the display settings, you will need to expand custom display setting to turn your new view mode on.
Now edit the display for this view mode by clicking on the new tab that should of appeared, and for your image field change the format to Image URL.
If you were using this media in a paragraph or a node you would go to the display settings for this and under your media field set the format to rendered entity and the View mode to 'Image URL' or what ever you called yours.
You will need to create a custom media template file for your field to remove the outer HTML.

I also needed to render my field as follows in my paragraph template file

  {{ content.field_image|render|striptags|trim }}


Which host do I need to fill in the database connection? So I have made a local Drupal site and now I'm moving it to my webhost. In the database connection array:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => 'localhost',
);

So I filled in all my credentials (driver, database, username,...) but what do I need to fill in after 'host'? Can I just leave it 'localhost' or do I need to fill in the host of my webhosting?

It will depend on your hosting setup and where the DB is located. The host value can be:

A reachable hostname where the PHP code is running (e.g. localhost for your local server)
An IP address (e.g. 127.0.0.1, the ip address normally used for localhost),
A fully qualified domain name (e.g. my-data-base-host.example.com)

Consult your hosting provider on retrieving your DB host connection credentials.

In the host, you need to add your host IP Address like:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'drupaldb',
  'username' => 'username',
  'password' => 'secret',
  'host' => '111.111.111.111',
);


How do I create hierarchical select for state, district, city, and location using AHAH? I have a site for Indian tour places where I need to add the information for the "Location" content type.
For example, in http://www.indiantourplaces.com/andhra-pradesh/hyderabad/hyderabad/saroornagar-lake-51.htm we have the information for the location "SAROORNAGAR LAKE" which is located in India (country), Andhra Pradesh (state), Hyderabad (district), Hyderabad (city). I want to create all the above state, district, city as different nodes, and when I add the location details, I want to first select the state; then another list box will be populated with the list of districts which are present in that state, and once the district has been selected, another list box will be populated with the list of cities present in that district.

I am stuck up with this from may days.

It seems Hierarchical Select does exactly what you need.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

  Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

Ajax Chain Select Module can certainly help for exactly the same problem. It can work for n number of levels where you can make the next field options dependent on the previous field selection.

This module can only be used by programmers as it requires the implementation of callbacks for the field options.

Here is the link: https://www.drupal.org/project/ajax_chain_select


How to redirect to another page after submitting the ctools modal form Actually i want to redirect to some other page after submitting the multistep ctools modal form .I have tried using form_state['redirect] and drupal_goto in submit function but didnt work.

function get_quote_menu(){

$items=array();
$items['get_quote'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'get_quote_form',
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
$items['get_quote/%ctools_js/details'] = array(
  'title' => 'Get Quotation',
  'page callback' => 'quote_ajax_details_form',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'type' => MENU_CALLBACK,
);
return $items;
}
function quote_ajax_details_form($js = NULL, $step = NULL){

if ($js) {

    ctools_include('modal');
    ctools_include('ajax');
 }
  $form_info=array(

    'id' => 'quote_details',
    'path' => "get_quote/" . ($js ? 'ajax' : 'nojs') . "/details/%step",
    'show trail' => TRUE,
    'show back' => TRUE,
    'show cancel' => TRUE,
    'show return' => FALSE,
    'next callback' =>  'get_quote_details_next',
    'finish callback' => 'get_quote_details_finish',
    'cancel callback' => 'get_quote_details_cancel',

    'order' => array(
        'start' => t('View the plans and premiums best suited to you <br/>in 4 straight forward steps.'),
        'second'=>t(''),
    ),

    'forms' => array(
        'start' => array(
            'form id' => 'get_quote_start',
       ),
       'second'=>array(
            'form id'=> 'get_actual_quote_details',
       )
    ),
);

$object_id = 1;

if (empty($step)) {
// We reset the form when $step is NULL because that means they have
// for whatever reason started over.
get_quote_cache_clear($object_id);
$step = 'start';
}

// This automatically gets defaults if there wasn't anything saved.
$object = get_quote_cache_get($object_id);

$form_state = array(
'ajax' => $js,
// Put our object and ID into the form state cache so we can easily find
// it.
'object_id' => $object_id,
'object' => &$object,
);

ctools_include('wizard');
$form = ctools_wizard_multistep_form($form_info, $step, $form_state);
$output = drupal_render($form);

if($js){

$commands=array();

if($output===FALSE  || !empty($form_state['complete'])){

  $commands[] = ajax_command_html('#ctools-sample', finish($form_state['object']));
  $commands[] = ctools_modal_command_dismiss();

}else if(!empty($form_state['cancel'])) {

    $commands[] = ctools_modal_command_dismiss();

}else {

     $commands = ctools_modal_form_render($form_state, $output);
}

 print ajax_render($commands);
 exit;
}else{

 return $output;

 }
}
 function get_quote_start($form, &$form_state){
            $form['first_name'] = array(

'#title' => t('Your Name'),
'#type' => 'textfield',
'#size'=>20,
'#default_value' => $form_state['object']->first_name,
'#attributes'=>array(
    'placeholder'=>t('First Name'),
    'id'=>array('quote-first-name'),
),
//'#required'=>true,
);
$form['middle_name'] = array(
'#type' => 'textfield',
'#default_value' => $form_state['object']->middle_name,
'#size'=>20,
'#attributes'=>array(
    'placeholder'=>t('Middle Name'),
    'id'=>array('quote-middle-name'),
 ),
//'#required'=>true,
);
 return $form;
}
 function get_quote_start_submit(&$form, &$form_state){

global $user;

 $form_state['object']->uid=$user->uid;
}
function get_actual_quote_details($form, &$form_state){
$form['adults']=array(

    '#type'=>'select',
    '#title' => t('Adults'),
    '#options'=>array(
        1=>1,
        2=>2,
        3=>3,
    ),

 );
return $form;
}
function get_actual_quote_details_submit(&$form, &$form_state){

    // Not working redirect
       // drupal_goto('node/add/page');
        $form_state['redirect]='node/add/page',
}

This is a bit old, but hopefully it'll help someone. Down where you write your commands[] array. Change it to something like this. In the submit function of one of the earlier forms I set the redirectpath parameter on the object, then i just use that in ctools_ajax_command_redirect() after calling the dismiss modal function ctools_modal_command_dismiss().

  // If $output is FALSE, there was no actual form.
  $commands = array();
  if ($output === FALSE || !empty($form_state['complete'])) {
    // Dismiss the modal.
    $finish = _aap_main_add_finish($form_state['object']);
    $commands[] = ctools_modal_command_dismiss();
    ctools_add_js('ajax-responder');
    $commands[] = ajax_command_html('#ctools-sample', $finish);
    $commands[] = ctools_modal_command_dismiss();
    $commands[] = ctools_ajax_command_redirect($form_state['object']->redirectpath);
  }
  else if (!empty($form_state['cancel'])) {
    // If cancelling, return to the activity.
    $commands[] = ctools_modal_command_dismiss();
  }
  else {
    $commands = ctools_modal_form_render($form_state, $output);
  }

I recommend you strongly to use rules  module. there is no need to programming, simply add event and action and it works great.


Custom formatting of tokens for date fields In D8.1, I have created a field called field_date and added it to a content type.

I try to use pathauto to try to configure a URL pattern for the content type like type/year/title. But the token browser does not expose expandable date options for date_field. If I enter it manually, I get "The Path pattern is using the following invalid tokens: [node:field_datetime:custom:Y]."

How can I format the output of a token for a date field, the same way I can for a node property like date created?

I've searched the issue queues for contrib token, core datetime and core token system, but I find nothing about this.

The Token module added direct support for datetime and daterange fields in December 2016. See https://www.drupal.org/project/token/issues/2786181.

You should be able to use something like [node:field_datetime:date:custom:Y]

Another option is to use:

[node:field_[YOUR-CONTENT-TYPE]_date:0:date:custom:Y]


How do I remove container div from a specific view? I have tried for a few days now, to figure this one out on my own, but have had next to no luck getting a working solution.

The issue:
I have a view that displays a list of images, where all wrappers have been removed, so that it only contains the images themselves. I have also overwritten templates for this view, so that any additional wrappers from templates are also removed.

The issue is that views automatically adds <div class="views-element-container"> around the entire views. Normally this would be fine, but I have no need for it for this view, it's just cluttering the markup.

I know that it in some cases is used for additional functionality, such as the contextual links, but this has also been disabled for this view.

What I have tried:

I have tried to figure out if views also adds a template suggestion to container.html.twig, but sadly found no indication anywhere on what that might be (even if I used normal views template naming convention, it didn't override)
I have tried to access the views render array in a preprocess function, to unset #theme_wrappers, in hopes that this would prevent views from using the container. Sadly this also didn't do anything. Code example below.

function rodekors_preprocess_views_view__paragraph_gallery(&$variables) {
  unset($variables['view_array']['#theme_wrappers']);
}

I simply want to remove the wrapper div from my specific view, yet have found no information on how to do that.

Does anyone know how to achieve this? Preferably without having to install a module for what should be such a simply thing to do.

I was only able to solve this after much hair-pulling regarding Drupal not picking up my suggested template. Where I was hung up was that the template suggestion must start with container__ otherwise Drupal will ignore the file and use the next template in the suggestion list (likely the default container.twig.html).

Here is my code:

/**
* Implements hook_theme_suggestions_user_alter().
*/
function myTheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  // A list of view names in which to exclude the container markup.
  $exclude_views = [
    'someView',
  ];

  if (in_array($variables['element']['#name'], $exclude_views)) {
    $suggestions[] = 'container__no_wrapper';
  }
}

I then added container.html and container__no_wrapper to my theme at templates/container/.

if($variables['element']['#name'] = 'view_name') { // value from

should be

if($variables['element']['#name'] == 'view_name') { // value from

AND

$suggestions[] = 'suggested_template';

should be

$suggestions[] = 'suggested__template';

:)


How to get user id of order from order entity metadata wrapper I am implementing hook_commerce_cart_line_item_refresh(). It will be receiving line item and entity metadata wrapper for the commerce order.

How can I get user id of order from its metadata wrapper without loading user object like this

$uid = $order_wrapper->owner->value()->uid

With above line it will be loading user object. I would like to avoid loading user object and simply take uid directly.

Following line does not work:

$uid = $order_wrapper->uid;

Or should I think of loading order object? As it might be already in static cache.

Thanks

It's the same as any property on a metadata wrapper:

$uid = $order_wrapper->uid->value();

  Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with

$order = $order_wrapper->value();

Correct answer is:

$uid = $order_wrapper->author->uid->value();


Résumé upload functionality in Drupal 7 Is there any module available in Drupal 7 for getting a résumé uploading functionality? I need a form with a couple of text fields and a file upload field that accepts files of .doc, .odt, and .docx formats. My requirement is to send an email also with the attachments, and also see the list of submitted résumés.

Add a Résumé content type. Add your text fields and a file field to this content type. Set your permissions accordingly, allowing whichever user roles you want (or anonymous) to create this content.

This will allow people to upload their resumes.

Get the Rules module and create a rule a bit like follows

Events

Node - After saving new content

Conditions

Node - Content is of type:  Résumé

Actions

System - Send mail

You can use Token to put content fields into the email, but I'm not sure if you can put links to the file.  If not, you can at least put a link to the content that contains the file.

Lastly...use Views and create a simple view that shows Résumé content -From here, get  sorted however you want.

For extra points, you could also use the Flag module to flag résumés (e.g. follow up, spam, not useful and so forth), and then create more views based on those flags (so you can only see useful résumés for exampleetc).

thats baked into d7 core already. just add a filefield and specify the file types.


Change permission on Content Overview page I have granted an admin 'Administer Content' permission under People->Permissions. This gives him the ability to publish/unpublish nodes. But I don't want him to be able to go to the Content overview page where he can delete and unpublish in bulk. This is because I have setup certain workflow rules with node_validate which only let him delete or unpublish nodes under certain conditions within the node edit screen. If he goes to the Content overview page, he can circumvent the workflow logic.

So how do I programmatically take 'Administer Content' permission away when he goes to the Content overview page? I still want him to be able to see the Content overview, but I don't want him to be able to unpublish, delete, or do any of the other bulk operations.

Any thoughts would be appreciated.

This is such an old question, but I had the same question and hiding it in css is not the answer.

The correct answer IS to enable the Actions permissions (VBO) (actions_permissions) module.  That will allow you to set which roles can perform bulk operations.

I am pretty sure there isn't a way to accomplish this.

Maybe you could use css and hide the Edit Options field set like this:

#edit-options {
  display: none;
}

That would hide it, but if he was malicious he could edit the CSS in his browser and then use it.


Iterate through all children of an element I have a Drupal code below:

function myid_create_template($form, &$form_state){
    $form['myid_templates_editor']['#access'] = TRUE;
    foreach (element_children($form['myid_templates_editor']) as $child1)   {
        $form['myid_templates_editor'][$child1]['#access'] = TRUE;

    }
    return $form;
}

This code iterate to the first child only of an element, but not the child with degree 2 or more. How will I iterate it to all child/grandchild of the element?

A simple recursive function will do the trick:

function allow_access(&$root_element) {
  $root_element['#access'] = TRUE;
  foreach (element_children($root_element) as $key) {
    allow_access($root_element[$key]);
  }
}
allow_access($form);

I believe you will have to manually add support for 2nd/3rd/etc. levels.

Didn't test the code, but this should point you in the right direction:

function myid_create_template($form, &$form_state){
  $form['myid_templates_editor']['#access'] = TRUE;
  foreach (element_children($form['myid_templates_editor']) as $child1) {
    // Check if this element is a parent of another element.
    if (count(element_children($form['myid_templates_editor'][$child1]))) {
      foreach (element_children($form['myid_templates_editor']) as $child2) {
        if (count(element_children($form['myid_templates_editor'][$child1][$child2]))) {
          foreach (element_children($form['myid_templates_editor']) as $child3) {
            // You can continue to search for more levels here, if necessary.
          }
        }
        else {
          $form['myid_templates_editor'][$child1][$child2][$child3]['#access'] = TRUE;
        }
      }
    }
    // This is just a regular element.
    else {
      $form['myid_templates_editor'][$child1]['#access'] = TRUE;
    }
  }

  return $form;
}


How do I theme the user profile page? What is the best / easiest way to theme the user profile page? I'm building a talk radio website and registered members will provide news articles publically avail. eventually there will be thousands of registered users.

I'm worried that I will figure out an answer that works but isn't correct and will force me to go back and rewrite later on.

I don't know if I should use views or just straight code the page-user.tpl - if I straight code,  what function gets the uid from the /user/xx url? if I use views how do I assign the view to the pages in /user/xx

For some reason I cannot find any complete info on this; either it's a great secret or I'm missing something really simple. thank you!

I would suggest you to use Panels and Views modules and optionally Profile2.

You will add some fields to user account or to the user profile if you installed Profile2. Then enable the 'User profile template' page under admin/structure/pages and add a panel variant, select a layout and place the content or fields. If you have Profile2, then you need to add it as a relationship 'Profile2 from user' under the 'Contexts' menu of the panel page. I'm not going into details about how to use panels.

To display the summary of user's recent activity, you should setup a view with a contextual filter of user id, preferably a 'Content pane' display, then you need to place this content pane into you user panel.

It is not a great secret how to build a user profile page, but it's completely dependent of what you want to have. If you have any difficulties implementing the steps I wrote, you can update your question or post another more specific question.

I decided to use a combination of VIEWS and template overrides, hooks, css and custom PHP.


Is there a way to place the "Add new comment" link where I want? Is there a way to place the "Add new comment" link where I want in my content type? I'd like the link to be between two already existing fields in the content type. Is there some type of way to add this link via a field? Please help. This issue has been killing me.

You can use hide and render to hide/show individual fields.
http://tjegz.wordpress.com/2012/03/02/132/

This will allow you to place things in any order in the tpl file


Can I remove/hide the "Provide a Menu Link" checkbox when creating new content type? I am creating a site where authenticated users (not too computer savvy) will be entering in data to the content types we create and the "Provide a Menu Link" may cause them too much trouble.  Is there a way to remove or hide this option when I create my custom content types?

In drupal 7, go to edit your content type and in the tabs at the bottom there should be 'menu settings'. If none of the checkboxes under 'Available menus' are checked, then the option of creating a menu item is not displayed when creating content of that type.

If the users do not have the rights to add new menu items, the option should not be visible to them.


Creating a page to display several content types I have a website to build that requires several quite long pages, each containing several sections with quite different content in each.

A content type for each page isn't going to work as some sections would need to contain several entries, to be displayed as a slider.

So, I think, I need to create each section as a different content type and my problem becomes displaying several of these on the same page?

How can I display several content types on the same page?

Or maybe I could create a category for each page and add the types to those?

The Views module might help you for this purpose. It is highly configurable, and it allows you to display several items on a single page. Other modules can add functionality, like the Views Slideshow module.

Learning how to use Views takes some time, but there are many Views tutorials available in the web. A possible starting point might be this one:

https://dev.acquia.com/blog/a-totally-beginner-tutorial-to-views-for-drupal-7/22/01/2016/9576

Views module is what you need.

Edit:

With this module, you can customize the presentation of the content (and different content types) of your Drupal site in many different ways on a single page and in many other ways. The fact that the module is so flexible, it can be assumed as "advanced web based query builder" and hence also makes it that confusing and complex at the same time.

It can take some time to grasp the whole concept of views as the other answer illustrates, however you can start using it to fit your simple needs in no time. You can follow some tutorials and make use of it in no time. The link that the other answer has provided looks like a good place to start. Here's one more.


Styling label of a select list I want to style the label of my select list with bold font and give it some color.

This is the code for rendering form which I am using in a hook_block_view

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'City',
    '#options' => $options_first,
    '#prefix' => '
',
    '#suffix' => '
',
    '#default_value' => $selected,
    '#ajax' => array(

      'callback' => 'get_citylocations_dropdown',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

The #prefix and #suffix is wrapping entire select list and effecting/applying the select list which is not I want. I just want to style the City to something likeCity

Its not working as I expected.

How do i do it?

Not sure why you insist on using Form API for this, but form element labels are rendered in theme_form_element_label(). You may want to override that function in your theme's template.tpl.php file to produce the desired markup.

You have to do the styling using CSS, something like .classname label{ font-weight:bold; color:#FFF; } . Refer here.


Code showing on every content page I'm pretty new to Drupal but have take my company's half-baked site from the server and gotten a working instance of it in my local wamp stack working.  The only problem is that it seems on every page there is a section of code being inserted:

<?php
if ( isset($entity->field_job_id['und'][0]['safe_value'] )) {
   $job_id = $entity->field_job_id['und'][0]['safe_value'] ;
   $application_link_form = '
<form action="/careers/application" method="POST">
    <input type="hidden" name="job_id" value="' . $job_id . '" />
    <input type="submit" value="Apply online" class="job-application-link" />
</form>';
   print $application_link_form;
}
 ?>

This is showing a section of this code plus an "Apply Online" button at the top of each section of content.  It doesn't seem to matter what the content type of the content and the site which I imported all the files and db from has no such code - not even when I view source is there anything even commented out.  Hopefully this code gives you some context as to where this is ocurring - it comes immediately following this series of divs:

In any case, I cannot figure out where to find this code in order to get rid of it.  I'm not seeing any modules relating to this, etc.  And I just am baffled as to why it would start showing up after importing from a site that doesn't display this.  If anyone can think of any possibilities, please let me know!

If it's not in the source, it's in the DB. At a guess, this is code that someone entered using the PHP filter, but the PHP filter is not active so it's showing up as text.

As to where it is in the DB, there's many possibilities. I'd use brute force to search the DB in its entirety. (That's easy for me to say as I have a copy of SQLyog to hand. I'm sure there are other tools that provide this functionality, though: I think PhpMyAdmin has it.)

Addendum: looks like it's in a custom pane, so the table panels_pane is the most likely culprit. Ideally you want to find how it's getting inserted onto the page. Do you have the module Panels Everywhere enabled?

As Alfred says, it's going to either be in the code or the database.

If you have the sql data dump, you can open that in a text editor and search for the code.

The fact that it's found here in your html

... leads me to think that it's a block within your content region that's injecting this code.

Go to Admin > Structure > Blocks and see what blocks are enabled in the content region, try disabling them.


Clear a single url from cache Using Drupal's standard cache system, is there a way to clear the cache for a node or url without clearing the entire cache (which slows down the whole site)?

The module Cache actions provide very fine grained control over your cache clearing.

Unfortunately, whether it will solve your exact problem depends on how this particular url is built up. In case it doesn't do exactly what you want, it's codebase would still be an excellent start for building more exactly what you need.

cache clearing stuff can be done simply by downloading drush module from
http://drupal.org/project/drush

terminal->your drupal directory

write the command drush cc

It would return you with

[0]   :  Cancel
 [1]   :  all
 [2]   :  drush
 [3]   :  theme-registry
 [4]   :  menu
 [5]   :  css-js
 [6]   :  block
 [7]   :  module-list
 [8]   :  theme-list
 [9]   :  registry
 [10]  :  views

So you can select which ever thing you want to clear..

If you want to do clear cache from the drupal website then you could install and enable the module http://drupal.org/project/admin_menu
It provides a home icon on your drupal sile and would give you a menu list where you could go for cache clear stuff....


Drush is updated but not usable in Drupal 8 in Windows Is this a bug? I've the version that does support Drupal 8, so what is actually the problem here?

Update

I followed kiamlaluno and seem to have updated Drush but I still get the same error. I haven't touched the settings.php file. It's a totally brand new site so I would still get an error :\

You need drush 8 for drupal 8. You have drush 7 installed.

Please, use as simple as:
composer require "drush/drush:^9.0"
in folder within composer.json


How to hook "/system/ajax" with javascript in Drupal 7 When a field accepts multiple values, the admin form adds a button "Add another item". Mousedown submits a POST to /system/ajax to get another field (i'm using multifield here).

I'd like to hook into the javascript completed event to do some custom handling on those additional fields.

How can I most easily hook these ajax calls for javascript callback and reference to the block being added? Is it possible without PHP?

You can use hook_menu_alter and define your own custom callback function like below.

function demo_pane_menu_alter(&$items) {
  $items['system/ajax']['page callback'] = 'demo_pane_taxonomy_autocomplete';
}


How to show the product "add to cart" button on a product kit? I would like to add a "add to cart" button on a product kit, for each product in the product kit. How may I achieve that? I have been searching for a while now. Ubercart 3.

This would be similar to iTunes when viewing an album, the user may buy a single song of the album. Currently with product kit, the user has to click the product link to get to the song then be able to buy it.

Drupal has a number of modules that make "add to cart" and other similar features of Drupal commerce work, by simply enabling those modules.Check out the following links:

Commerce Line Item Cart Form
This link may also help- Cart Modules


How to override some text in the login form located in a block put on a panel? I create a subtheme base on bartik theme.

Then I create a panel, and put the user login block to the panel.

I want to change some text in the default user login from.

I find the theme suggestion about how to override block: block--[region|[module|--delta]].tpl.php

So I try to create block--user--login.tpl.php, And try to type whatever word to this file:

111

when I visit the login form, still default, not changed.

I try to clear cache, can not work too.

EDIT:

I paste the follow picture for better explain.

the 111 is a login form block in page, the right form is a login form block in a panel.

this is my block--user--login.tpl.php file

This sounds like a job for hook_form_alter() and it can be used from either a custom module (eg, MODULENAME_form_alter()) or in this case probably more easily from your theme, eg, something along these lines inside your template.php file:

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {

  switch ($form_id) {

    case 'user_login_block':

      // drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');  // uncomment to see what you have to work with

      $form['name']['#title']='Enter UserID here'; // originally "Username or e-mail"
      $form['pass']['#title']='Enter Secret here'; // originally "Password"

      break;

    // other form ids go here

  }

}

The above (after clearing caches) will turn this:

into this:

If you need to change other text in the form, you can uncomment the drupal_set_message() and look in the form to see what you have to work with and change it appropriately.

ADDITION:

If you want to get rid of both of the links, eg, the Create new account and Request new password you can either do:

unset($form['links']);

or set the access to them to FALSE, eg:

$form['links']['#access']=FALSE;

Lots more information about this can be found in the Drupal Form API Reference.  I would look into the #weight key for changing the position/ordering of elements in the form.

is this what you want to do?

then you need to go to your website then right mouse click and then click view source. then search for user-login-form you need to copy all the code where the form starts and ends onto the block--user--login.tpl.php file

for example block--user--login.tpl.php contains:

<form method="post" id="user-login-form" accept-charset="UTF-8">

  I just edited this, woo*
 <input type="text" id="edit-name" name="name" value="" size="15" maxlength="60" class="form-text required" />

  Password *
 <input type="password" id="edit-pass" name="pass" size="15" maxlength="128" class="form-text required" />

Create new account

Request new password

<input type="hidden" name="form_build_id" value="form-_elpq-7B19Scnbgk13TZtp9YWCcANc-rDYCWcHPuihI" />
<input type="hidden" name="form_id" value="user_login_block" />

<input type="submit" id="edit-submit" name="op" value="Log in" class="form-submit" />

</form>

Pros: You don't need to know PHP nor how to create a custom module. (The noobie approach).

Con: If you change theme's you will need to make a copy of this template and put it in your new theme's template folder.

Counter the con: There might be some other (views, blocks, nodes?) templates that also need to be moved if you change themes, since this is in the /sites/all/themes/yourtheme/templates folder, you will likely not forget to move it with the others? Therefore, this approach is not as bad as people may think.

Don't get me wrong, the accepted answer is the better approach, if you have the knowledge that is.


Use email to validate post, not unlike craigslist I'd like for anonymous users to be able to post nodes to my site. By default their post is unpublished, but when they submit it, the site sends an email with a verification URL. When they revisit the site with that URL they can then publish their node.

Call this the 'craigslist model.' :-)

Restating: I want users to be able to publish their own node anonymously, by linking out of an email.

I've been unable to find a module or setting that does this, and I thought I'd ask before diving into code.

Update: Found this unmaintained Drupal 5 project: Anonymous publishing.

Similar question: How can anonymous users be allowed to post while still maintaining content integrity?

You can use the Rules module, but you'll have to write a custom rule to grab the email from the submitted node and send a verification link to the email address. You could also do this with a custom function through hook_entity_insert().

For the verification link you could do use drupal_hmac_base64() to create a url-safe hash of the content of the post or of the node + timestamp + email or something like that.

Then you can create a custom menu to fire a callback function that takes arguments from the verification link to publish the node if the verification link is correct.

You could use the Rules module for this: When a user posts a node, an email with a link to the node is sent to the admin, or a user role that you want to revise the node.

Using this method will save you much time than diving into code.


D7 - How to get mlid value from path of menu item Quick question. How to get mlid value from path of menu item. There is a function called menu_link_load() but it requires an mlid value, but I need something exacly the same function using path.

There's no build-in function for this. You can use menu_tree_all_data(), but it returns all the menu. After that you can compare in loops your path with the paths returend. But there is a better and easier answer. Here it is:

$mlid = array();
$q = 'your-path';
$menu_info = db_select('menu_links' , 'ml')
  ->condition('ml.link_path' , $q)
  ->fields('ml', array('mlid', 'plid'))
  ->execute()
  ->fetchAll();

foreach($menu_info as $key => $value) {
  $mlid[] = $menu_info[$key]->mlid;
}

Try using menu_get_item(), this should load your menu item directly from your path.


Why is it sometimes $node->field_name[0], and sometimes $node->field_name['und'][0]? Sorry for the code in the title, I couldn't think of a clearer way to ask it.

I have several nodes of the location content type, and a view outputting teasers of those nodes. I want to do some custom stuff in node--location.tpl.php to affect the teasers everywhere they're displayed. When I do a simple dpm($node) to get at the variables, some field values are not always in the same place.

For instance, I have field_phone that just has identically formatted phone numbers. For the first node in this view, that field is structured as $node->field_phone['und'][0]['safe_value']. But for the second node, it's simply $node->field_phone[0]['safe_value'].

I know that und has to do with translations, and perhaps means "undefined". I'm not doing anything with translations or localization or languages on the site, so it's not like this node is any different from other nodes that way.

What causes this, and is there a function or something that can help me test for and get at the value easily, or do I have to roll my own?

EDIT: Chris Rockwell below points out field_get_items(). This seemed to solve my problem on the site I was working on the other day. But now, on a different site, it's failing for exactly the reason I bring up here.

I have a view that outputs three nodes. For some reason, when I dpm($node) in the node--node-type.tpl.php file, I get six variable dumps. The first one has $node->field_link_image['und'][0], while all five others — INCLUDING the duplicate of this same node — just has $node->field_link_image[0]. And now, field_get_items() is silently failing and returning false on those last five nodes.

So I go back to my original question: What causes this difference between some node variables and others, and what can I do about it?

The lack of the 'und', or LANGUAGE_NONE level data seems to indicate that the field has lost the ability to be translated. I've never encountered such a field.

field_get_items() as already pointed out is the canonical way to safely retrieve field data. Any fields that don't work with field_get_items should be considered broken.

I would hazard a guess that you either

Have a broken contrib module that re-arranges field data and doesn't know better than to sometimes remove the language level.
Your field settings have just broken somewhere along the way. Potentially because of a reason similar to above.

Does the problem keep happening on newly created fields?

Can you reproduce on a clean install?

If you take a look at this https://api.drupal.org/api/drupal/includes%21bootstrap.inc/constant/LANGUAGE_NONE/7

this is a safer value to use and will work for any defined language, including no language.


"The website encountered an unexpected error. Please try again later." error show on cache clear My Drupal 8 site is working fine but when I am clearing the cache then my site display below errors.

    The website encountered an unexpected error. Please try again later.

Please suggest me what is the problem ?  I have checked status report and it shows the error below

I was also getting the same error. The reason is given in the error message,i.e. Drupal is not able to find the specified controller. In my case, in the routing yml, the controller's path is "hello_world\Controller\HelloController", whereas my HelloController.php file was contained in the hello_world\src folder instead of the required path (**hello_world\src\Controller** folder).

My hello_world.routing.yml contents

hello_world.content:
 path: '/hello'
defaults:
 _controller: '\Drupal\hello_world\Controller\HelloController::content'
_title: 'Hello World'
requirements:
_permission: 'access content'

this work for me:

update script in settings.php i.e $settings['update_free_access'] = TRUE;
and then run { website url}/update.php

Note: After running update.php set 'update_free_access' to FALSE.


How to grant permission to FileSystem.php file I navigate to admin/config/media/file-system in the drupal admin interface. I get this error

  Warning: mkdir(): Permission denied in Drupal\Core\File\FileSystem->mkdirCall() (line 244 of core/lib/Drupal/Core/File/FileSystem.php) .

I granted the permission to sites folder using the following commands chown -R www-data:www-data sites and chmod -R g+rw sites.
But still the error appears.

Any advice?

First of all make sure that the files directory (sites/default/files by default) has the right owner and permissions.
And also directory of temporary files, in general /tmp if you don't have create one and give it the right permissions.


Sort content of views with drag and drop I use Drupal 8, but I can not figure out how to sort views with drag and drop.
The client needs to sort the items of the views in a very personal way.

Do you know some way?

The Draggable Views module might be what you need. There is a version of the module for Drupal 8.

According to the module description,

  DraggableViews makes rows of a view "draggable" which means that they
  can be rearranged by Drag'n'Drop.

I tried the following instructions in the documentation page on a vanilla Drupal 8.2.6 installation, and it worked fine (see screenshot below).

  Activate the module and navigate to the edit-page of an existing
  view.
  Now go to the Format section and choose Table.
  Make sure you have the "Content: Title" field, place it as your first field.
  Add the field "Draggableviews: Content" at the Fields section, place it after the "Content: Title" field.Make sure not to check
  "Exclude from display"; if you do the view will permit drag and drop
  but the changes will not be saved.
  Add "DraggableViews: Weight" at the Sort criteria section and place it as the first Sort criteria. Save the view and you're done.

Refer this link, it may help.
https://www.drupal.org/node/2824325


How can I programmatically load and display all available blocks? $block = Drupal\block\Entity\Block::load($block_id);
ksm($block);

This code loads only one specific block. But how can I load and display all available blocks?

Using the service plugin.manager.block we will get all blocks available definition.

$blockManager = \Drupal::service('plugin.manager.block');

$contextRepository = \Drupal::service('context.repository');

// Get blocks definition

$definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

To get details about one specific block you can use below code.

print_r($definitions['help_block']);

$query = \Drupal::entityQuery('block_content');
$ids  = $query->execute();

You can also use 'block' instead of 'block_content' to get blocks from code


Installing modules without FTP So I have installed the latest Drupal 7 stable on my new server, and it asks for an FTP user/password every time I try to install a new module from a .zip file. (Or using an URL).

The problem is that I don't have an FTP installed on the machine, and I don't really want to install one. I'm pretty sure this is related to some configuration/permission, but I'm not sure where to start. Tried searching around about the question, but only found "random" answers. Nothing clean and/or official.

It is a permissions issue...basically your web server needs permission to write to 'sites/all/modules' for Drupal to be able to get the new module folder there without using FTP.

However, it's a security risk to do this, so if your server is already configured in such a way that stops the apache/php daemons from writing to those folders you should keep it that way.

The better way to install modules automatically in Drupal is to use the Drush command line tool. You can issue a couple of commands:

drush dl views
drush en views

And the module will be automatically downloaded and installed on your site. Drush is infinitely more powerful than that (you can perform all sorts of administration tasks easily from the command line) so if you haven't come across it before I'd thoroughly recommend giving it a go.

I had the same problem before I started using drush to install, enable, and manage themes and modules. Try these commands from the terminal.

drush dl;
drush en;
drush cc all;


Render a Views row ID using NID (Node ID) I can easily add NID (Node ID) as a field in my view and then render it as a class for the Views Row using replacement patterns for the row class of an unformatted typical view. (See screen capture).

However, I'd like to render the NID as an ID for each row for use for some special theming I am doing. If I use devel themer, I see my template is views-view-unformatted.tpl.php so I can of course copy this template into my theme's template folder with a custom name specific to my view and then theme it.

The relevant line of code in the template that renders the row class is:

  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>

If I change it to:

<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    id="<?php print $fields['nid']->content ?>">

...However, this does not work as I don't think fields are available at this level in the views row.

So essentially right now my rendered output is:

... when I'd like it to be

My question, is there a way to just render the associated NID where I want it as an id other then the method I am trying to use?

In most Views templates, the entire $view object is available.  So, assuming you have a nid field in the row, you should be able to access it with something like this:

$view->result[$id]->nid

so, give

id="my-nid-is-<?php print $view->result[$id]->nid; ?>">

a try in your template.

If this doesn't work exactly, a print_r($view->result); up at the top of the template will give you a gander at what you have to work with.

You need to use the views-view-fields--[name].tpl.php for construct the main row div. So, put in your `views-view-fields:

<div id="<?php print $row->nid; ?>">
<?php foreach ($fields as $id => $field): ?>
  <?php if (!empty($field->separator)): ?>
    <?php print $field->separator; ?>
  <?php endif; ?>

  <?php print $field->wrapper_prefix; ?>
    <?php print $field->label_html; ?>
    <?php print $field->content; ?>
  <?php print $field->wrapper_suffix; ?>
<?php endforeach; ?>
</div>

The main problem is that you have two <div> tags. So you can choose to delete the div into views-view-unformatted.tpl.php.