Contextual filters in taxonomy term ID (with depth) I need to make a view that will show me the nodes of a content type inside a node of another content type filtered by a taxonomy term.

I have three content types. The first one is Projects, in which I've added some projects (title, body and images-shadowbox). The second one is Projects Categories, in which I have some categories like:

houses.
offices.
etc.

The third one is Services, in which I've added the following categories:

architecture.
engineering.

I have added a "Projects" vocabulary with two items:

Project 1.
Project 2.

In each node of the "Projects" content type, I assign term of the Projects vocabulary. Each node of the "Project Categories" & "Services" can have more than one terms of the Projects vocabulary.

What I need is to preview under each "Project Categories" & "Services" node the relevant node "Project", filtered by the taxonomy term of the "Projects" vocabulary.

How can I achieve this?

This is similar to another request: Contextual filter in taxonomy- Drupal 7

I've customized my answer to your specific requirements:

First thing you need to do is install the References module

When setting up your project content type, create a category node reference field and a services node reference field. This will tie each project to one or more categories and one or more services.

When configuring your view, you will need to create relationships between the project and service/category.

You should use EVA - Entity views attachment module.


Invalidating Paragraph Cache I'm working on a paragraph type that will need to display on a very limited number of pages but has some specific functionality where the preprocess function will need to run each time.

In my preprocess function, I've tried various iterations of the following:

$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';
$variables['elements']['#cache'] = ['tags' => ['my_paragraph']];
Cache::invalidateTags(['my_paragraph']);
\Drupal::service('page_cache_kill_switch')->trigger();

However, the preprocess function runs once after a cache clear and then doesn't run again.

What am I doing incorrectly here? How can I get this to run each time?

You've got a logic error in your PHP. You're doing the following and setting some variables:

$variables['elements']['#cache']['max-age'] = '0';
$variables['elements']['#cache']['contexts'][] = 'url.path';
$variables['elements']['#cache']['contexts'][] = 'url.query_args:r';

But then in the next line you're redeclaring $variables['elements']['#cache'] as a new array of  ['tags' => ['my_paragraph']]; So everything you were doing previously in the
$variables['elements']['#cache'] is now gone

So your max-age declaration doesn't exist now. Try with just these 2 items and that should be all you need. The first to tell drupal not to cache the paragraph. The 2nd to disable anonymous page caching as setting max-age 0 doesnt disable the page cache:

$variables['elements']['#cache']['max-age'] = '0';
\Drupal::service('page_cache_kill_switch')->trigger();

This worked for me. The idea behind is to invalidate both node and paragraph entity caches.
$variables['elements']['#cache']['max-age'] = '0';
Cache::invalidateTags(['paragraph:' . $par->id()]);
Cache::invalidateTags(['node:' . $node->id()]);
\Drupal::service('page_cache_kill_switch')->trigger();

The context is hook_preprocess_paragraph__TYPEID(&$variables)


Views Grouped Filters turns Radiobuttons into Select? I have a grouped filter in a view with lets say 3 items. For the Widget i choose Radios and Allow multiple selections. For 3 Items everything works fine and i have some checkboxes. Wenn they are more then 3 items instead of checkboxes there is a select list! But i want to have checkboxes. Even Better Exposed Filters only shows select as an option for that filter.
Whats wrong ?

I  came up with writing a simple hook:

 function  MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
  {
    if ($form['#id'] == 'MYFORMID') {
      $form['field_MY_VALUE_FIELD']['#theme'] = 'select_as_checkboxes';
    }
  }

I have the same problem, but I can get up to four items. My workaround was to just add more grouped filters, making sure to use the OR grouping.


Implementing Taxonomy hierarchy in View and Search I am working on a biology website that needs to make use of Drupal 7's Taxonomy system, for a biological taxonomy.

My goal is to allow users to tag all content with related species information, and provide the following functionality:

Display all nodes that are associated with a child term of the
specified taxonomy term (so if they access the "Birds" term,
"sparrow" would be included)
Include taxonomy terms in search
Allow for species nicknames, (synonyms), abbreviations and variations in spelling or singular/plural usage

I have installed the Hierarchical Select module, but am not sure it is working correctly. Or, I am not using it correctly. When I insert new terms deep in the hierarchy, they sometimes end up at the top level. There have also been intermittent errors showing in a red box. I'll add that to this post if it shows again.

Example taxonomy

Animalia
- Chordata
-- Aves
--- Passeriformes
---- Passeridae
----- Passer
------ Passer domesticus (primary species term)
------- Common sparrow   (synonym)
------- English sparrow  (synonym)
------- House sparrow    (synonym)
------- ENSP             (synonym/abbreviation)
------- House sparrows   (synonym/plural)

In the above example, I need users to see English Sparrow content when they view the Taxonomy page for Aves, as well as the Taxonomy page for "ENSP" if the node has been tagged with Passer domesticus or any of its child terms.

Ideally, a basic search for any of the child terms for Passer domesticus would also return a list of nodes tagged with any of the term's siblings.

I am open to configuring a View for this, if Search is not possible.  All advice is appreciated.

Similar questions from others:
http://drupal.org/node/1792256

How to have parent taxonomy terms include their children terms' nodes?

How to show the parent and child taxonomy term?

https://stackoverflow.com/questions/5910071/views-show-child-taxonomy-terms

I would look into using Search API for this and build up facets using the Facets API.

Once you have Search API installed you need to create a search index, choose which fields to index and what facets to create.

With the search index in place you can from Views create a Search view that uses your index as base.

Place the facets where you want them and tell them to show up at your search views url.

There is a guide that explains how to setup Search API here. In the guide they use Apache Solr as backend for the search index. That is not necessary, you can use the database as backend but I recommend using Apache Solr as backend as I've stumbled on a few bugs in the database backend which work with Solr.

You would be able to do searches such as this:

Good luck


How can I display the price field twice? I am using commerce kickstart 2. Here's a screen shot of my product display

I've set a VAT tax rate in Drupal Commerce, so the price in that screenshot is the price of the product, plus the 20% VAT tax.

How can I display the price excluding VAT?

You should use Commerce Extra Price Formatters module.

Extra Price Formatters Implemented So Far

RRP / Your Price

Allows you to display the Retail Price and the User Price
for a product and optionally the amount the customer
will save.

Allows you to switch the display back to a single price if
there is no discount available on a particular product.
Formatted Price with Prefix and Suffix

Allows you to present a price in the style just £9.99 ex
VAT or only £9.99 for a limited time only.
Formatted Price with no decimal places

When you are selling items with whole unit prices, you
don't necessarily want to see £10.00. This formatter
lets you change the display to show £10. (use this with
care!)

There's a video demo here: http://www.youtube.com/watch?v=-WR3mKjou8M

Then you should add two price fields in your product content type. In your manage display tab you would be having a settings option to calculate your price excluding or including tax and other parameters and thus you can add two price fields.


Cannot install any theme I am new to Drupal and am facing an issue where any theme that I try to install will fail with the following message:
Installing light_skeleton
An error has occurred.
Please continue to the error page

An AJAX HTTP error occurred.
HTTP Result Code: 403
Debugging information follows.
Path: /core/authorize.php/core/authorize.php?batch=1&id=4&op=do_nojs&op=do
StatusText: Forbidden
ResponseText:
403 Forbidden
403 Forbidden
nginx/1.9.10

The root folder is owned by www-data:www-data and I have given the directory 775 permissions. I have also tried to give it a full access using chmod 777 but without success.
I have checked the logs of nginx and php but there are no errors displayed. The site itself, using the standard theme, works without any issues.
After getting the error, I get:
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Warning: Invalid argument supplied for foreach() in update_authorize_install_batch_finished() (line 291 of core/modules/update/update.authorize.inc).
Notice: Undefined index: log in update_authorize_install_batch_finished() (line 332 of core/modules/update/update.authorize.inc).
Notice: Undefined index: tasks in update_authorize_install_batch_finished() (line 333 of core/modules/update/update.authorize.inc).
Installation failed! See the log below for more information.

This is an nginx configuration issue and discussed intensely on this page Yet curiously no solid solution could be offered. Some guy on an other page proposed a solution. I applied that proposed solution and can confirm that in works!

To apply proposed solution go to your nginx configuration file under

/etc/nginx/sites-available/ directory on Ubuntu and add

rewrite ^/core/authorize.php/core/authorize.php(.*)$ /core/authorize.php$1;

just above the

location ~ \..*/.*\.php$ {
    return 403;
}

block. Location does matter!.. Restart your server:

  sudo service nginx restart

and that's it. The problem solved!

I have similar error, any solution?
update i just finally fixed it
just add this:
rewrite ^/core/authorize.php/core/authorize.php(.*)$ /core/authorize.php$1;
to my server{} block of my nginx conf


Changing language in drupal So my problem is i dont know how to make my custom menu item change language in drupal. I know there is a language switcher in drupal, but i want to make a new custom menu in drupal, theme it, and i want the links to trigger changing the language, like the link "french" changes the site to french. How can this custom trigger of events be created in drupal and how do i know which functions to call/variables to change to allow me to achieve this?

I really appreciate any help!

May be you are looking for language_negotiation_get_switch_links

  Return the language switch links for the given language.

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$links = language_negotiation_get_switch_links($type, $path);


Pressflow 6 forms creating session cookies We have a Pressflow 6 website behind a Varnish cache but our cache hit-rate is awfully low. I've recently found that stripping the "Cookie" header from requests completely increases the hit-rate to 97-98%.

The vast majority of our users are anonymous, so Pressflow shouldn't be setting a session cookie, however we do have a number of forms on the site and it seems that when someone uses a form a session cookie is set in their browser. The forms aren't fancy, the page they submit to just says "thanks for your comment" so there's no need for a session as POST requests aren't cached anyway. The cookie's lifetime is about a month and a half too.

I was considering stripping the cookies when there's no "DRUPAL_UID" cookie, however I'm loath to remove them all in case there's a legitimate reason for them being set.

So, two questions:

Is there a legitimate reason for these cookies being set?
If not is my best option to get Varnish to strip them out or is
    there a way to prevent them from being set or to remove them within Pressflow?

// Default backend definition.  Set this to point to your content
// server.
//
backend default {
  .host = "127.0.0.1";
.port = "81";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
// enable to use status script for health of backend
//  .probe = { .url = "/status.php"; .interval = 5s; .timeout = 1s; .window = 5;.threshold = 3; }
}

//
// BOOSTED VARNISH - by Trellon, LLC
//
// - Based on a configuration by Lullabot and VCL examples for Varnish Wiki.
//
// Logic is:
//
// * Assume: A cookie is set (we add __varnish=1 to client request to make this always true)
// * If boosted URL -> unset cookie
// * If backend not healthy -> unset cookie
// * If graphic or CSS file -> unset cookie
//
// Backend response:
//
// * If no (SESSION) cookie was send in, don't allow a cookie to go out, because
//   this would overwrite the current SESSION.

// Respond to incoming requests.
sub vcl_recv {

////// START BOOST Logic (Prerequisite)
  // We always send a cookie, so that empty requests are
  // handled by below boost logic, too.
  set req.http.Cookie = ";__varnish=1;" req.http.Cookie;
////// END BOOST Logic (Prerequisite)

// Enable to disable varnish
//      return (pipe);

////// START DEFAULT RULES
 // -------- CloudFlare ----------
  remove req.http.X-Forwarded-For;
  if (req.http.CF-Connecting-IP) {
    set req.http.X-Forwarded-For = req.http.CF-Connecting-IP;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }

  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  set req.http.Cookie = regsub(req.http.Cookie, "^__\s*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|cfduid)=[^;]*","");
  // -------- CloudFlare ----------

 if (req.request != "GET" &&
    req.request != "HEAD" &&
    req.request != "PUT" &&
    req.request != "POST" &&
    req.request != "TRACE" &&
    req.request != "OPTIONS" &&
    req.request != "DELETE") {
      // Non-RFC2616 or CONNECT which is weird.
      return (pipe);
  }
  if (req.request != "GET" && req.request != "HEAD") {
    // We only deal with GET and HEAD by default
    return (pass);
  }

////// END DEFAULT RULES

  // Allow the backend to serve up stale content if it is responding slowly.
  set req.grace = 1h;

  // Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/sitemap\.xml$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/jstats\.php$" ||
      req.url ~ "^/boost_stats\.php$" ||
      req.url ~ "^/cron\.php$" ||
      req.url ~ "^/ooyala/ping$" ||
      req.url ~ "^/admin/" ||
      req.url ~ "^/info/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$") {
       return (pass);
  }

  // Pipe these paths directly to Apache for streaming.
  if (req.url ~ "^/admin/") {
    return (pipe);
  }

  // Do not allow outside access to cron.php or install.php.
  if (req.url ~ "^/(install)\.php$" && !client.ip ~ internal) {
    // Have Varnish throw the error directly.
    error 404 "Page not found.";
    // Use a custom error page that you've defined in Drupal at the path "404".
    // set req.url = "/404";
  }

  // Handle compression correctly. Different browsers send different
  // "Accept-Encoding" headers, even though they mostly all support the same
  // compression mechanisms. By consolidating these compression headers into
  // a consistent format, we can reduce the size of the cache and get more hits.=
  // @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression
  if (req.http.Accept-Encoding) {
    if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v)$") {
      // No point in compressing these
      remove req.http.Accept-Encoding;
    }
    else if (req.http.Accept-Encoding ~ "gzip") {
      // If the browser supports it, we'll use gzip.
      set req.http.Accept-Encoding = "gzip";
    }
    else {
      // Unknown or deflate algorithm. Remove it and send unencoded.
      unset req.http.Accept-Encoding;
    }
  }

////// START .htaccess rewrite rules

// Strip out Google Analytics campaign variables. They are only needed
// by the javascript running on the page
// utm_source, utm_medium, utm_campaign, gclid
  if(req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
    set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[^\&]+&?", "");
    set req.url = regsub(req.url, "(\?|&)$", "");
  }

////// END .htaccess rewrite rules

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION

  // but boost will always set the DRUPAL_UID cookie
  // when the user is logged in.
  //
  // So it is safe to remove all cookies for the boosted paths.
  if (!(req.http.Cookie ~ "DRUPAL_UID=")) {
     // User is anonymous

     // Boost rules from .htaccess
     if (!(req.url ~ "(^/(admin|cache|misc|modules|sites|system|openid|themes|node/add))|(/(comment/reply|edit|user|user/(login|password|register))$)")) {

////////// BOOST CONFIG: Change this to your needs
       // Boost rules from boost configuration
       if (!(req.url ~ "/(excluded-url-to-be-configured)")) {
         unset req.http.Cookie;
       }
////////// END BOOST CONFIG: Change this to your needs
    }
  }

////// END BOOST LOGIC

////// Cookie removal logic

  // Always cache the following file types for all users.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    unset req.http.Cookie;
  }

  // Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }

}

// Routine used to determine the cache key if storing/retrieving a cached page.
sub vcl_hash {
  // Include cookie in cache hash.
  // This check is unnecessary because we already pass on all cookies.
  // if (req.http.Cookie) {
  //   set req.hash += req.http.Cookie;
  // }
}

// Code determining what to do when serving items from the Apache servers.
sub vcl_fetch {

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION
  // but we only set SESSION if we actually send cookies
  //
  // So logic is: If we did not send a cookie in,
  // we do not allow a cookie out.

  if (!req.http.Cookie) {
    unset beresp.http.set-cookie;
  }

////// END BOOST LOGIC

  // Don't allow static files to set cookies.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    // beresp == Back-end response from the web server.
    unset beresp.http.set-cookie;
  }

  // Allow items to be stale if needed.
  set beresp.grace = 1h;

  // Serve the good page from the cache and re-check in one minute

  if (beresp.status == 503 || beresp.status == 501 || beresp.status == 500) {
    set beresp.grace = 60s;
    restart;
  }

  // Anything that is cacheable, but has expiration date too low
  // which prevents caching gets cached by varnish to take the
  // load off apache.

  if (beresp.cacheable && beresp.ttl < 1h) {

////////// MINIMUM CACHE LIFETIME: Change this to your needs
    // Set how long Varnish will keep it
    set beresp.ttl = 1h;
////////// END MINIMUM CACHE LIFETIME: Change this to your needs

    // marker for vcl_deliver to reset Age:
    set beresp.http.magicmarker = "1";
  }

}

sub vcl_deliver {
////// START DEBUG
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT Varnish (" obj.hits ")";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
////// END DEBUG

  // The magic marker is used to reset the age to 0
  // as else the object is older than its ttl.

  if (resp.http.magicmarker) {
    // Remove the magic marker
    unset resp.http.magicmarker;

    // By definition we have a fresh object
    set resp.http.Age = "0";
  }
}

// In the event of an error, show friendlier messages.
sub vcl_error {
  // Redirect to some other URL in the case of a homepage failure.
  //if (req.url ~ "^/?$") {
  //  set obj.status = 302;
  //  set obj.http.Location = "http://www.megaleecher.net";
  //}

  // Otherwise redirect to the homepage, which will likely be in the cache.
  set obj.http.Content-Type = "text/html; charset=utf-8";
  synthetic {"

  <title>"} obj.status " " obj.response {"</title>

Page Could Not Be Loaded

The page you requested is temporarily unavailable.

We're very sorry, but the page could not be loaded properly. This should be fixed very soon, and we apologize for any inconvenience.

We're redirecting you to the Tech Blogs Homepage in 5 seconds.

(Error: "} obj.status " " obj.response {")

"};
  return (deliver);
}

The above worked for me, if you are not using Cloudflare make sure to remove that section.


How can I tell if a config entity hasn’t been saved yet? How can I tell if a config entity hasn’t been saved yet?

isNew();

this core test confirms it:

// Config is no longer new once saved.
$this->config->save();
$this->assertFalse($this->config->isNew());

(from core/tests/Drupal/Tests/Core/Config/ConfigTest.php)

Check if it has an ID.

if ($entity->id()) {
   // Not a new entity.
}
else {
  // Hasn't yet been saved.
}


hook_field_extra_fields: hidden by default When implementing hook_field_extra_fields(), can I make the extra field hidden by default?

Sometimes it is friendlier to offer the extra fields as an option, instead of displaying it immediately after a module is enabled.

In _field_info_prepare_extra_fields() the extra fields are set to visible by default, but the extra field settings are stored in the field_bundle_settings variable which you can change in your module's hook_install() like:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'my_extra_field';
$view_mode = 'teaser';

$field_bundle_setting = variable_get('field_bundle_settings', array());
$field_bundle_setting[$entity_type][$bundle]['extra_fields']['display'][$field_name][$view_mode]['visible'] = FALSE;
variable_set('field_bundle_settings', $field_bundle_setting);

So much simpler example.  For Drupal 7
Create example_module.install under the example_module directory

/**
 * hook_install
 */

function example_module_install() {
  $field_machine_name = 'new_extra_field';
  $entity_types = array('node', 'taxonomy_term', 'user');
  foreach ($entity_types as $type) {
    $info = entity_get_info($type);
    $settings = field_bundle_settings($type, $bundle);
    $view_modes = array_merge(array('default'), array_keys($info['view modes']));
    foreach($view_modes as $view_mode) {
      $settings['extra_fields']['display'][$field_machine_name][$view_mode] = array(
        'visible' => FALSE,
        'weight'  => 0,
      );
    }
    field_bundle_settings($type, $bundle, $settings);
  }
}

Documentation for hook_install
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_install/7

In your example_module.module file add

 /**
  * Implementation of hook_field_extra_fields
  *
  */
 function example_module_field_extra_fields() {
   $extra = array();
   $field_machine_name = 'new_extra_field';
   $entity_types = array('node', 'taxonomy_term', 'user');
   foreach ($entity_types as $type) {
     $info = entity_get_info($type);
     foreach(array_keys($info["bundles"]) as $bundle) {
       $extra[$type][$bundle]['display'][$field_machine_name] = array(
         'label' => t('New extra field that will show up in manage display'),
         'description' => 'A description for the extra field',
         'weight' => 5,
        );
     }
   }
   return $extra;
 }

Documentation for hook_field_extra_fields https://api.drupal.org/api/drupal/modules%21field%21field.api.php/function/hook_field_extra_fields/7


Is there a way to setup a site monitor on drupal? I have the current question: https://drupal.stackexchange.com/questions/37712/ubercart-items-wont-add-to-cart-unless-cache-is-cleared. In order to try and narrow down what the issue is. I'm curious if there is a way to setup a sort of monitor or logs to be able to get some more insight as to what is going wrong. I know of the typical status reports, Log messages & server logs. But is there anything that might be able to give me more drupal related details?

mysql and httpd logging on your server should help a bit.  turn them on (and adjust reporting levels) but make sure you don't fill up your disk with logs.  turn the logging level back down to something normal once you've looked for a while.


Not able to change the settings.php I am working on drupal commons, and using pantheon servers for hosting. The major problem I am facing is the server database config issues. I am not able to change the settings.php file. Also Pantheon every now and then changes their db server password. How can I control this ? is there any server variable for the db instance, port, user id, password ?

Drupal removes "write" permission from settings.php, so to edit it, you need to give this permission back.

SSH

chmod u+w sites/default/settings.php

FTP, SFTP and alike

Use your cilent, and just tick appropriate checkbox. Like this:

Copy the file setting.php and paste them in same folder
Rename that folder like setting1.php.
Now you can change that file and user db name,apssword.
Rename that original settings.php as originalsettings.php.
Now you can rename that setting1.php file as settings.php.

now its working fine now.


How to validate and submit a form using AJAX? I've created a webform using the Form API. I'm using the #AJAX field option to add AJAX validation to each field.

Is it possible to validate and submit the form using AJAX without reloading the page. If validation fails I want to show an error message and if validation is successful then I want to show a message (ideally in a lightbox) and reset the form fields.

My code so far:

$form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default_value' => '',
    '#maxlength' => '128',
    '#required' => TRUE,
    '#ajax' => array(
        'callback' => '_validate_name',
        'wrapper' => 'name-error-icon-container',
        'method' => 'html',
        'effect' => 'none',
        'progress' => array(
            'message' => NULL,
        ),
    ),
);

$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
    '#ajax' => array(
        'callback' => '_handle_form_submit',
        'effect' => 'fade',
    ),
);

callback functions look like this:

function _validate_name($form, $form_state) {

    if ($form_state['values']['name'] != '') {
    $output = 'OK';
    }
    else {
      $output = 'Enter a value';
    }

   return $output;

}

function _handle_form_submit($form, $form_state) {
}

But I'm not sure what should go in the _handle_form_submit function to validate and then either return a message or submit form and reset fields?

I know this is question has been lying around for a couple of years by now, but I don't feel any of the other answers really get the point of Drupal 7 ajax form submission, so I'll try to explain it.
Since your form should work as well without the ajax as per good practice, your ajax submit handler should do nothing but return the form. Everything else should be in your validation and submit functions.
function ex_form($form, $form_state) {
  $form['name'] = array(
    '#type' => 'textfield',
     '#title' => t('Name'),
     '#default_value' => '',
     '#maxlength' => '128',
     '#required' => TRUE,
  );

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => 'Submit',
   '#ajax' => array(
     'callback' => 'ex_form_ajax_handler',
     'effect' => 'fade',
   ),
  );
}

function ex_form_submit(&$form, &$form_state) {
  // Submit logic - runs when validation is ok
  // You can alter the form here to be just a markup field if you want.
}

function ex_form_validate(&$form, &$form_state) {
  // Validation logic - invalidate using form_set_error() or form_error()
}

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

The examples module has an ajax form that you can refer to as well as many others. Here is a link to the ajax form example in the code repository, but I suggest downloading to look at the implementation yourself anyway.


How to set one region over the other (and not beside it) in Omega theme? I´m using Omega theme in a Drupal 7 installation, and don´t know how to put the sidebar second right below the sidebar first.

Under Zone and region configuration I have the content section, with the content zone inside it.
Content zone has 12 columns.
Inside it I have 2 regions:
content (6 cols).
sidebar second (3 cols).

If I add there another region, (sidebar first in my case) Omega puts it along the other two, and I can only set the weight of each one to determine wich one will appear first.
But what if I want one region under the other?

I´m using delta module to create different layouts according to some variables, but every time I try to set one region over the other it fails. Is there any way to do that?

Thanks!

UPDATE: How may I use context to do that in case it is possible?

The side bars are used to create columns and not for placing it one on top of the other.

If you want a single column then you would go for one of the three. If you want two columns go with any two of them and if you want three columns go for all three.

As for placing contents one on top of the other the blocks should be used for that. Let us say you have two blocks one to show the latest articles and another to place the login box and you want the articles to be on top of the login box then you would go with one of the side bars and content and place both the blocks in the same sidebar and arrange it as you would want it.

The problem isn't really with Omega, it's more in the way that divs work.

You can't float divs sequentially that way without putting one inside the other.

What you want to do requires putting one region inside another, not on top of.

You could make custom template files and a custom grid that puts one zone alongside the other, but you'd lose the ability to extend each zone to 100% width, limiting your design options.

One javascript solution is good old Masonry http://masonry.desandro.com/ which essentially gives you the equivalent of a  "float: top-left;" css rule.


Allow Anonymous User to Access Form I'd like to create a form with Drupal that all users can access, but every time I try to access the form without being logged in, I get this error:

Access denied

You are not authorized to access this page.

How can I allow all users to access the form?

Select People -> Permissions, scroll down and adjust the permissions of Contact.


What is the equivalent of hook_property_info_alter()? In Drupal 7, we had hook_entity_property_info() and hook_entity_property_info_alter() which allowed us to add custom properties. (Not everything is a field.)

I can't find anything related to Drupal 8. The only thing I find is how to add it on a custom entity. How should I add properties to an existing entity/bundle?

I suppose you want hook_entity_base_field_info(). By using a computed field based on a class, you can get a behavior similar to properties.

function hook_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $fields = [];
    $fields['mymodule_text'] = BaseFieldDefinition::create('string')
      ->setLabel(t('The text'))
      ->setDescription(t('A text property added by mymodule.'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\EntityComputedText');

    return $fields;
  }
}

I have copied a snippet from Drupal commerce, where a payment gateway reference is appended to a commerce_order entity (commerce_payment module altering an entity from commerce_order module).

/**
 * Implements hook_entity_base_field_info().
 */
function commerce_payment_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'commerce_order') {
    $fields['payment_gateway'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment gateway'))
      ->setDescription(t('The payment gateway.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_gateway');

    $fields['payment_method'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Payment method'))
      ->setDescription(t('The payment method.'))
      ->setRequired(TRUE)
      ->setSetting('target_type', 'commerce_payment_method');

    return $fields;
  }
}

By using ->setReadOnly(TRUE); or ->setComputed(TRUE), you can probably hide them from regular forms, making them behave like properties.

You might want to look at D8 - hook_entity_bundle_info_alter


How to pass parameters to same form after form submission? I have created a module that creates and displays a table and with a filter element. What I would like to do is when the user enter a string into the filter can submits it, I then use that string to filter the results of the table. What I am having an issue with is how to pass that string back into the form creation function to filter the results.

This is what I have in the submit function:

function submission_list_form_submit($form, &$form_state) {

  $filter = array();
  if (isset($form_state['values']['filter_user'])) {
    $filter['username'] = $form_state['values']['filter_user'];
  }
  return $filter;
}

Which is not right obviously. How do I get the $filter variable to be passed back into the submission_list_form function that creates the page? This is being done with Drupal 7.

Thanks.

You can use the following code, to achieve what you want.

function submission_list_form_submit($form, &$form_state) {
  $filter = array();

  if (isset($form_state['values']['filter_user'])) {
    $form_state['filter']['username'] = $form_state['values']['filter_user'];
  }

  $form_state['rebuild'] = TRUE;
}

The form building function should then check if $form_state['filter'] is set.

function submission_list_form($form, &$form_state) {
  if (isset($form_state['filter'])) {
    // …
  }

  // …

  return $form;
}

If the code doesn't work, use another array index instead of $form_state['filter']; it is probable that in such case the array index conflicts with the one used by Drupal or a third-party module. I would rather prefix the array index with the short module name, to be sure to avoid conflicts with other modules or future Drupal versions.

References

drupal_build_form()

I'm not sure but I think you should use variable_get and set to pass it.
Hope that helps.


How to assign nodes to an organic group in code How can I assign a node to an organic group in code?
After consulting following page

http://www.barnettech.com/content/adding-node-organic-group-programmatically
Programmatically assign a node to an organic group

And de OG API I ended up with this code, but it throws an error 'The website encountered an unexpected error. Please try again later.'

$node = node_load(5827);
$values = array('entity type' => 'node', 'entity' => $node, 'field_name' =>'og_group_ref');
og_group('node', 3, $values);
node_save($node);

More info:
OG-7.2.7

Found out removing the last line from the snippet 'node_save($node)' and the above type error was the reason for my problem. Thanks for the support.


How to have all the fields available in a display mode for content type D8 I'd like to be able to choose the date field or other fields that you can see in form display in 'custom display mode' for content types ?

How can I do that ?

Thank you.

You need to drag the items that you don't want to the disabled section. This works for both form display and front end display.

For your custom display mode, you should be able to select from each display mode:

You can go to admin/structure/types/manage/content_type/form-display and drag the fields under "disabled" which you don't want to show in the node edit form. Rest will be present in node edit form

But the field which you have moved under disabled, will show up in front end display.

Attached is the screen shot


Token Value to insert URL of page into field I am trying to create a webform to appear at the end of all my site pages that asks if there is anything about the page that should be improved.  This is dumped straight into the page.  In order for this to make sense I need to be able to record the url the form was shown on.

I tried to dump these tokens into the default value for a field

%nid
%title

but they output the nid of the webform not the page it is dispayed as a block on.

If the user is logged in I can use

%server[SCRIPTNAME]

which works but almost all my users won't be logged in.

Is there a way I can get this information into a field on my form?   Otherwise my feedback for is useless.

you can use form alter .get the values from url put the values using form alter to default fields .


Getting a field's value from an entity What I have installed on my site is the Entity API and Entityform modules. The Entityform module allows me to create forms that any user can submit and the forms fields are available for me to use in views, similar to how a content type would work.

Normally to pull a field's value from a node into my template with php I'd do the following:

<?php echo $node->field_name[$node->language][0]['value']; ?>

However this does not work with entityforms/entities.

Does anybody know of a way to do this for a field within an entityform? Some people have suggested to use devel and the dpm() function but I have no idea how to use those either.

Some specific examples on how I can get this field's value would really help me a lot.

Have you tried accessing the values with entity_metadata_wrapper?

$entityform_id = 12; // entity form id
$entityform = entityform_load($entityform_id);
$entityform_wrapper = entity_metadata_wrapper('entityform', $entityform);
// Access fields with $entityform_wrapper->field_name->value() or ->field_name->raw()
drupal_set_message($entityform_wrapper->field_my_field->value()); // for example

Rather than using dpm and installing that module I use:

print_r('<pre>');
print_r($node);
print_r('</pre>');

Hopefully this will help you dig down to the value.


Alter cart unit price and total amount I need help on this code which is invoked on calculate sell price rules event
on cart view. Line items and order are properly modified. But nothing is displayed, old unit price amount and old total amount are displayed. Even after cart refresh. Any idea ?

/**
* Calculates the price when line item are dispalyed
* or created.
*/

function mymodule_calculate_product_price_cart($order) {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    // Iterates on line items and alter the price.
    $commerce_line_items = array();
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      $line_item = $line_item_wrapper->value();
      $type = $line_item_wrapper->commerce_product->value()->type;
      if ($type === 'insurance') {
        $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
        $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
        $amount = _mymodule_calculate_policy_price($warranty_price, $package_price);
      }
      elseif ($type === 'little_product') {
        $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      }
      else {
        $commerce_line_items[$delta] = $line_item;
        continue;
      }
      $qty = $line_item->quantity;
      // This sets the unit price by adding a component price 'base_price'
      mymodule_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
      mymodule_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
      commerce_line_item_save($line_item);
      entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
      $commerce_line_items[$delta] = $line_item;
    }
    $order_wrapper->commerce_line_items = $commerce_line_items;
    module_invoke_all('commerce_cart_order_refresh', $order_wrapper);
    commerce_order_save($order_wrapper->value());
  }

I finally made it work.

function mymodule_commerce_commerce_cart_order_refresh($order_wrapper) {
  foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $type = $line_item_wrapper->commerce_product->value()->type;
    if ($type === 'insurance') {
      $package_price   = $line_item_wrapper->commerce_product->field_package_ref->commerce_price->amount->value();
      $warranty_price  = $line_item_wrapper->commerce_product->commerce_price->amount->value();
      $amount = _mymodule_commerce_calculate_policy_price($warranty_price, $package_price);
    }
    elseif ($type === 'little_product') {
      $amount = $line_item_wrapper->commerce_product->commerce_price->amount->value();
    }
    else {
      return TRUE;
    }
    $qty = $line_item->quantity;
    // This sets the unit price by adding a component price 'base_price'.
    mymodule_commerce_line_item_price_amount($line_item, $amount, 'commerce_unit_price');
    mymodule_commerce_line_item_price_amount($line_item, $qty * $amount, 'commerce_total');
    commerce_line_item_save($line_item);
    entity_get_controller('commerce_line_item')->resetCache(array($line_item->line_item_id));
  }
}

This part :

line_item->commerce_unit_price[LANGUAGE_NONE]['0']['data']['components']['0']['price']['amount']=$price; // Alter the base_price component

... made my day (Commerce 7.x-1.10).

It correctly sets the order total amount on top of the line item amount.

If you don't do this, your order total will be out of sync.


Using Panels to display Taxonomy terms My Drupal 6 taxonomy terms are linked to two types of content, one is called Results (text) the other is a Photo.  Is it possible through Panels to develop a node where a user can select a term via a drop down menu then it will display only the Results and the pictures related to that term?  My goal is to have all of the results together in their own region and the same with the photo.

If it can be done, is there a recommended recipe I should follow?

If it can't be done any suggestion on how to do it?

Drupal Panels can do this using the Views module. The two modules work very well together to arrange your content on a page, but Views is the workhorse for sorting through the content and selecting what you want.  Check out the video series "Taming the Beast" at Nodeone.se for how to use Views.  They also have a series on Panels/Page Manger that shows how to link them.

I don't think panels is required here at all. Create one view that returns content of type Results and Photo. Have the content type as a field that will be hidden from display and then group your results by the content type.


Different Templates for Same Field I want to have two different templates for the same field on a node template.

For example:

{{ content.field_section }}

    // uses paragraph--section.html.twig
    // Only want to print the titles from paragraph sections

{{ content.field_section }}

    // uses paragraph--section2.html.twig
    // Want to print the body and titles from paragraph sections

How can I do this? Is there a way to flag one instance or force a specific template?

You can override existing twig file in preprocess hook. You may check the link https://www.drupal.org/docs/8/theming/twig/working-with-twig-templates.


Permanent Deleting of files still doesn't work for me (make_unused_managed_files_temporary = true) make_unused_managed_files_temporary didn't work for me.
I am using Drupal backend for the REST API frontend application.
Thats how the File input looks (because I am not sure if that setting is for that File elements, but guess so).

I read some informations about permanent files deleting, because I would like to delete files permanent from the file system and also database.
I was set the make_unused_managed_files_temporary to true and debuging, this is really true in the code.
I also found the configuration in Backend / File system - Delete temporary files after (6 hours), so this is on.
I am checking also the database file_managed before and after (and after 6 hours) file deletion for the flags like status that indicates isTemporary() method. But after uploading file, saving... then editing, and removing file, the file is still in the database as a status 1.
I am also checking DB table file_usage where there is still the item with count=1 too, that should be not true (because of deletion).
And files maybe should move to /tmp folder, but that doesnt.
I am working on Drupal 8.5.6 and 8.7.2 on production, but the behaviour is the same.
I am doing something wrong? Is there some cron to be configured? Or another futher settings?
Edit 1: I think it is not a Media, but simply file widget - /core/module/file
Edit 2: The main problem is that, when I delete file, it stay in the database as a permanent flag (status=1), and also it has a count of usage 1 (file_usage=1). When I manually update database to set status=0 and count=0, the cron works OK. Why the file usage and count stay on?

I just made a solution that works for me even the Drupal or config doesn't works properly. In my plugin I hooked up the hook_cron() for logging these unused files to proceed them next.

SQL SELECT; query to fetch all file_managed fid's. You can select only status=1, as permanent files, but I got all,
PHP loop all id's and making a Drupal\file\FileInterface entity reference $file = File::load($item->fid) to check all the file references $references = file_get_file_references($file). When the $references is empty() this file is unused. Save all that fid id's into array $fids,
SQL UPDATE; build update query to null these rows: UPDATE file_managed SET status=0 WHERE fid IN($fids) and UPDATE file_usage SET count=0 WHERE fid IN ($fids).

Finaly after next cron run the default function file_cron() {... will properly delete these files.


Make uploaded image thumbnail bigger I have file upload field in node edit form. After succesfull upload process (ahah by clicking Upload form button) I am getting thumbnail instead of file upload field. It's standard Drupal behaviour. I would like to know how to change size of image thumbnail generating by Drupal after ajax upload.

Could somebody give me any advice?

Here's want you need to do to modified the image field thumbnail thats display after you upload an image.

You will need to overwrite the imagefield_widget_preview theme function. You can drop this theme overwrite in the template.php file of your theme.

function THEMENANE_imagefield_widget_preview($item = NULL) {
  //By default this returns  theme('imagefield_admin_thumbnail', $item);
  //But If you're going to change it I would recommend replacing it with image-cache.
  //Also you should keep the imagefield-preview div.
  return '
' . theme('imagecache', 'your_custom_preset', $item['filepath'], $item['alt'], $item['title']) . '
';
}

This will replace the thumbnail images uploaded using image field.

Hope this helps.

Also remember, to use the name of the theme thats being used when editing. In-case you're using different themes.

I use ImageCache in D6 to control thumbnail and other preview sizes.  It's a simple and robust image module.

Drupal 7 has these controls in the core.


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

Clear my page cache and browser cache several times.

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

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

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

This works well on both themes.

alert(Drupal.settings.basePath);

This is my code.

MY_MODULE.module

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

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

MY_MODULE.js

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

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

  Uncaught TypeError: Cannot read property 'my_var' of undefined

How can I fix this?

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

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

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

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

Drupal.settings

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

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

Uncaught TypeError: Cannot read property 'my_var' of undefined

means that

Drupal.settings.MY_MODULE

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

you could also try

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

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

This is likely not the "preferred" way of handling this but I just use php to output js code thusly:

if (isset($post)) {
    echo "<script type='text/javascript'>\n";
    foreach ($_POST AS $name => $value) {
        echo "var " . $name . " = '" . $value . "';\n";
    }
    echo "function initialize() {\n";
    if (strpos($_SERVER['REQUEST_URI'],'results') !== false) {
        echo "initializePillars();\n";
        echo "initializeFeed(instagramFeed);\n";
    }else if (strpos($_SERVER['REQUEST_URI'],'quiz') !== false) {
        echo "initializeQuestion();\n";
    }
    echo "}\n";
    echo "</script>\n";
}

It's easy and it works.


Problem on the comment form #validation and #submit I've tried to create a validation and submit functions on a custom comment form, using drupal 7.9,  but it's not working, and I don't know why.

In the following code, we can see the "dpm's" in the first function, but not the "dpm's" in the last ones.

function job_form_comment_node_job_form_alter(&$form, &$form_state) {
    $form['#validate'][] = 'job_comment_validate';
    $form['#submit'][] = 'job_comment_submit';
    dpm($form);
    dpm($form_state);
}

function job_comment_validate($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

function job_comment_submit($form, &$form_state) {
    dpm($form);
    dpm($form_state);
}

if I add a #validate or #submit it also doesn't call others drupal hook comments like presave, insert etc.

If I comment these lines, the hooks are called, but I can't use the validation or the submission functions in this case.

Do you have any idea on why this happens?

You're missing $form_id, the third parameter of the function.

See hook_form_alter() reference on drupal.org. The problem you're experiencing might be a (weird) way of PHP reacting to that.

In situations like this you may want to check for errors on the logs (Drupal, PHP, MySQL). Some times there are useful hints there to figure what's wrong.


Drupal website was hacked? What is the hack that can cause my Drual website to be blank, without showing any message error.. Not be able even I enter .../users, -> blank. It was absolutely brilliantly showing fine.

If you want to see this Drupal website URL, go ahead:

http://fightforhongkongdemocracy.net

Thanks.

There is a guide on drupal.org with multiple troubleshooting methods to resolve white screens with no ouputs: https://www.drupal.org/node/482956

It is not finding it on the server. Reboot the server and try again quickly.


Disable select drop-downs, display names only I am looking for a way to remove the select drop-downs from the datepicker popup and display only months (and the year). As for the appearance, it can be altered in datepicker.1.7.css.

How do I disable the select drop-downs and show only the names?

As of date_popup 7.x-2.9, you can do this in your theme or custom module, implementing hook_element_info_alter(&$type).

function mytheme_element_info_alter(&$type) {
  $type['date_popup']['#datepicker_options'] += array(
    'changeMonth' => FALSE,
    'changeYear' => FALSE,
  );
}

Did it. Turns out, that you can influence the datepicker options in modules/date/data_popup/date_popup.module. In the function date_popup_element_info you can influence the datepicker-options for the jquery-part. This means that:

'#datepicker_options' => array(
  'changeMonth' => FALSE,
  'changeYear' => FALSE
),

will disable the dropdowns. However remember: This is a system wide change and might be gone with the next update.


How to disable SASS in Omega 4? I tried to set up SASS as part of an Omega 4 theme on a VPS server, but I'm now drowning in Ruby permissions and versioning issues. It's causing far more sysadmin type work than a CSS generator is worth for this project.

The Omega 4 docs repeatedly state that SASS is helpful but not essential to Omega 4 and that you can simply write CSS the old-fashioned way, which is what I intend to do - but they don't say anything about how to stop Omega trying (and failing) to apply SASS all the time.

How can I completely disable the SASS element of Omega 4?

I can't find anything relevant in the theme settings. I've tried simply removing / renaming the sass folder in my subtheme and clearing caches, but I'm still getting Ruby / SASS related errors that look like this:

  Error: File to import not found or unreadable: singularitygs.

I want it to completely stop trying to do anything related to SASS.

From reading around, it sounds like it's common to have a Drupal production server run Omega 4 with no SASS, and for people to have SASS on their development server then upload the CSS output to production when they're happy with it. Sounds sensible. But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

But how what I can't find is, how do they stop the production server from trying to run SASS and access all that Ruby stuff all the time?

There seems to be a major misunderstanding here.

Compilation of SASS is invoked by you, it's not an automatic action that a server will just take upon itself to perform. Your remote VPS will not be set up to try to auto-compile SASS into CSS unless you, or someone else with access to the server, has set it up like that. The very fact that you've had to setup and install ruby on the remote serve should hopefully make that obvious.

Having that stuff on your production server is wrong anyway, you should prepare your distribution locally (read: compile SASS, minify/uglify js, etc), and sync that. That way you can never have any problems.

Your comment below the question is correct: if you don't want to compile SASS, then simply don't run bundle exec guard, compass compile, or whatever other method you're using to instigate the compilation.

If you haven't told any process to watch/compile your SASS files, then no process will be able to do so. The power is yours.

If you've used drush omega-guard, it's not so simple.

In the end, two Drupal.SE and two StackOverflow questions later, the only way I could get Omega 4 to behave and stop freaking out trying to run Ruby every time I touched any directories was brute force, deleting every ruby-related file in the subtheme directory.

Uninstalling Ruby didn't help, so it can't have been something in Ruby. Rebooting didn't help, so it wasn't a process left running. Copying or renaming the subtheme folder didn't help, so it wasn't some system thing set to watch a directory by name. Renaming the guardfile didn't help, so it wasn't a process scanning for guardfiles, so it seemed it must be something in the subtheme folder.

I think deleting the guardfile is enough, but am not sure.

I don't know which file was the one that finally fixed it, but the only non-directory remaining files after my purge were:

Or, the short answer is, don't use Omega 4 theme and its drush commands if you're a themer. Omega 4's drush commands make system-level changes without an option to undo them: system-level changes are for Linux sysadmins, not Drupal themers.

After lots of research and two SO questions I think that the omega drush command makes these changes by accessing the inotify Linux kernel library from the PHP command line which can only be turned off by writing your own PHP CGI script to access the same api. Either that or it modifies .bashrc. If you're a themer whose skillset doesn't stretch that far into sysadmin territory, I'd advise against using the drush commands bundled with Omega 4 - at least until someone writes a drush omega-unguard script.


how to a translatable string in drupal theme? I want to put a string as a signature in drupal theme I am working on. the website is multilingual and the string should be translated based on the current language of the website. I don't know how to do it.

my drupal version is 6.

Would you help me?

The first step to translate a string used from a module, or a theme is using t() for every string that needs to be translated. Remember that the first argument given to the function is a literal string containing a phrase in English. This means that the following calls to t() are not correct.

// The string is a concatenation of literal strings.
$error = t('This example, ' . "doesn't work.");

// Also in this case there is a concatenation of literal strings.
$errno = 15;
$error = t("Error number $errno received while translating a string.");

// This could work, provided that another function calls t() using a
// literal string that is equal to the string returned from the function.
$error = t(mymodule_get_error());

The second step is providing the translation of the string passed to t(). If the theme is hosted on Drupal.org, then the translation will be provided from translators on http://localize.drupal.org.
Otherwise, you need to translate the string on admin/build/translate/search.

You can look for the string to translate searching for untranslated strings, or entering a string.

you should use something like t('your string');


No way to install or add libraries? I've been trying to set up a site on Acquia for a good 3 days now, and am baffled - Acquia doesn't allow Composer, the Acquia Dev Desktop does not sync libraries.  I've tried ludwig with no luck.

Is there any way to add csv/league libraries to Acquia? W/o this capability, I'm not sure how useful Acquia is, or am I missing something simple?

Acquia has to have the full site, core, modules, themes, libraries, et.al. checked into their git repo in the format like:

git root
  docroot
    core
    modules
    themes
    etc.
    (includes index.php and other root files)

As Clive said, there is a pay for it CI process.  However, for the normal sites, you need to manage the site as a whole entity.  They do have Deployment hooks, but that is generally for clearing cache and the like.

FYI - I use composer on all my sites.  You run it locally and check in the composer files to the repo (e.g. the composer.lock, etc.).  Things like js libraries are added by manually adding repo's to the composer.json file if they are not composer friendly. E.g., here's how the jquery chosen plugin gets added:

"harvesthq.chosen": {
  "type" : "package",
  "package" : {
    "name" : "harvesthq/chosen",
    "version" : "1.8.7",
    "type" : "drupal-library",
    "dist" : {
      "url" : "https://github.com/harvesthq/chosen/releases/download/v1.8.7/chosen_v1.8.7.zip",
      "type" : "zip"
    },
    "require" : {
      "composer/installers" : "^1.2.0"
    }
  }
},

It's also best to have the Drupal friendly paths defined in your composer file.  E.g.:

"extra" : {
    "installer-paths" : {
        "docroot/core" : [
            "type:drupal-core"
        ],
        "docroot/libraries/{$name}" : [
            "type:drupal-library"
        ],
        "docroot/modules/contrib/{$name}" : [
            "type:drupal-module"
        ],
        "docroot/themes/contrib/{$name}" : [
            "type:drupal-theme"
        ]

These make sure things get placed properly by composer.

Acquia dev desktop comes with composer and drush installed already.

You can also install composer on your machine by following the instructions here: https://getcomposer.org/download/

There is a good tutorial here to get you set up with a Drupal 8 site package built with composer here:
https://www.youtube.com/watch?v=IhWAegz8glk

The github project for that Drupal 8 composer package is here: https://github.com/drupal-composer/drupal-project

You can then open a command window in devdesktop/Sites/your-new-d8-site/Web (the root of the site you are building in dev) and then run for example composer require "drupal/commerce"  This will pull in all the dependencies (and libraries) for Drupal Commerce 2 very easily without fussing with ludwig. it's very fast and easy.

Also here is a good video here on installing modules with composer:
https://modulesunraveled.com/drupal-8-composer-and-configuration-management/installing-and-uninstalling-modules-composer

Hope this helps!


Views: URL Alias as a field How do I get the URL alias of a node in views.

Here is a previous question, Get a url alias as a field value?
However, the Content: Link field outputs something along the lines of

view

I want to wrap the link around another field using rewrite results and tokens.  Something like

[product:image]

I was able to do this with

[product:image]

However, I would rather have it show the node alias than the node ID.

If you click on Content: Path it will give you the a field that repesents the path of the node.

Have you ever tried the Views PHP module?  You could use it to do something like the following:

<a href="<?php print url('node/'.$data->nid)?>">Print Image Here

Mind you, you will need to have the image field added before the PHP field. You will also need to exclude it so it doesn't show up twice.


Failing to create thumbnail, medium and large images When using a new installation of Drupal 7.10, I have set the directory for public uploads to sites/uploads.

When I then add an image to a content instance, I get the original uploaded to sites/example.org/files/imagename.png as expected. However, the other images (thumbnail, medium and large) do not get created at sites/example.org/styles/*.

The directory is readable and writeable by the PHP5-FPM user, and so there should be no issue permissions wise.

Why does this happen? How can I fix it?

Right, the answer is in fact a little more subtle than I realised. Turns out that D7's imagecache replacement needs some attention in your nginx vhost. Without the 404s being sent to Drupal for the missing files, the images are not created - something I didn't realise initially, as I'd assumed they were created on upload.

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
}

It needs to be added to your server definition, and you should be ready to roll. Clearly, the path may need altering for your setup, but for mine it was.

Check you .htaccess file in root and files directory. Replace with the new .htaccess file if required


How do I include a JavaScript file and pass the value of a PHP variable with a single function call? I'm trying to pass a PHP variable to my JavaScript file. The file is js/backgroundConfig.js, it's in the theme directory, and this is the content of the file.

(function($, Drupal){
  Drupal.behaviors.backgroundAnimation = {
    attach: function(context, settings) {
      alert(Drupal.settings.variableName);
      alert(Drupal.settings.basePath);
    }
  };
})(jQuery, Drupal);

Drupal.settings.basePath is displayed correctly, but I've no idea how to pass variableName from template.php. I've tried a couple of methods but none of them work.

There are tons of examples on the web but none of them contains the filename and the settings together. Like this one:

drupal_add_js(array('variableName' => 'value'), 'setting');

Alright, but where I should put my filename? I always add my JavaScript file like this.

drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

How do I combine it together?

How to combine it togather?

You don't - Javascript files and settings are two completely different things. Anything you add to the settings will be available on the global Drupal object, which will be available by the time the code in your JS file is invoked.

Your code should be:

drupal_add_js(array('variableName' => 'value'), 'setting');
drupal_add_js(path_to_theme().'/js/backgroundConfig.js');

Or the other way round, it really doesn't matter.

Suppose there is some function in template.php

function THEMENAME_preprocess_page(&$vars) {
  drupal_add_js(array('backgroundAnimation' => array('variableSetting' => 'VariableSetting_output', 'variableSetting1' => 'Himanshu')), array('type' => 'setting'));
  drupal_add_js(path_to_theme().'/js/backgroundConfig.js');
}

Place the file backgroundConfig.js at proper location.
Then in JS file write like

(function ($) {
Drupal.behaviors.backgroundAnimation = {
    attach: function (context, settings) {
        alert('js file loaded');
        console.log(settings);
        alert('basePath is ' + settings.basePath);
        alert(settings.backgroundAnimation.variableSetting);
        alert(settings.backgroundAnimation.variableSetting1);
    }
};

})(jQuery);


Fatal error: Class name must be a valid object or a string in /home/dsmedia/blog/public_html/includes/common.inc on line 7749 I installed a module in drupal called Views Media Browser, that is when I first noticed the issue.

I properly uninstalled the module (unchecked it, uninstalled it, then removed the folder from my sites/all/modules folder).  Now when I go to any article content I've created I am welcomed to the above mentioned error.

I checked the file and the location of it mentioned in the error

/**
 * Get the entity controller class for an entity type.
 */
function entity_get_controller($entity_type) {
  $controllers = &drupal_static(__FUNCTION__, array());
  if (!isset($controllers[$entity_type])) {
    $type_info = entity_get_info($entity_type);
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);
  }
  return $controllers[$entity_type];
}

I even compared it to a vanilla version of Drupal and the files are the same.

I noticed that it does not occur with basic pages or any other content type I have. I would prefer not to have to restart the site, so if there is a way to correct this fatal error I would appreciate it.

I had a similar issue today (same error message) and I just solved it. It concerns my personal case, but if the description can help anyone :
the problem was the fact that I had created a few items with a content type that I deleted since. So these non published items had an invalid class, because the content type was not existing anymore.
I found these 3 items in the list of content with a blank space instead of the content type name.
Deleting these 3 items, and then extracting/importing the database again to the customer made it work.

The stange thing is that my version of the site was still working since I deleted the content type, so I couldn't understand why suddenly this problem when migrating the site.

This issue has been raised and closed (without repair) a huge number of times (more than 50 that I can see). It is, admittedly, a tough one to find. I have entered the issue. I have tracked down the actual cause, but the intricacies of the cache are a bit beyond me.

Clearing the cache could help here. Sadly, you can't always get there, largely because drush cc will also blow up when this error is occurring. So will anything having to do with accessing a user (in my case). . Requiring a user to clear the cache every time this occurs is improper by its nature - you can't have a user do a workaround as a normal course of business.

This is the tip of the iceberg on this problem. (the PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522).

[[[[in 7.28, at line 7855, 6 = ]]]]

$class = $type_info['controller class'];
$controllers[$entity_type] = new $class($entity_type);

The symptom appears because the search for the element ['controller class'] is presumed to be successful. It is not, and no secondary message (such as in a try / catch or an actual test here) is generated.

The issue stems from, for whatever reason, not being able to obtain a $class value from the $type_info array by executing module_invoke_all('entity_info'). Certainly a call time pass by reference could do it, but that would normally be caught. The actual problem is in /includes/common.inc at 7644.

  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
        $entity_info[$name] += array(
          'fieldable' => FALSE,
          'controller class' => 'DrupalDefaultEntityController',
          'static cache' => TRUE,
          'field cache' => TRUE,
          'load hook' => $name . '_load',
          'bundles' => array(),
          'view modes' => array(),
          'entity keys' => array(),
          'translation' => array(),
        );
        $entity_info[$name]['entity keys'] += array(
          'revision' => '',
          'bundle' => '',
        );
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
          $entity_info[$name]['view modes'][$view_mode] += array(
            'custom settings' => FALSE,
          );
        }
        // If no bundle key is provided, assume a single bundle, named after
        // the entity type.
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
        }
        // Prepare entity schema fields SQL info for
        // DrupalEntityControllerInterface::buildQuery().
        if (isset($entity_info[$name]['base table'])) {
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
          if (isset($entity_info[$name]['revision table'])) {
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
          }
        }
      }
      // Let other modules alter the entity info.
      drupal_alter('entity_info', $entity_info);
      cache_set("entity_info:$langcode", $entity_info);
    }
  }

Notice that if the condition is true in the if at

if ($cache = cache_get("entity_info:$langcode")) {
  $entity_info = $cache->data;
}

then the module_invoke_all('entity_info') is never executed.
It just happens that the condition is always met after some other processing is done to create the cache. That means that there is no way to get the entity_info set up --- in my case there was no way to obtain the 'user' entity info, causing the original error above. I made the 'else' one level higher (took out the 'else {}') for testing, and everything worked as it should to clear the error.

I believe that the real bug is that the checking of cache is less than adequate, and that a check on the existence of the entity_info about the specific entity being searched for is needed. In fact, it may be justifiable to also search for the element ['controller class'] for that entity in the entity_info stored in cache.
D


Pathauto for a multilingual site not generating alias for non-default languages I have a site with 90% content in Chinese, and only 10% in English.

Thus the requirement of the client is that when viewing an article in English, everything around it remains in Chinese. Blocks, menus etc

a) Enable language prefix

What this does is sets english article with en/[node:title] which is acceptable. But the problem occurs as it appends that to every url in the menu, and other places. So they become like en/categories/CHINESE-CHARACTERS which is not right, and no content is displayed.

In pathauto for English articles, I thus tried, specifically giving it [node:title]. Yet it prepends the en.

b) Disable language prefix.

Now all my links are fine. But the english article is now a node/[nid]. The url aliases just don't seem to be working in this case. If I could just have the URL alias working in this case, things would be great too.

Any solution to my misery is welcome.

Aliases indeed disappear from nodes with non-default language after disabling language prefix in URLs. The solution to that is easy, but you have to do it in code, using Pathauto's hook_pathauto_alias_alter().

Basically all you need to do is:

function yourcustommodule_pathauto_alias_alter(&$alias, array &$context) {
  // Force all aliases to be saved as language neutral.
  $context['language'] = LANGUAGE_NONE;
}

This way you make sure that the language of the saved alias (not of node!) will always be und, meaning it will show for nodes of all languages.

Note: For existing aliases it is not enough to re-save the node. You have to delete the alias first and then have it recreated. Often the easiest is to do it in bulk via Pathauto's configuration interface. First delete all paths, then bulk-recreate them.

For more, see https://www.drupal.org/node/1234924


How do I redirect a form after has been submitted? I need to upgrade this Drupal 6 code to Drupal 7.

I add a form submission handler to a form, using an implementation of hook_form_alter() that executes the following code.

array_unshift($form['buttons']['submit']['#submit'], 'MODULE_case_form_pre_submit');
$form['buttons']['submit']['#submit'][] = 'MODULE_case_form_submit';

The code for MODULE_case_form_submit() is the following.

function MODULE_case_form_submit($form, &$form_state) {
  if ($form_state['values']['type'] == 'case_slide') {
    $form_state['redirect'] = 'case/' . $form_state['values']['cid'];
    return;
  }
}

There isn't anything different between Drupal 6, and Drupal 7, for the code you are showing, which means:

$form_state['values'] still contains the values submitted from the users
$form_state['redirect'] is still used to redirect the users to a different page

What changes is that the submission buttons for the node edit form are inside $form['actions'].

  // Add the buttons.
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
    '#value' => t('Save'),
    '#weight' => 5,
    '#submit' => array('node_form_submit'),
  );
  $form['actions']['preview'] = array(
    '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_DISABLED,
    '#type' => 'submit',
    '#value' => t('Preview'),
    '#weight' => 10,
    '#submit' => array('node_form_build_preview'),
  );
  if (!empty($node->nid) && node_access('delete', $node)) {
    $form['actions']['delete'] = array(
      '#type' => 'submit',
      '#value' => t('Delete'),
      '#weight' => 15,
      '#submit' => array('node_form_delete_submit'),
    );
  }

I solved it by using the following code in hook_node_insert(). It works now.

drupal_goto("content/$title");


Multiple Images from external WEB URL My problem is simple though multiple solutions touch upon it but none address it directly. Hence posting this question.

Problem: I have multiple servlet urls (hosted at external web server)
that returns a single image in response stream. My task is to embed
images from these (precisely 6) URLs in my drupal site. How can I do
that.
Attempts: I tried using Media Module, Embedd Media Module,
Custom formatters but none worked for me (may be because I'm a
beginner). If anyone can help me with some sort of link of steps to achieve this.

I achieved it in a work-around. I am downloading images inside my drupal accessible folders with the fixed names. Updating these images with fixed names using a background script. Applied cache buster techniques so that images with same names are updated.


Change some charachter in All field before saving node I want done a action (change some charachter) on every field in saving node.
I know for specified field can use hook_node_presave ,but I want do this on all field in all content type (proximity 300 field  and 40 content types) with out specify one by one .
Have drupal api for hook_filed_presave or something like it?

This is work for specified field

function custom_changes_node_presave($node){

    if ($node->type ==='designer_background_images'){

        $filename =$node->original->field_db_image['und']['0']['filename'];
        $uri       =$node->original->field_db_image['und']['0']['uri'];

        $filename    = str_replace (" ", "_", $filename);
        $uri        = str_replace (" ", "_", $uri);

        $node->original->field_db_image['und']['0']['filename']= $filename;
        $node->original->field_db_image['und']['0']['uri']       = $uri;

        //field_attach_presave('node', $node);

            // And the actual field change for the given node (e.g. entity).

        //field_attach_update('node', $node);

        // echo "<pre>";
            // print_r($node);
        // exit;
        // print $node->original->field_db_image['und']['0']['filename'];
        // print $node->original->field_db_image['und']['0']['uri'];
    }
}

You're probably looking for hook_entity_presave():

  Act on an entity before it is about to be created or updated.

It's equivalent to hook_node_presave(), but as the name suggests is run for all entity types.

From there you can use the Field Info API functions to get a list of fields that should be attached to that entity, then loop through them and do the character replacement.

You can do it with this modules:

http://drupal.org/project/transliteration Transliteration help you to
fix the name of fields.
http://drupal.org/project/filefield_paths helps you tu put the fields in it's folder.
Also you should use Token for filefield_pahts.

This 3 modules are a "must have" in every drupal projects with fields.

If they are all values, you should activated the "Retroactive update" to update all the old fields.

Oskar


Why are the edit/delete/reply links missing in the Comment module? I'm using 8.6.0 core's Comment module. I can add comments, but I can't edit or delete them. I also can't reply to anyone else's.

Permissions have been set that all authenticated roles can edit. I'm even an admin and nothing.

I even looked at the comment.html.twig template. I don't see any of those links. The only link showing is {{ permalink }}. The variables also don't supply any of the links I require.

I looked around and can't find anything related to Drupal 8.

It ended up being layout builder. Enabled full content and layout builder, cleared cache and it worked.


How to prevent CKEditor from removing content and tags written in source? I'd like to be able to use things such as the  tag for purposes of using font awesome icons, but CKEditor strips tags like this. If I place
 when in 'source' mode in ckeditor it gets removed as soon as I return to the standard mode. Is there a way to ensure that ckeditor allows these tags?

I saw that someone provided a solution here How to stop CKEditor 3.6.3.7474 from stripping <script> tags however in drupal 8 admin/config/content/ckeditor/edit/advanced does not exist.

I also saw the CKEditorPluginConfigurableInterface here https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginConfigurableInterface.php/interface/CKEditorPluginConfigurableInterface/8.2.x
But I wasn't sure how to make use of that.

Is there a way to prevent CKEditor from removing content and tags written in 'source'?

I had the same requirement, I followed this tutorial for that, How to Display Icons in Drupal using Icon API.

It needs two modules (1) Fontawesome and its dependencies Library module & Fontawesome Library. (2) Other module you need is Icon API which has sub-module Icon_filter that will convert the icons in the images.

I am afraid that Icon API module will work for D8 or not, but it has D8 version but unstable as you can see on the module page.

I am using this way on D7 site.

Update: Filter setting

CKeditor has Content Filtering feature,

  Configure input data filtering in CKEditor. See this blog post for more information about ACF.

By the way, there are two solutions to prevent CKEditor  filter contents,
one easy solution is to Disabled "Advanced Filtering Feature" at admin/config/content/ckeditor/edit/Full  but I don't recommend it in all cases , better solution is specified your tags at admin/config/content/ckeditor/edit/Fullz > Extra allowed content > Extra allowed content  enter you desire tags, as an example I told ckeditor, Hey Boy,Please don't filter scripts in my contents


Mapping field columns with D8 migrate and d7_node source plugin I'm trying to write a D8 migrations files but the following one isn't working on the source 'body/value' because it resolves to a null value instead of the intended string.

id: my_d7_node_news
label: 'Nodes (News)'
langcode: en
status: true
dependencies: {  }
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
source:
  plugin: d7_node
  node_type: news
process:
  nid: tnid
  vid: vid
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  'body/value':
    plugin: get
    source: 'body/value'
  'body/summary':
    plugin: default_value
    default_value: some summary
  'body/format':
    plugin: default_value
    default_value: rich_text
destination:
  plugin: 'entity:node'
  default_bundle: news

I tried multiple writing for the source: 'body/value' (e,g: source: body_value, etc, ...) with no luck...

Which syntax should I use to make successful mapping on body/value: body/value using the d7_node source plugin?

Something like this:

  body:
    plugin: iterator
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: filtered_html

Just use 'body', as in:

body: body

That is what core d7_node migration does.


Using as shipping address the value entered as billing address In Drupal Commerce 2 how can we allow a customer to select as shipping address the same address entered as billing address?

Yes, you can try to custom jquery event.
1.To create a custom js file in your theme folder (/themes/theme-name/js)
Triger Function Like:
$("select[name='panes[delivery][select_address]']").change(function()
{
//your code
//.....
});

Thanks


How to Split content in drupal 7? I am new to drupal and drupal 7, I saw a video tutorial previous day regarding drupal 6, there they just used this:

print $content;
print $title;

to display post title and content separately however, in drupal 7 , I copied one of theme page.tpl.php file and there is only  this:

 <?php print render($page['content']); ?>

This shows full content inlcuding everything, how do I split them into parts like:

I want to customize my template like this

Welcome to My site // for header

                            Some text Portion //

This should be same for individual page and front page that shows 2 or 3 posts.

I tried making custom node.tpl.php file too, should I add some special function call to make it able to load content from node.tpl.php file ?

I pasted this code in template to render from page.tpl.php file of my theme

function connect_preprocess_page(&$vars) {
if (isset($vars['node']->type)) {
    $nodetype = $vars['node']->type;
    $vars['theme_hook_suggestions'][] = 'page__' . $nodetype;
}
}

In page.tpl.php leave where ever you wants: <?php print render($page['content']); ?> and then use node--YOUR_NODE_TYPE.tpl.php and put content where ever you want. You habe $node object print it and see what variables it has.
Make sure that you also have node.tpl.php - initial template file in your theme folder.


List All vocabularies and their terms How can i list my vocabularies and their terms in this way . Is there a module that can help me to do this . or i should go with custom VIEW and jQuery.

thanks :)

You can do with Taxonomy Term Reference Tree Widget module.

  This module provides an expandable tree widget for the Taxonomy Term
  Reference field in Drupal 7. This widget is intended to serve as a
  replacement for Drupal's core Taxonomy Term Reference widget, which is
  a flat list of radio buttons or checkboxes and not necessarily fit for
  medium to large taxonomy trees.


create drupal 7 webform programmatically? I have already created a webform and I need to fill it programatically.

how can I create webform ? Can i create it like node creation:

$node = new stdClass()
$node->type = 'webform'
$node->webform['components'][1]['value'] =  'sss'

See code below:

function _add_webform_components($node) {
  $components = array(
    0 => array(
      'name' => 'First name',
      'form_key' => 'first_name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 1,
      'pid' => 0
    ),
    1 => array(
      'name' => 'Name',
      'form_key' => 'name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 2,
      'pid' => 0
    ),
    ... and so on

  );

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }
  $email = array(
    'nid' => $node->nid,
    'email' => 'name@example.ch',
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);
}

You can make use of drupal_form_submit  I didn't tried it.

Anyway this may can help you.

  This function allows you to supply values for form elements and submit
  a form for processing.

The idea is to find the form_id check for the form fields and

// register a new user
$form_state = array();
$form_state['values']['xxx'] = 'yyyyy';
drupal_form_submit('xxx', $form_state);

Give a try and please paste the code here if you succeed.


Are service autowiring and class autoresolving not anymore supported? In Drupal 8, I needed to define services via the mymodule.services.yml file only, if I wanted to use them via the service container. I could also autowire them and the classes were automatically resolved.
services:
  my_module.twitter_feed:
    class: Drupal\my_module\TwitterFeed
    autowire: true

  domcrawler.crawler:
    class: Symfony\Component\DomCrawler\Crawler
    public: false

In Drupal 9, it looks like I must define all my custom classes inside the mymodule.services.yml file. Drupal 9 seems not to be able to identify my classes without an entry within the mymodule.services.yml file. There seems to be no autoresolving anymore. Symfony 4 and 5 are able to do that and Symfony 3.x (Drupal 8) was definitely able to autowire services and find classes by its own. Drupal seems to have its own service container, which suppresses that functionality.
Defining every single PHP class within a *.services.yml file is a huge amount of work for upgrading and maintaining my project. I cannot believe that Drupal 9 requires this work, because the Symfony framework already does that automatically.
Do you know any way to re-enable PHP class autowiring and autoresolving in an upgrade from Drupal 8 to 9?
I hope that anybody else was struggling with autowiring during an upgrade from Drupal 8 to 9 and knows any solution.

I found out, that in Drupal 9 some autowiring "magic" from Drupal 8 was removed. Drupal also overrides the Symfony dependency injection by its own logic. Therefor you must write your own service provider class in your module to autowire your service containers (basically all PHP classes, except e.g. Drupal Plugins or Drupal Entities, which Drupal 9 resolves by its own).
Like this (path: modules/custom/my_nice_module/MyNiceModuleServiceProvider.php):
<?php
declare(strict_types=1);

namespace Drupal\my_nice_module;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Finder\Finder;

class MyNiceModuleServiceProvider extends ServiceProviderBase {

  public function register(ContainerBuilder $container) {
    $containerModules = $container->getParameter('container.modules');
    $finder = new Finder();

    $foldersWithServiceContainers = [];

    $foldersWithServiceContainers['Drupal\my_nice_module\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Transformer\RegionalCouncilMeeting\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Transformer/RegionalCouncilMeeting/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\DomCrawler\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DomCrawler/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\MongoDBFetcher\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/MongoDBFetcher/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\MongoDB\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/MongoDB/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Importer\RegionalCouncilMeetingsArchive\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Importer/RegionalCouncilMeetingsArchive/')->files()->name('*.php');

    $foldersWithServiceContainers['Drupal\my_nice_module\Entity\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Entity/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Extractor\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Extractor/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\Service\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/Service/')->files()->name('*.php');
    $foldersWithServiceContainers['Drupal\my_nice_module\DrushCommandFacade\\'] = $finder->in(dirname($containerModules['my_nice_module']['pathname']) . '/src/DrushCommandFacade/')->files()->name('*.php');

    foreach ($foldersWithServiceContainers as $namespace => $files) {
      foreach ($finder as $fileInfo) {
        $class = $namespace
          . substr($fileInfo->getFilename(), 0, -4);
        // don't override any existing service
        if ($container->hasDefinition($class)) {
          continue;
        }
        $definition = new Definition($class);
        $definition->setAutowired(TRUE);
        $container->setDefinition($class, $definition);
      }
    }
  }

}

Here is a good presentation about this: https://events.drupal.org/sites/default/files/slides/drupalcon.2019.autowiring.pdf
The Autoservices Drupal module can also be a good example for your own solution: https://gitlab.com/upstreamable/drupal-autoservices


Views - user/role has access to edit node I'm trying to set a view that shows only the nodes that current user or role has access to edit. I've tried with contextual filters and relationships but with no luck. Anyone know how to restrict it?

Views accessed can be controlled by Views Access configuration, check the screen shots if it helps.

Step 1: Find the Views Access Configuration

Step 2 : Opt the permissions, which suit your needs

Step 3 : Configure the permissions

In Drupal 7 with Views 3 and Views PHP it can be done in one step. Create a Global PHP Filter and in the Filter code add:

return !node_access('update', node_load($data->nid));


How to get an editable cart at checkout with Drupal Commerce? I always used Commerce Kickstart as a starting point for making e-commerce stores, but this time I opted to go with pure drupal + commerce modules.

One problem I have is that the cart view I get when I enter the checkout process is non-editable: it's just the list of items. The view used by the checkout is "Shopping cart form (Commerce Order)", and the cart uses Shopping cart summary (Commerce Order). The latter has "remove" button in rows and an "update cart " link. Actually, I was able to replicate the elements of the formerin tha latter, save for the update" cart link.

I can get the one I am used to by going to view cart, but I do not get this one on chceckout. I tried to change settings at admin/commerce/config/checkout/form/pane/cart_content, but I can't  get the desired result.

Any Ideas?

The module Commerce cart form checkout pane does this very well.


How do I change a field type from integer to decimal? I have some fields type integer that are already populated, is possible to change the fields from integer to decimal?

Ok, I found a good solution to solve my problem.

Modules required

Helper
Devel (this is not strictly necessary)

Steps

Enable Helper module;
Enable Devel module;
Enable the block Execute PHP;
Paste and execute this code in the block: FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);

If you don't want use Devel and can use Drush:

Enable Helper module;
create a new file in root Drupal folder, i.e. name it: intToField.php

<?php
FieldChangeHelper::changeType('field_myintegerfield', 'number_decimal');
?>
launch the drush command: drush src intToField.php
Delete the file;
Edit display format for node where the field is being used;
Edit Views where the field is being used to fix the format settings (If necessary);


How to remove modules via ftp? I need to know how to remove modules via ftp, i activated some modules, and now im getting constantly errors like

  Fatal error: Call to undefined function views_include() in /home/a7898297/public_html/sites/all/modules/eva/eva.module on line 113

so how can i remove custom modules?

You need to disable the module on http://example.com/admin/modules first. That should take care of your error messages.

If your administration interface is not accessible - caused by the error message - you could access the database directly and disable the module in the system table - as suggested by Mołot and outlined in https://drupal.org/node/157632.

Additionally to disabling the module, you should also uninstall it - which will remove any configuration and data associated with this module from the database: http://example.com/admin/modules/uninstall (at least it should, if it is properly written).

Now, you can safely remove the module from the modules directory, if you want to. Since the module is disabled and uninstalled, it will not interfere with your Drupal installation, however, it is advisable to clean up the modules directory, and move the module to a location outside the webroot - to avoid issues if the module has security holes and the web-server is (mis)configured to allow direct execution of modules.

Before you do all this, I would save a backup of the database and the custom module, in case the functionality and data might be needed after all.

You can of course do all of this also on the command line using drush - since you asked about ftp, I assume you do not have ssh access.

You must install the FireFtp addon in Mozilla Firefox, connect the host, and delete the modules. That is not working for you. You must disable modules from admin/modules and uninstall them from admin/modules/uninstall; that would delete any database table that the modules created.

I would recommended to edit modules/eva/eva.module on line 113, and delete the views_include() function; after that, disable and uninstall the modules.


How to attach a view display switch to a view? I am wondering how I can attach a switch/ link from one view display to another view display within the same view. I can only think of messing around in the template files and hardcoding this navigation.

What is the best solution/ is there a better solution for that?

Update: both displays shall have a own url this for caching and possibility to link to a specific display.

myview/(default: display-table)
myview/display-table
myview/display-list

Display Suite

A possible solution to this is probably utilizing display suite.

You could trigger a link using display suite & display suite extras to open different view mode. The drawback to this is that the user would have to load a different page.

Quicktabs

Another solution would be to load the two views as blocks and use quicktabs to display the two views in that tab format you require. The drawback to this solution is that you have two views loaded.

Views Header

At the top of your views, just add a header anchor to your other views page. This solution is best if you just have one view where this output is being displayed. Otherwise, it would be difficult to maintain duplicate views.

I actually found a good solution for this problem using the built-in menu system, providing menu links to these view pages and attaching the menu to the view using context module.

This works even better with Icon API