How to redirect users to log in page when they try to access the order page, but not when they try to check out I'm using Checkout Login module that adds an inline login form to the account information checkout pane. No anonymous users have to activate their accounts to complete checkout or payment, which is all I want. However, after the PayPal redirects users back to my site, and users try to access the order (order history) page, the following message appears:

  You are not authorized to access this page.

Is there a way I can re-direct users to login page when they try to access the order page, rather than the above message appearing?

In short, I want my users to be redirected to login page when they try to access order (order history) page, but not when they try to checkout.

That's one of the main features of the LoginToboggan module.

When the Present login form on access denied (403) is enabled in its setting form, any access denied page will display a login page. Upon login, users are redirected back to the previously requested path.


drupal_static() uses a FUNCTION variable,what does it mean? function drupal_set_page_content($content = NULL) {
  $content_block = &drupal_static(__FUNCTION__, NULL);
  $main_content_display = &drupal_static('system_main_content_added', FALSE);

  if (!empty($content)) {
    $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
  }
  else {
    $main_content_display = TRUE;
    return $content_block;
  }
}

This snippet is pasted from common.inc. We pass in a __FUNCTION__ to  drupal_static() but I do not know what this variable means. Does it mean a cache for the outer function itself? How does it work? I do not see any data handled inside the function before it returns $content_block.

__FUNCTION__ is one of the so-called Magic Constants of PHP.

All it does is return a string with the name of the function that the constant is contained in.

For example:

function my_strangely_named_function() {
  print __FUNCTION__;
}

The above will print 'my_strangely_named_function'.

Drupal uses this constant with its static cache so that each cache is identifiable from any other function, and as such can be identifiably cleared.

To use an abridged version of your code:

function drupal_set_page_content($content = NULL) {
  $content_block = &drupal_static(__FUNCTION__, NULL);
}

Any other function in the Drupal lifecycle can call:

drupal_static_reset('drupal_set_page_content');

And that will clear the cache for that specific function, so that next time it's called the data is built up as if from new.

That's just the basic use of the static cache pattern, you can find more information and examples on the documentation page for drupal_static() itself.


How to add custom class on the menu block using twig? I'm new in Drupal 8 and i'm trying to display my primary menu block using twig as below

 {% if page.primary_menu %}
   {{ page.primary_menu }}
 {% endif %}

which gives me like this

      <a href="/drupal8/" data-drupal-link-system-path="<front>" class="is-active">About

      <a href="/drupal8/" data-drupal-link-system-path="<front>" class="is-active">Home

I want to add my custom class attributes on ul  and a elements to get the menu like this

      <a href="#about" data-drupal-link-system-path="<front>" class="page-scroll">About

      <a href="#home" data-drupal-link-system-path="<front>" class="page-scroll">Home

How can i add my custom class on the menu? If you have any idea about this problem then please help me. Thank you.

You can do this by creating template file called "menu--main.html" in your theme's template folder.

Then in place below code in that file:

{% import _self as menus %}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {% if menu_level == 0 and item.is_expanded %}

    {{ item.title }}

      {% else %}

        {{ link(item.title, item.url) }}
      {% endif %}
      {% if item.below %}
        {{ menus.menu_links(item.below, attributes.removeClass('nav', 'navbar-nav'), menu_level + 1) }}
      {% endif %}

{% endfor %}

  {% endif %}
{% endmacro %}

This will add the class "ul"


How to change the style of the pages title in a view? I've created a content type view using teasers. The titles are all H1s. How to change that to H3, for example?

Is this just a case of CCS?

Open firebug to see what are the ancestors of the h1, there should be a name that contains the content type or view, you can easily set:

.WRAPPER-OF-CONTENT-TYPE h1{
    //here is your css style
}


How to secure access to a Forena data block? I have set up an external database source using the Forena reports module and the PDO driver. This data source has its data security method set to "Use Drupal permissions". The only other option is "Match values provided by a data block".

There is a matching Drupal permission for the data source in admin/people/permissions labelled "Access MyDB data". (Machine name "access my_db data"). The "Access MyDB data" permission has only been granted to a couple of roles.

What I have tried:
I put a line in my .sql file for the data blocks built on this source:

--ACCESS=access my_db data

This prevents anyone from getting any results from the report based on this data block, even the Drupal administrator.

I removed the above line in the .sql file. This allows any logged in user to access the report. It does not respect the permission "Access MyDB data".

How do I set this up so that the access to this data block (and therefore the reports using it) is limited to only those who have the "access my_db data" permission?

Quote from the documentation that comes with Forena, about Data Block Security:

Data Blocks Security is a technique used to secure a selected data block. It is an additional (but optional) security layer on top of the Drupal permission "access repository name data" right (whereas "repository name" is the name of the data block's repository). Using this technique it is possible to enforce additional Drupal permissions such as:

access content
access administration pages
administer content
administer users
administer permissions
... (the (Drupal permissions) sky is the limit)

Data Blocks Security is actually implemented by means of a comment containing ACCESS=some_permission. It is added near the top of a data block which indicates the Drupal permission required to access the data retrieved by the data block. Its format depends on the format of the Data Block (which can be either in SQL format or in XML format), as further detailed below.

From the scenario in the question here, it appears to me that there is no need for adding such comment with ACCESS=some_permission, instead it should be sufficient to only use the access repository name data for those "couple of roles" that should have access to the data in the report.
Note the data in the report I wrote here: it is well possible that users who do not have the required permission for the data blocks, do have access to such "reports" anyhow. However: those reports, by design, do not show any data of the data blocks they do not have access to.
Nevertheless, I wonder if there is anything (like a bug?) that may be related to the "my_db" part of your issue. Therefor I'd recommend to also experiment with (eg) the "Drupal" reports: only grant access to these reports to "Admin" role, and then run a similar testcase. How do your results look like in that scenario? As a variation, can you (temporarily) rename "my_db" to "mydb", to check what results you then get?


Schedule node modifications? I use Scheduler when i need to public/unpublish nodes and it works pretty well, but i would like to  schedule the modification of an specific node? is there any module or something?

Take a look at Workbench Scheduler. you could make changes as a draft(or any other workbench moderation state) and let Scheduler publish it.


Get logged in user id in api calls I am working on an existing site where it has exposed api's via a custom module.

There's a new requirement where an api should only be accessed by authenticated user. For that theres a login api provided.

How can I make sure to add login information such that drupal recognises which user is making the call.

Does keeping SESSIONID in header will make drupal identify the user.

Note the API calls are made from android/ios app.

If the user is not logged into your app and if you don't let anonymous users to access the API, how can you let them to log in without accessing API?

What you can do is you can maintain a API key for your application. You should call the API using the key all the time. That should be your first check point. Then you should add that API key validation for accessing the API. Then you can give access to your login API function using that key.

Once user is successfully login to the system you can return a dynamically genarated(random) session key to your APP so that the user login to the app and he/she has a session key. From that point call the API using the session key and add validation method to validate both session key and API key.

So all API functions are accessed by logged in users only. When the user logs out from the app call a session key function to remove your key.

I think you are looking for this kind of a solution.


How to alter 'not null' value of field after creation I have a custom module that defines a field wherein I erroneously set the 'not null' value to be FALSE when I should have set it to TRUE. Ideally I would like to remedy this by means of an update hook. How can I do that?

function MYMODULE_field_schema($field) {
  $columns = array(
    'payments' => array(
      'type' => 'varchar',
      'length' => 20,
      'not null' => FALSE,
      'description' => 'Number of payments made',
    ),
  );
  return array('columns' => $columns);
}

From reading the documentation it looks like I could do it by passing a field structure to field_update_field, but I don't know what to put in the field structure

function MYOTHERMODULE_update_70xx() {

 $field = array(
    // What should I put in here in order to change 'not null' to FALSE
    // and as a bonus, change the type from 'varchar'
    // to an integer (number_integer?)
);

 field_update_field($field);
}

Am I over-simplifying things? I know it's often not possible to modify fields if they contain data, and in this particular case I can delete and re-create the content type without too much difficulty, but no point doing all of that if there's no need.

You need to ud db_change_field function to change structure of table field.

function MYOTHERMODULE_update_70xx() {
  db_change_field('tablename', 'payments', 'payments', array(
    'not null' => TRUE,
  ));
}


Link “My Workbench” is no longer visible I have installed Workbench and the Workbench Moderation modules, but My Workbench(on top with other Administration Menu) link is coming only for when user logged in as Administrator, it is not visible for user with Editor role.
I have given following permissions to Editor
Workbench

Administer Workbench settings

For Editor:
Administer Workbench settings - Yes
Access My Workbench - Yes

I posted an answer on this question:
Link "My Workbench" no longer visible

In order to have it appear in the admin menu. You need to give access to:

"Use the administration pages and help"

Because the My Workbench link is child of admin: /admin/workbench


Migrate : Update not working Im using the migrate module to import data from a json feed.
Mostly work fine however, i require that each time the feed is imported , updated records in the source are updated in the destination if they exist.

Im struggling to find much information on this or more over explicitly how to implement this kind of functionality.

I have list my code to date and would really appreciate any input someone has on this.
An example might be the same feed being imported but the aboutOurClient field updated in the source

cheers

Steve

class JSONMigration extends Migration {
  /**
   * A constructor
   */
  public function __construct() {

    parent::__construct(MigrateGroup::getInstance('json_migration'));

    $http_options = array();

    // define source definitions.... wont work with out this so hey ho
    $this->map = new MigrateSQLMap(
      $this->machineName,
      array(
        'jobref' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
        ),
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $fields = array(
      'jobref'                   => 'Job reference',
      'jobTitle'                 => 'Job title',
      'aboutOurClient'           => 'About the job',

    );

    $json_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'json_migration') . '/';
    $items_url = $json_folder . 'PEsamplejson.json';

    $this->source = new MigrateSourceList(new ExampleListJSON($items_url),
      new ExampleItemJSON($items_url, array()), $fields);

    $options = array();

    $options = array('track_changes' => 1);
    $this->destination = new MigrateDestinationNode('jsontest', $options);
    //$this->systemOfRecord = Migration::DESTINATION;

    $this->addFieldMapping('field_jobref', 'jobref');
    $this->addFieldMapping('title'       , 'jobTitle');
    $this->addFieldMapping('body'        , 'aboutOurClient');

  }

  public function prepareRow($row) {
     // i can remap/manipulate here if needs be ie date
  }

}

If you are using the Migrate UI, at the bottom of the page there is an Options slideout with the Update checkbox. If you are kicking off your migration programmatically then call prepareUpdate() before calling processImport().

migrate_static_registration(array($machine_name));
$migration = Migration::getInstance($machine_name);
$migration->prepareUpdate();
$result = $migration->processImport();


How can I theme individual fields? I have views of ubercart products which are displayed in a table by standard drupal view standards.
How can i theme individual product fields ?

views-view-field.tpl is having the complete product listed inside $output variable..
I want to solve this in a template file where all fields are available individually ..

Inside the views-view-field.tpl.php, you can use the $row variable to get your other fields.
If you're using the Devel module, just send a dsm($row); to get the path to the fields you want to access.

For example I've this inside a views field template, to check if a user have something inside the field "twitter_account" :

$twitter_account = "";
if(isset($row->field_field_twitter_account[0]['raw']['value'])){
    $twitter_account = $row->field_field_twitter_account[0]['raw']['value'];
}


Action to be triggered on Comment Approval How can add new rule to trigger when a comment approve, in Drupal 7?

Currently there is no rules condition to do this but there is a patch in the rules issue queue.
You can try using that, and if you do you can report back to that issue and help it get committed to the rules module.
http://drupal.org/node/1421058#comment-6532372


Can Webforms include the URL they were submitted from in their emails? I have a bunch of webforms in blocks on taxonomy pages.
It would be helpful for the recipient of the resulting emails to know what taxonomy page the user was on at the time they wrote their query.
Do I use the %get token in a hidden field? And if so then what [key] value returns the full (pathauto) url?
Webforms can only use %get[key] and %post[key] for non-authenticated users.

You can achieve this by using the %server token as the value of the hidden field. To be more precise http://%server[SERVER_NAME]%server[REQUEST_URI] should get you the full url (path alias is also preserved). For a complete list of options that can be used with the %server token check out the manual.

UPDATE:

The %server token only works for authenticated users since Webform version 2.8 due to potential security/privacy issues with some values. Since you only need the url in e-mails a better solution should actually be to put a appropriately themed version of <?php print url($_GET['q'], array('absolute' => TRUE)); ?> inside your copy of webform-mail.tpl.php file (or webform-mail-[node id here].tpl.php).


What's the command to migrate images too? I'm currently using Drush to migrate a Drupal 7 site to a fresh copy of Drupal 8. Everything is migrated except the image fields.

I get thousands of these warnings with different ID numbers.

  [warning] Missing file with ID 26. ImageItem.php:329
  [warning] Missing file with ID 26. ImageItem.php:329
  [warning] Missing file with ID 26. ImageItem.php:329

I'm also using WAMP to locally migrate the site and maybe I'm typing the destination public file path incorrectly. Here's some of the commands I tried.

drush migrate-upgrade --legacy-db-key=migrate --legacy-root=/wamp64/www/d7 --configure-only
drush migrate-upgrade --legacy-db-key=migrate --legacy-root=c:/wamp64/www/d7 --configure-only
drush migrate-upgrade --legacy-db-key=migrate --legacy-root=/www/d7 --configure-only
drush migrate-upgrade --legacy-db-key=migrate --legacy-root=/d7 --configure-only

What's the command to migrate images too?

Thanks!

Thanks guys for helping out! I figured it out and migrated all my images and files. Here's what I did for anyone who has the same problem:

I'm was using WAMP and WSL Ubuntu, I was setting the legacy--path incorrectly so my source_base_path was incorrect. I had to open up migrate_plus.migration.upgrade_d7_file.yml and used the correct path. Then I ran drush config-import to import the updated file and then ran the migrate.

Here's my file:

uuid: 2a4842a5-0869-4984-aaae-68d6c5814f5d
langcode: en
status: true
dependencies: {  }
id: upgrade_d7_file
class: Drupal\migrate\Plugin\Migration
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Content
migration_group: migrate_drupal_7
label: 'Public files'
source:
  plugin: d7_file
  scheme: public
  constants:
    source_base_path: /mnt/c/wamp64/www/d7
process:
  fid:
    -
      plugin: get
      source: fid
  filename:
    -
      plugin: get
      source: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
        - constants/source_base_path
        - filepath
    -
      plugin: urlencode
  uri:
    -
      plugin: file_copy
      source:
        - '@source_full_path'
        - uri
  filemime:
    -
      plugin: get
      source: filemime
  status:
    -
      plugin: get
      source: status
  created:
    -
      plugin: get
      source: timestamp
  changed:
    -
      plugin: get
      source: timestamp
  uid:
    -
      plugin: get
      source: uid
destination:
  plugin: 'entity:file'
  source_base_path: /mnt/c/wamp64/www/d7/sites/default/files/
migration_dependencies:
  required: {  }
  optional: {  }


Separate Domain users get redirected to Default domain upon login and content save I have set up Domain Access module in Drupal correctly, and everything works fine but with an issue. The issue is, that when a subdomain user logs in with his account from his assigned domain, he gets redirected to main domain and finds an access denied page. Then he manually goes to subdomain.domain.com and it works fine then. Similarly, if he save any node from his assigned domain, node works fine, is shown only upon his domain, but upon save, he is redirected to the main domain, and the node path is maindomain.com/urlalias, which causes him to show access denied.If he then goes to subdomain.com/urlalias of the node he just created, it shows fine without any problems. How to settle this issue, I have spent days sorting it out but still no success

After plenty of fatigue , I ended up removing $base_url from settings.php and the problem was solved. But still I wonder what if I have to ever to use $base_url again, the problem will again creep up.


Is there any problem with downloading and overwriting modules? Theoretically for the most part is it usually a non-issue to overwrite modules ?

Typically i would disable a module then upgrade a module. Is disabling a module superfluous?

Obviously, I'll take the steps to backup my database before doing so.

You don't need to disable a module. That is often not even possible e.g. when there are many other modules relying on it and disabling them would break your site.

You might want to take your site to maintenance mode while running updates though, as your site might completely break between replacing the files and running update.php.

What however is recommended is to remove the old files first and then add the new directory. The reason for this is that you otherwise end up with stale files if files have been moved or deleted.

If you have shell access, I can strongly recommend using drush dl/up for this task as this will handle this for you automatically.


How to show Content Titles only in Entity Reference drop down list, but restrict general access to the Content Type? Drupal 7.25

I have a list of "Locations" (content type) and need people to select an item from this list when they register on the site.

However, I do not want anonymous or authenticated users to view the detailed contents of these locations.

When I restrict the permissions on the content type, this removes all the values from the entity reference list for anonymous users when they try and register.

So is there an easy way to show ONLY the content Title field in the list, without people being able to then see all the other fields for the content type?

Thanks for any help!

OK, so the only way I found to do this was install the field_permisssions module and restrict access to all the custom fields for specific roles.

Not ideal, but achieves the objectives. There are a lot of fields and it took quite a while. Also need to remember to restrict fields when creating new ones.


warning message after uprgraded to drupal 6.38 I upgraded drupal 6.2 to drupal 6.38 to apply the security patch to ignore the vulnerabilities as mentioned in https://www.drupal.org/drupal-6.38-release-notes .

But after updating to 6.38 when i checked the status report am getting the following result .

How could i resolve this ? is there need to install any additional modules to ignore this warning ?

UPDATE

After enabling the module i got this

system_requirements will raise this warning if the core Update status  module is not installed.

To 'fix', enable the core Update status module.


Temporarily change the current language during a request Background information

I am developing a multilingual Drupal 8 commerce site where only authenticated users (customers) can place orders (anonymous users can't place orders). Customers can edit their preferred language using the default language field on their account. After an order is placed, another user with a special role (webmaster) has to prepare the order and physically fill a box with the contents of the order. When the webmaster is ready, he performs a transition on the order changing it's state. This transition triggers an e-mail that is sent to the customer, informing him that his order is ready for shipment. This e-mail is triggered through an event subscriber that reacts on the shipping transition of orders. The e-mail is formed by rendering a custom template.

Problem

A customer who's preferred language is Dutch, has placed an order. A webmaster is using the website in English and sets the order 'ready for shipment'. The customer gets an English e-mail while he should get a Dutch e-mail.

Code

The code that triggers the e-mail:

/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $event->getEntity();

$to = $order->getCustomer()->getEmail();
$langcode = $order->getCustomer()->getPreferredLangcode();
$subject = $this->t('Your order #@order_number is packed', ['@order_number' => $order->getOrderNumber()], ['langcode' => $langcode]);

$build = [
  '#theme' => 'commerce_order_shipped_mail',
  '#subject' => $subject,
  '#order_number' => $order->getOrderNumber(),
  '#order_date' => $this->dateFormatter->format($order->getCompletedTime(), 'default_date_only'),
  '#order_url' => Url::fromRoute('entity.commerce_order.user_view', [
    'user' => $order->getCustomer()->id(),
    'commerce_order' => $order->id(),
  ], ['absolute' => TRUE]),
];

$mail = $this->mailManager->mail('order_shipped_mail', $to, $subject, $build, $langcode);

The mail function of the mail manger (wrapper):

$name = \Drupal::config('system.site')->get('name');
$email = \Drupal::config('system.site')->get('mail');
$from = '"' . $name . '" <' . $email . '>';

$params = [
  'headers' => [
    'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
    'Content-Transfer-Encoding' => '8Bit',
    'From' => $from,
  ],
  'from' => $from,
  'subject' => $subject,
  'body' => $this->renderer->renderRoot($body),
];

$langcode = $langcode ?: $this->languageManager->getDefaultLanguage()->getId();

return $this->mailManager->mail('XXX_general', $key, $to, $langcode, $params);

The custom template:

{{ 'Shipping confirmation'|t }}

{{ 'Dear customer,'|t }}

            {% trans %}
            Your order #{{ order_number }} of {{ order_date }} has been handed over to XXX.

            You will receive an email from XXX with the tracking information of your package.
            {% endtrans %}

{{ 'Order details'|t }}

The XXX team

As you can see a custom template is rendered that contains the body of the e-mail.

Actual question

How can I temporarily change the current language during a request so rendering happens in the correct language? I know I can give a langcode to a t-function but my rendered order URL would still be an English URL so this doesn't fix the problem. I have tried suggestions from here, and I thought the LanguageNegotiation Plugin would do the trick, but it doesn't.

Please excuse me if my question is malformed or if I provided to little information.

See How to progragrammatically get NodeType translated value in D8?, that example is actually based on user_mail() which has exactly the same use case, to send things like password reset e-mails in the language that the user set in his profile.

That will however only work for stored configuration. I think you can't easily change the active interface language, what you can do is explicitly pass the language to each t() call, also inside twig, at least for t().

The only thing I can think of right now that might allow to override it is do a fake negotiator, set that with setNegotiator() on the language manager, then at the end set back the original one.


Using Views to Display Taxonomy Terms Along with a single image field of the latest content type that has that taxonomy term Let's say I have the following content type called Gallery that has an image field and a term reference field that can contain multiple terms from a single vocabulary.

In addition, I have several contents of these content types that share terms.

Would it be possible to create a view so that it satisfies the following conditions?

List all terms from a certain vocabulary
Have each term accompanied by an image (from the image field) from only the Gallery content type that uses that term
Term and Image should be listed once. If the term is being used by more than one Gallery content, the term should appear with the image from the latest content using that specific term.

The first two conditions are very straightforward to accomplish, independently. But once I try to accomplish both at the same time, I end with a display of all images paired with a single term it's associated with.

If that image is tagged with three different terms, then that same image appears three times, each instance using each of the terms.

Further, if one term is used for x number of different content, then that term will appear x number of times.

Was just wondering if there's a way to set it up so that it's 1 term, 1 image (preferably from the latest content type).

Apparently there's a module called Views distinct that would eliminate duplicate entries due to having one field having the same values.


Taxonomy term node count with depth I want to achieve the following term listing:

clothing (17)

dresses (2)
skirts (3)
tops (12)

accessories (5)

bags (1)
jewelery (4)
necklaces (2)
rings (2)

Is this possible with views? I know you can use the "Taxonomy Term: Content with term" relationship, but this only counts the nodes attached to the parent terms and not those attached to the child terms...

Yes, this is possible with only views. Here is a good thread to get you started. http://drupal.org/node/301485#comment-1065230


Upgrading Drupal from 6 to 7 results in double slash being present in image file paths After upgrading from Drupal 6 to Drupal 7 I noticed that my image paths now have a double slash like this:

/files/sites/default//filename.jpg

I was thinking of running a simple find and replace in the database, but I'm sure how to resolve this.

I migrated my website from an old domain to a new one and this issue came up. Apparently, you should define new paths for website media (e.g. images) here:

http://youwebsite.com/?q=admin/config/media/file-system

There are two paths that must be specified. In my case,

Private: sites/youwebsite.com/private

Public: sites/youwebsite.com/files


How do I dump a variable that is too big for dump(var)? I am working with the views-view-unformatted.html.twig file, and I am trying to use the following code.

{{ dump(row.content | keys) }}

The returned value is the following.

/var/www/html/example_site/vendor/twig/twig/lib/Twig/Extension/Debug.php:60:
array (size=5)
  0 => string '#theme' (length=6)
  1 => string '#view' (length=5)
  2 => string '#options' (length=8)
  3 => string '#row' (length=4)
  4 => string '#field_alias' (length=12)

With {{ dump(row.content['#row'] | keys) }} I get the following.

/var/www/html/example_site/vendor/twig/twig/lib/Twig/Extension/Debug.php:60:
array (size=0)
  empty

Based on it being empty, I assume it is not an array and proceed to use {{ dump(row.content['#row']) }}. When I do this I get a 504 Gateway Timeout error. max_execution_time is set to 30.

How do I dump a variable that is too big for dump(var)?

As a workaround, until Kint will be configurable via UI see #2405179, edit modules/devel/kint/kint/config.default.php and set $_kintSettings['maxLevels'] to a lower number (the default is 7).

Try using 4. This will limit the depth of the array that gets dumped.


Reset the cart if same product is added I am using Drupal Commerce in that user can add a product to cart. If user add same product for five times, cart contains same product for five times. What I need is when user adds same product again and again it should reset to 1. I have include the following lines still I am getting the same.

function dt_admin_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {

   $form_state['line_item']->data['context']['add_to_cart_combine'] = TRUE;

   return $form;

}

Here you can find the solution for restricting duplicated items to the cart.

Solution is

Create rule, name it; Event: before adding a product to the cart
You can add there conditions if you wish. I am chcecking here is product is digital or not.
In Actions add Loop through commerce-order:commerce-line-items
Create component, single rule, name it
Create following variables of the component and name them as you wish:

Commerce line item (line item of the order from the loop of the main rule)
Commerce product (product added to the cart)

Add condition to the component: Entity has field, Entity: [line-item-in-order], Field: commerce_product. this will bring us the product from actual line item in current order (shopping cart).
Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart (variable brought from the main rule)
Add action to the component: Remove an item from a list. List: [order:commerce-line-items], Item to remove: [line-item-in-order]. This will completely remove duplicated product from the shopping cart and from the order as well.
Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.
Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.
You are done. Chcek it, it should work


How do you access user profile fields? In D7, using profile2 module, you would load the entity_metadata_wrapper from user object then access profile fields as such: $userWrapper->profile_XXX->field_XXX

Given that Profile2 is replaced by Profile module in Drupal 8, what is the Drupal 8's equivalent of accessing profile module's fields from a user object?

This is late, but other people will come here (just like I did).

I had to go into the profile module source code to find this, but I guess it's obvious when you think about it:

$list = \Drupal::entityTypeManager()
  ->getStorage('profile')
  ->loadByProperties([
    'uid' => $account->id(),
    'type' => 'profile_type',
  ]);

You'll probably want to wrap it up in a service - and if you don't, you should take a long hard look at yourself as to why not :-)


Sending user edit form to user profile I'm trying to send user edit page to the user profile page (/user), so I can get user profile informations and user edit form on the same page.

function hook_preprocess_user_profile(&$vars) {
  global $user;
  $account = user_load($user->uid);
  $vars['form'] = drupal_get_form('user_profile_form', $account);
}

Then in user-profile.tpl.php I have the following :

<?php print drupal_render($form['field_user_address']); ?>
<?php // Print necessary validation fields and remove others
      unset($form['field_user_society_id']);
      unset($form['field_user_locations']);
      unset($form['locale']);
      unset($form['account']);
      print drupal_render($form);
 ?>

It works well, I have my form, the datas are coming into it but when saving it, even if I get status message "Changes have been saved" actually no datas are saved.

I tried to put module_load_include('inc', 'user', 'user.pages');in a hook_init() and in a form_alter, but no way to get the form datas saved.

Thanks for helping.

So, the solution was quite simple.

I just needed to remove the call to $form['field_user_address']

//<?php print drupal_render($form['field_user_address']); ?>
<?php // Print necessary validation fields and remove others
      unset($form['field_user_society_id']);
      unset($form['field_user_locations']);
      unset($form['locale']);
      unset($form['account']);
      print drupal_render($form);
 ?>


How to clear a field using jquery after Ajax form reload I have a custom module with a custom form with two fields: field A (select), field B (datepicker). When the user picks field B, it launches an Ajax call to validate field B. All works well so far, except for one issue: if user decides to change field A after the Ajax call, it should clear field B.

My problem is I can't get jQuery to detect that field A was changed after the Ajax is called. I can see field A's id changes from 'foo' to 'foo--2' and I've tried the below code with both '#foo' and '#foo--2' but neither works. jQuery works only the first time the form displays, but not after ajax fires. IOW the user can change field A's selection but jQuery doesn't detect that change, I can't even get the alert to trigger. Any ideas what I might be doing wrong here?

$('#foo--2').change(function(){
    alert ('change detected');
    'input#bar-datepicker-popup-1'.val('');
});

Try this, it should work. Instead of $(document).on you can also use any outer static element.

$(document).on('change', '#foo--2', function(){
    alert ('change detected');
    'input#bar-datepicker-popup-1'.val('');
});


How to change the link target in a entity reference display? I'm on d7. I have two content types on my site, "link" and "Article". The link content type contains a link field from the link module that users enter a link to another site in to. I have the "link" content type referenced (thanks to the entity reference module) in my "article" content type and I would like for the link, when clicked, to open the referring page (offsite) in a new tab/window. How can I do this?? Any suggestions?
Thanks.

You can configure a link field to open in a new window.

About halfway down the edit page for your link field, you'll see 'Link Target,' and that's where you set it.


How to set Form API link href to # hashtag In Form API when creating a link, the output a-anchor will have a prefix of "en/" in front of whatever I set as the href value and if href is set to "#" it will be output with the language prefix and # is escaped and becomes a code something like "en/%23"

this is the code:

$element['add_address'] = array(
            '#type' => 'link',
            '#title' => t('Add new address'),
            '#href' => '#',
        );

I need that link to not have a href destination value, as it's supposed to react to javascript only. I know I could do a preventDefault() or any of the same resulting bypasses with JS, but I'm curious how to make a empty anchor with the form API.

Thanks,

Alari

Not sure if this will work, give this a try

'#href' => '&num',  OR  '#href' =>'&#x00023', OR '#href' => '&#35',


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.


Creating RSS feeds for individual nodes Is there any way to have rss feeds for individual nodes, taxonomies and so on.Right now we have rss feed for the entire website.

for example :
I'd like to access a node feed through http://www.musite.com/node/1.xml

Yes. Using Views you can add a Feed display, with a path that contains a with a wildcard component (e.g. /rss/%/feed), & Content: Nid for a contextual filter. This will create a path that will have an RSS feed for each nid (e.g. http://www.example.com/rss/1/feed. http://www.example.com/rss/2/feed, etc.).


how to render content type's fields in Custom Module Form I'm new to Drupal 8 and I'm trying to create a form that allow to fetch my content types hierarchy and show its fields using ajax callback, but unfortunately none of the fields shows up eventhough the ajax works fine and callback function correctly fired?
The Fields Types in my ContentType is {body:text_with_summary, price:decimal, title:string}
As I Tried with debugging it seems that my code cannot define those types as form field types

here is my code in MyForm.php File:

public function level3SelectedCallback(array &$form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $fields = MyController::contentTypeFields('MY_VOC');

    foreach ($fields as $field){
        $name = $field->id();
        $label = $field->label();
        $type = $field->getType();
        $desc = $field->getDescription();
        $form['fields_wrapper']['field_'.$label] = array(
            '#type' => $type,
            '#description' => $desc,
            //'#options' => '',
            '#attributes' => array(
                'class' => array(
                    'myField'
                ),
            ),
            );
        $ajax_response->addCommand(new HtmlCommand('#fields-wrapper', $form['fields_wrapper']['field_'.$label]));

    }

    $ajax_response->addCommand(new InvokeCommand('#fields-wrapper', 'change'));
    $form_state->setRebuild(True);

    return $ajax_response;
}

My Controller Function is:

static function contentTypeFieldsAsFields($contentType) {
    // Get the definitions
    $fields = array_filter(
            \Drupal::service('entity.manager')->getFieldDefinitions('node', $contentType), function ($field_definition) {
                return $field_definition instanceof \Drupal\field\Entity\FieldConfig;
            }
    );
    return $fields;
}

To get an empty form of a content type you would use code like this:

$node = \Drupal\node\Entity\Node::create(['type' => 'page']);
$form = \Drupal::service('entity.form_builder')->getForm($node);

To open this form with ajax, put the form in a controller:

public function contenttypeform(NodeTypeInterface $node_type) {
    $node = $this->entityTypeManager()->getStorage('node')->create([
      'type' => $node_type->id(),
    ]);
    return $this->entityFormBuilder()->getForm($node);
  }

Configure a route for this controller and open the form in an ajax modal like this example from ConfigSync.php:

$links['view_diff'] = array(
            '#type' => 'link',
            'title' => $this->t('View differences'),
            'url' => Url::fromRoute($route_name, $route_options),
            'attributes' => array(
              'class' => array('use-ajax'),
              'data-dialog-type' => 'modal',
              'data-dialog-options' => json_encode(array(
                'width' => 700
              )),
            ),
          );


How to unpublish a node and any related nodes? I am currently working on a problem where, when a Physician node has been unpublished, its related Review nodes will be unpublished as well. They do have an entity reference built in to distinguish which Review belongs to which Physician.

I have been working with the Rules, Views Bulk Operations (VBO), and Workflow modules to get this to work.
I have many failed attempts using the Rules module, so I don't have any code to supply.

Would anyone be able to point me in a direction?

Yes this seems perfectly possible with Rules ... In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should use (at least) have a Rules Action to create a loop related to your 'related "Review" nodes' (as in your question). After you do, you should iterate over each item in that list. And for each iteration you should then perform a Rules Action to "unpublish the review being processed in the loop".

Done

PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.

PS 2: I assume this is about D7 ...


Hierarchical Views Catalog using Taxonomy in Drupal 8 I have the following Taxonomy vocabulary named Product Catagories:

Categorie1

Sub categorie1
Sub categorie1

Categorie2

Sub categorie2
Sub categorie2

If the user click on e.g. Categorie1 I want to show the child-terms of Categorie1 in a view.

I followed this tutorial and configured all steps. But in Drupal 8 I cant't find this step:

  Default validation criteria" for "Taxonomy term" and choose "Convert
  taxonomy name to ID

Where is a similar option like Convert taxonomy name to ID in Drupal 8?

Ubercart for Drupal 8 has a catalog example that might be a solution for you

https://ftp.drupal.org/files/projects/ubercart-8.x-4.0-alpha4.tar.gz


removing the 'title' field from custom content types I've created a content type to manage people, but in addition to the 'first name' and 'last name' fields that I've created, there's a 'title' field that seems to be present because its a Node module element.

Is there any way to, say, auto-fill it with something and hide it so that users who add content don't have to worry about it? It seems so redundant to have them fill out 'title' in addition to first name and last name.

You are looking for Exclude Node Title module

  This module handles a very simple functionality, decide whatever to
  exclude a node title from full node page or node teasers. It provides
  a checkbox on node-edit pages for easier exclusion, or you can use the
  admin page to manually enter a list of node id's to exclude title.

Also provides the option to hide all titles of a certain Content type.


How to disable/enable all products in commerce? The Commerce Backoffice module allows to delete all selected products from the list. But how about to change the status for all products or for the selected ones?

It will take just a few steps to create a view for your commerce product
fields values manipulation:

add a new View:

"show group" set to Commerce Product "of type" - type of
     you commerce product, you want to change fields values;
"display format" set to "Table";
press "Continue & Edit";

In "fields"  group add "Bulk operations:Commerce Product" field:

set checked "Modify entity values " in "Bulk operations" group;
press "Apply" button;

That are the main settings for your operation view. Just add fields and filters whatever you want.
Save your view and use it for change field values using bulk operations.


Programmatically creating a new instance of a custom content entity that contains a field collection I am trying to write a script that will create about a thousand instances of a custom content entity type I defined via a module from existing data that I have prepared. Right now I just need to figure out how to create an instance of my entity type programmatically.

This entity type contains multiple field collections. I don't understand how to structure the arguments of {entity_type}::create() to accommodate field collections.

Following the accepted answers to Programmatically create nodes and How to programmatically insert and update Field Collection values?, here is my function code so far (i have it inside hook_entity_view_alter() just for easy testing):

$food = Food::create([
    'type'  => 'food',
    'title' => 'Allspice',
    'field_category' => 'Spices'
]);
$variation = FieldCollectionItem::create([
    'field_ingredients' => 'allspice',
    'field_safe_for' => [
        'field_nut_allergies' => 'Yes',
        'field_seafood_allergies' => 'Yes',
    ]
]);
$variation->setHostEntity($food);
$food->field_variations[] = ['field_collection_item' => $variation];
$food->save();

where food is my entity type, field_variations is the ID of the field collection in food which may have unlimited values per food instance, and field_safe_for is a nested field collection.

No matter what I do, I always get this:

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

Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type field_collection_item in Drupal\Core\Entity\ContentEntityStorageBase->doCreate() (line 83 of core\lib\Drupal\Core\Entity\ContentEntityStorageBase.php).
Drupal\Core\Entity\EntityStorageBase->create(Array) (Line: 509)
Drupal\Core\Entity\Entity::create(Array) (Line: 39)
food_food_view_alter(Array, Object, Object) (Line: 501)
Drupal\Core\Extension\ModuleHandler->alter(Array, Array, Object, Object) (Line: 268)
Drupal\Core\Entity\EntityViewBuilder->buildMultiple(Array) (Line: 203)
Drupal\Core\Entity\EntityViewBuilder->build(Array)
call_user_func(Array, Array) (Line: 381)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 62)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 98)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 77)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 628)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

which I do not understand in the slightest since my custom entity types don't make use of bundles.

How can I fix this?

The bundle of the entity type "field_collection_item" is field_name and the error messages says this is missing:

$variation = FieldCollectionItem::create([
  'field_name' => 'my_field_name',
  ...


Embedded Youtube Block Thumbnail I seem to be having an issue with the auto generated Thumbnail of a you tube video that shows in a block as a teaser on my frontpage.

When viewing the front page using Firefox the thumbnails are shown. But when viewing on IE11 I just get the alternative text description without the thumbnail.

I am using Drupal 7

Try using the /watch?v= parameter (i.e. www.youtube.com/watch?v=Y9eXzmVzDR8) instead of www.youtube.com/embed/Y9eXzmVzDR8 when adding content to the field.


Controlling node's content using field setting In a module I am developing I wish to control display of a link in node's content depending on user's choice. I want to display this option to user(whether he wants to display the link on particular node) when he is on a path like this /node/{node}/edit with other options(menu settings, comment settings) available on that page. On doing some research I managed to find out that usage of field plugins would be required. This I am saying because comment module implements FieldType plugin and displays option of type open, close, hidden comments. But now I am not able to move further because I am not able to understand how will I keep track of option selected by user for different nodes. It would be great if any one can throw some light on this, some code or reference to similar usage by other custom module would be  of great help. Thanks.

You don't need your own field types for this like comment adds.

You can use checkboxes, radios, lists, whatever you want that makes sense for you.

Moving them into the sidebar requires some form alter code in the node forms that moves them into fieldsets. path_form_node_form_alter() is an example that defines a fieldset and moves a field into it.

Then all that's left is custom preprocessing/twig checks.. check the value of those fields and then display whatever you want.


Two forms using one submit button I want to merge 2 forms together (user register form and node registration form). Should I use multiform module to achieve this or create new form using form API?

Option 1:

Think of one form as Node Form with more fields that you can reuse on user entity as well.

Now on node save you have flexible node api to hook in and create user. As an example

hook_node_presave($node)
hook_node_insert($node)
hook_node_update($node)

You can use any of the above, most suitable would be node_insert I think as you would like to create user only when new nodes is created. Inside the hook you will get the user submitted values inside $node object, all you have to do is create user programmatically from it.
Which basically is building a user object and mapping of fields and finally do a user_save() on your user object.

Here is an example of how you can create user programmatically

http://codekarate.com/blog/create-user-account-drupal-7-programmatically

Option 2:

Form does not need to be node form, you can have a custom form as well using form api, in that case you will not need any of the node hooks instead process would be just like user_save() you will do node_save(). So inside your custom form submit handler you will be creating a node(how to create node programmatically) and a user(how to create user programmatically)


How to invoke AJAX on Vertical Tabs? My case is simple: When user switches tabs, I want to dynamically fill empty fields in the tab he entered, calculating them from the tab he went from. Like suggesting city by zip code, or address by company name if I have it in database.

Problem is - I can do it on button click or on field's blur, but I'd prefer it to happen on vertical tab switch. Items with vertical_tabs type simply does not have #ajax property. Is there any neat way around it?

#states seemed a solution, but it seems they only support static value set, like:

':input[name="foo"]' => array('value' => 'bar'),

#states attributes cannot use to invoke AJAX. See drupal_process_states

With your question, i think the solution is write an javascript file and #attached it to the form you need.

You can bind a click event to .vertical-tab-button element (better) or orverride Drupal.verticalTab.prototype.focus function (not recommend).


How to make a contextual filter optional I'm making a contextual filter, to pass along an argument from a panel to a view, using Content: Has taxonomy term ID.

This is so that it pulls in a keyword from a URL.

However, I want it to work so that when no keyword is passed in, it goes based on the last URL parameter.

For example:

www.example.com/tech/startup

It should pull ONLY things with both tech and startup if this is passed.

However, if the URL is just:

www.example.com/tech

Then it should show ALL articles with the tech taxonomy term.

How do I do this?

You can use Exceptions setting in views like below

And point your menu link to www.example.com/tech/all instead of www.example.com/tech


Add extra field on check out page of Drupal 7 All we want is for the customer to have to tell us how they heard about us at checkout page even when they did not make an account.

How do I add this extra field?

We are running Drupal 7 and below are the new modules installed to accomplish this new task:

addressfield-7.x-1.0-beta2.zip
commerce-7.x-1.0.zip
commerce_extra_panes-7.x-1.x-dev.zip
commerce_fieldgroup_panes-7.x-1.0-rc2.zip
field_group-7.x-1.1.zip

I think you can add a new field for your orders in "Store > Configuration > Order Settings > Manage Fields."

Next, using the Commerce FieldGroup Panes module, you can add the new field as a pane in your checkout.


How do I migrate this module? I just migrate my Drupal 6 website to Drupal 7 successfully, using migrate_d2d module. Is there an easy way to migrate Drupal 6 xml sitemap to Drupal 7 too?

Should I just install the XML sitemap module in Drupal 7 and it'll create its own?

Your D7 may not remain unchanged forever.  When it change, you will want its sitemap to change in concert with the site. In other words, you need something like XML Sitemap on your site.

You should therefore install the XML Sitemap module (as you suggest yourself).  The module actually has an upgrade path if you used the D6 version of the module to generate the D6 sitemap.

If your D6 sitemap was generated by some other means, or if you don't care about preserving the D6 settings for the sitemap, just install at as a fresh module on D7, and it will create a new sitemap.


How to use the Profiles2 module for Drupal I would like to use the Profiles2 module for Drupal 7 to create user profiles that are separate from user accounts.

I'm trying to find out what is the url for editing the user profiles created with the Profiles2 module? For example:

    http://www.example.com/url-for-profile-editing-page

And what is the template file I have to modify in order to cutomize this page?

Does anyone know?

The URL is dynamic, per-user and per-profile... for my site, it's something like the following: user/[user-id]/edit/[profile2-machine-name].

This would be different depending on

the user whose profile is being edited
the profile2 profile that is being edited for that user

Alternatively, of course, you might want to just go to your 'my account' page (at /user), click on 'Edit,' and then in the local menu tasks (under the edit tab), you can click on the profile2 profile you'd like to edit.

With regard to a template to change the page, I'm not sure if there is one. You could do a hook_form_alter() in a custom module to change the form values a bit, but you might want to look around the profile2 documentation or module itself to see how these pages are built.


How to add replicate fields when adding content? I've got a drupal structure that I'm trying to set up for hospitality venues so it has information like opening hours, and what is going on at those times. E.g. At Joe's Burgers between 9-5 Monday-Thursday it is a restaurant, but from 9-5 Friday-Saturday it's a nightclub.

I've got fields of venue name, opening hours, and category (e.g. bar, nightclub, restaurant, etc), and therefore am able to add content for one time frame: e.g. Joe's Burgers is a restaurant from 9-5 Monday-Thursday. But I don't know how to set it up so that I can attach further details such as it's a nightclub 9-5 Friday-Saturday.

Is there a button I can add into the 'add content' section which allows me to replicate the opening hours and category fields so that I can have multiple opening hours and category combinations under one venue name?

Thanks guys!

You could use Field Collection to set up a field that contains both a category and a date as one unit.

Then all you would need to do is set the field collection to allow multiple values.


How to redirect a node to an external URL? Is there a way to "alias" a Drupal site node to an external URL?

I'd like that a click on a link in my Drupal site like 'http://mysite/node/64' redirects to an address like 'http://anothersite/whateverurl'.

I use Fullcalendar View module.
I added a Date range field to a custom content of mine (my modified Basic page).
If I set a date in a node of that type, I can see an item linked to it in the Calendar:

If I click on the item, I am redirected to the corresponding node and I see its content.
For some nodes, I'd like the link to point to an external url instead...

[Edit]
I tried something else: I created a new View with no fields at all except the Daterange.
When I use Format: Unformatted list, I get this result:

which is OK as I have only one node of the type filtered.
When I use Format: Full Calendar Display, I get this result:

which is strange as I have no fields in the View description pointing to the node itself...
Does it mean that Fullcalendar View] module generates its magic elsewhere?
I'm a bit confused :-(
Any help?

Since you want this done in a view here is a possible solution

Add a link field to your content type external url which would need to be followed when available otherwise (if empty) it would take to node view (normal behaviour).

Modify the Fullcalendar View and add follow 2 fields

Link to content hidden

external url and adjust the No results behaviour to include {{ view_node }}

Use external url as the link

NOTE: it appears that Fullcallendar view module takes the link to node in a way that it cannot be modified within the view as described above.  There is a feature request that asks for such an option.  In the meantime perhaps the above can be achieved with another calendar module () or modify the URL from within a custom module.


Get default min and max default values in views exposed filter form element I have a views display that lists out content that meets a criteria defined by an exposed form. One of the filters is 2 values which a content attribute must be between. In views, I can define this as a default min and max value.

I would like to get these default values out as data attributes on the form fields for some javascript validation, and therefore will need to be able to get these as twig variables in the form element template, or set these as attributes in the form element preprocess.

The inputs initially have the value of the default min and max, but as soon as these are changed there is no way I can see to access the defaults.

How can I do this?

function MYTHEME_preprocess_input(&$variables) {
  if (isset($variables['element']['#default_value'])){
    $variables['attributes']['data-default-value'] = $variables['element']['#default_value'];
  }
}


How do I create a workflow that creates multiple nodes? I'm recreating my pages in Drupal 8 for a platform upgrade. One thing I've identified for this upgrade is the need for a workflow that creates multiple nodes before it's actually finished. If a user creates node of type A, it automatically creates a second node of Type be and auto-fills an entity reference field with whatever nid Node A was given. I'm HOPING this is something I Can create easily, through a form builder or something like that.

I'm not sure what the best option is for this, but I do need to find a way to simplify this workflow. I think I'll need rules a part of it, but I'm not sure at all one way or the other.

Here is a solution I came up with.  Create a custom module and in your MODULENAME.module file implement hook_form_alter to add a custom submit handler MODULENAME_add_story

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // if creating node of type A (article is machine name)
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_add_story';
  }
}

In the custom submit function create the referenced node and save the reference on the original node

function MODULENAME_add_story($form, $form_state) {

  $article = $form_state->getFormObject()->getEntity();
  $aid = $article->id();
  $uid = $article->getOwnerId();

  // Create node of type B (story is machine name)
  $story = \Drupal\node\Entity\Node::create([
    'type'        => 'story',
    'title'       => 'New auto created story new',
    'uid' => $uid,
    //set other fields
  ]);
  $story->save();

  //set the reference and save
  $article->field_stories[] = ['target_id' => $story->id()];
  $article->save();
}

So when you create node of type article a node of type story is also created and referenced from article.


How can I import non-unicode text file by Feeds module? My drupal version is : 7.5x

I want to import an csv or txt file that have non-unicode (iransystem) encoding.

After import this file to Drupal (persian character with iransystem encoding) my characters show correctly in my site. So these texts are imported successfully. But when I want to filter results of those fields by Views (exposed filter), I can not see any result by filtering views fields (search in fields by views exposed filter).

I want to import non-utf8 or unicode persian text files into Drupal and filter those fields by Views exposed filter (search on non-unicode characters).

For example I imported A Persian or arabian word into a field of Drupal. This passage shows correctly to me, but when I search type this passage in exposed A Persian or arabian word text in Drupal page and paste on search field of Drupal Views, I can see results correctly.

I can only provide high-level guidance here, but you need to use the Feeds Tamper module, which allows you to alter data between when it is read from the source, and then passed to Feeds.

However, I don't think there is an existing tamper plugin that can handle your situation; you will have to create your own.

There are two patches in the issue queue that may provide guidance:

https://www.drupal.org/node/1817516
https://www.drupal.org/node/2263119 (disclosure, I wrote this one)

You can take one of those two patches, and update them to use your character set instead of the ones in the patch.

For example, in this patch, you would need to update

+function feeds_tamper_utf8_encode_callback($result, $item_key, $element_key, &$field, $settings, $source) {
+  $field = drupal_convert_to_utf8($field, 'ISO-8859-1');
+}

to use your encoding name instead of 'ISO-8859-1'.


Finding pages through FTP Our YMCA organization just redesigned a new website as a static site. The old site was in Drupal. The domain and hosting have already been transferred. I have access to the old site through FTP and am trying to find specific pages in order to pick up content. Can anyone tell me where the web pages are in the FTP directory? Thanks!

As @Beebee pointed out, Drupal stores its pages in a Database. That means the actual "pages" aren't going to be available via FTP.

The first thing you need to verify is, do you have a copy of the old Drupal website's database? If not, try reaching out to your old website host to see if they can recover it for you.

If the database isn't available, then your best bet to see the old website would be to use:

https://archive.org/web/

If you do have the old database, here's how you can set up and see the old website:

On your website host, set up a subdomain through cPanel (e.g.
drupal.example-ymca.com)
Place a copy of all the old Drupal files inside this new subdomain directory (e.g. ~/www/drupal - so the index.php file that comes with Drupal lives here: ~/www/drupal/index.php)
Create a new MySQL database, user and password through cPanel (take note of each while doing so)
Import the Drupal database into this empty database
Open the ~/www/drupal/sites/default/settings.php file and input your database credentials in the database config section
Visit your old website, e.g. http://drupal.example-ymca.com/

Here's a Google Search Result set that has additional topics:

https://www.google.com/search?client=ubuntu&channel=fs&q=drupal+transferring+from+host+to+host&ie=utf-8&oe=utf-8

I'd also like to point out, that it is possible to create/edit pages in Drupal by writing custom code (via an FTP if you wish) by using hook_menu(). This is a slightly more advanced topic, but nonetheless, a very important one to understand when working with Drupal. Once your site is up and running, locate any custom modules that implement hook_menu() to see custom pages (if any) that were created this way.


Building a dynamic menu based on taxonomy terms I'm new to Drupal and I am currently using Drupal 7. I need to know if what I am trying to do is even possible. If so I am going to need some pointers on how to implement it.

I have two vocabularies: Category and Brand. I have products that are tagged with a brand and one or more categories. I want a mega menu, dynamically built based on these terms. Basically, if there is a product tagged with category "A" and brand "X", a link should be created in the menu under products. So the menu would look like Products >> A >> X. Is there a way to accomplish this? I was thinking that I could create a custom module that would find all nodes of type product and create a category link for each new category it finds; then create a brand under the proper category.

You are looking for Taxonomy Menu module. Here is an excerpt from its project page:

Transforms your taxonomy vocabularies into menus with ease!
Features

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules

I found these tutorials helpful to get started.
First Tutorial (youtube video).
Second Tutorial (youtube video).


How to load all aliases of a domain I'm using the modules domain and domain_alias on Drupal 8.

I need to load all the aliases of a given domain.

I have tried the following without success:

$aliases = \Drupal::service('entity_type.manager')->getStorage('domain_alias')->loadByHostname('my.domain.com');

$aliases = \Drupal::entityTypeManager()->getStorage('domain_alias')->loadByProperties(['hostname' => 'my.domain.com']);

Got it.

The 'hostname' is not a property of the alias. The way to get the aliases is:

$aliases = \Drupal::entityTypeManager()->getStorage('domain_alias')->loadByProperties(['domain_id' => 'my_domain_id']);

Note that 'my_domain_id' is specific to the domain that you are trying to get the alias for.


I want a Notice message when save configuration I have a module and a form with a checkbox...What i really want is when the user press the button save configuration to take a notice message..Could anyone know how to do this thing?

foreach (watchdog_severity_levels() as $severity) {
    $severity_options[$severity] = check_plain(drupal_ucfirst($severity));
  }

  // Generate checkbox list for given severity levels.
  $form['severity'] = array(
    '#type'        => 'fieldset',
    '#title'       => t('Select the severity.'),
    '#collapsible' => true,
    '#collapsed'   => true,
  );

  $form['severity']['severity_levels'] = array(
    '#type'          => 'checkboxes',
    '#options'       => $severity_options,
    '#default_value' => array_values($severity_levels),
  );

  return system_settings_form($form);
}

Above mentioned is correct bit more Explanation on that

Syntax : drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE);

Example usage:

drupal_set_message(t('your message to the user.'), 'error');

Parameters

string $message: (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.

string $type: (optional) The message's type. Defaults to 'status'. These values are supported:

**'status'
'warning'
'error'**

bool $repeat: (optional) If this is FALSE and the message is already set, then the message won't be repeated. Defaults to TRUE.
Return value

array|null A multidimensional array with keys corresponding to the set message types. The indexed array values of each contain the set messages for that type. Or, if there are no messages set, the function returns NULL.


How to limit country list for address form drop-down? In my store I defined list of supported billing and shipping countries at store settings. This list is respected during checkout process - limited list of countries is shown when customer is entering the address. But when user is on "Address book" tab of user profile page and wants to add new address list is not limited, but all countries are allowed there.
How can I limit list of displayed countries when editing address at address book user profile tab?
I tried using hook_form_alter() but I don't see country drop-down there?
Also tried hook_preprocess_input() and I see other fields, but not country drop-down.
theme_preprocess_field() didn't help either.
And of course, I didn't find that option in back-end.

Found solution here:
https://docs.drupalcommerce.org/commerce2/developer-guide/customers/addresses/countries-and-subdivisions
Created new module "country_limit" added event subsriber like explained there:
<?php

namespace Drupal\country_limit;

use Drupal\address\Event\AddressEvents;
use Drupal\address\Event\AvailableCountriesEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LimitCountriesEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events[AddressEvents::AVAILABLE_COUNTRIES][] = ['onAvailableCountries'];
    return $events;
  }

  public function onAvailableCountries(AvailableCountriesEvent $event) {
    $countries = ['AT' => 'AT', 'DE' => 'DE', 'CH' => 'CH'];
    $event->setAvailableCountries($countries);
  }

}

and registered it like:
services:
  # Name of this service.
  my_config_events_subscriber:
    # Event subscriber class that will listen for the events.
    class: '\Drupal\country_limit\LimitCountriesEventSubscriber'
    # Tagged as an event_subscriber to register this subscriber with the event_dispatch service.
    tags:
      - { name: 'event_subscriber' }

Event subsriber class is directly inside "src" dir, since I don't have other functionalities in this module.


How to create a RSS feed of certain content type ( without affecting the front end layout )? I would like to create a RSS feed of certain content type ( without affecting the front end layout ), but I am not quite sure how can I add this feature to Drupal. Any clues for me to start with?

p.s. I'm using Drupal 7.

Views will allow you to do it.  But when you make changes to the view you must select "over ride for this view" or it will change all views associated with the RSS feed.


Trouble associating EVA with profile Using profile2, I created a profile, and it works fine.  I want to list content authored by that user on that profile page.  So, I created an EVA view, and I can't seem to figure out the right contextual ID configuration.  I tried a few several combinations to no avail.  What may I be missing?

The overall purpose is to display a profile page for users, along with a listing of their content they authored, using Display Suite (yes, the EVA field is visible).  I figured this would be the most simple way to build a profile page.

Synchronicity! I just answered this question which I think is essentially the same question. I don't have any experience with Profile2, but I think this advice is applicable. Hope this helps:

How to create an entity reference view that contextually filters based upon current user ID


Alter form button title I use this to alter field labels:

function ninesixty_form_user_login_alter(&$form, &$form_state) {
    $form['name']['#title'] = t('Name');
}

But how do I change the title of the button? The button is <button> not <input> and it's for node creation form. Form id is titles-node-form.

Use this

In place of name put button name.

$form['name']['#value'] = t('Name');

Hope this will work


How do I programmatically change the body text format on the page content type to full HTML? I have a custom install profile and I must programmatically change the body text format on the page content type to full HTML. However, I didn't manage to find how to do it.

How can I do it?

You can do it with hook_element_info_alter, here is a snippet.

<?php
/**
 * Implements hook_element_info_alter().
 *
 * Sets the text format processor to a custom callback function.
 * This code is taken from the Better Formats module.
 */
function MODULENAME_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'MODULENAME_filter_process_format';
      }
    }
  }
}

/**
 * Callback for MODULENAME_element_info_alter().
 */
function MODULENAME_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change the default text format of the 'field_company_spotlight' field to
  // 'Media HTML'.
  if ($element['#bundle'] == 'company' && $element['#field_name'] == 'field_company_spotlight') {
    $element['format']['format']['#default_value'] = 'media_html';
  }
  return $element;
}
?>

As THIS post suggests you could try

$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

in your hook_form_alter or in hook_FORM_ID_alter

Also there is Better Formats module

  Better formats is a module to add more flexibility to Drupal's core
  input format system.


How to overridden command via hook_drush_command_alter? I'd like to override command using hook_drush_command_alter before run as below:

/**
 * Implementation of hook_drush_command_alter().
 */
function policy_drush_command_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['command'] = 'custom-features-revert-all';
    $command['command-hook'] = 'custom-features-revert-all';
  }
}

However it doesn't work (it's calling the old command). I'm doing it right? Is it possible using this hook?

The command_alter hook is not super friendly / obvious when it comes to complete command replacement, as this hook was only designed to make minor alterations to the command.  It is all the same possible to replace one command with another, but the process is a bit obtuse, as you need to reset some variables that Drush has already initialized.

This should do the trick:

/**
 * Implements hook_drush_command_alter
 */
function policy_drush_command_alter(&$command) {
  if (($command['command'] == 'features-revert-all') && (drush_drupal_major_version() >= 8)) {
    $command['command'] = 'custom-features-revert-all';
    $command['command-hook'] = 'custom-features-revert-all';
    $command['primary function'] = FALSE;
    $command['arguments'] = array(); // Adjust this only as needed
    drush_set_command($command);
  }
}

Note that this example removes any arguments the user may have passed to the command; I included this just to demonstrate how to alter the arguments, in case this is needed. Remove the assignment to $command['arguments'] if you'd like the original args passed through.


Composer downgrading module version I wish to move the bootstrap theme from the repository
located in the folder theme/custom to be a dependency in composer.json
I've checked that the current version drupal/bootstrap is 3.16
I perform rm -rf web/theme/custom/bootstrap
composer require drupal/bootstrap:8.x-3.16
^^-> wrong syntax and have decided to just composer require drupal/bootstrap
Now I need to downgrade the version of drupal/bootstrap in composer.json
and perform composer update --lock
But I got an error:
Nothing to modify in lock file
Unable to find a compatible set of packages based on your non-dev requirements alone.
Your requirements can be resolved successfully when require-dev packages are present.
You may need to move packages from require-dev or some of their dependencies to require.

  Problem 1
    - Root composer.json requires drupal/bootstrap 3.16, found drupal/bootstrap[3.23.0] but it does not match the constraint.

Any hints would appreciate.

What that I have done to fix it is obvious from the question
remove drupal/bootstrap from composer.lock and from composer.json
composer require drupal/bootstrap:3.16


Clean URL's not respected on local I have set up my Apache 2.4 on this new Yosemite machine to use vhosts but the clean urls are yielding 404s. The .htaccess works on the 1and1 server and I'm using it in this folder. Reading other SO posts say to enable mod-rewrite and AllowOverride All which I believe I have done. Here is my vhost configuration

This is my working .htaccess that production uses:
For more clarity this is the output of apachectl -M

Loaded Modules:
 core_module (static)
 so_module (static)
 http_module (static)
 mpm_prefork_module (static)
 authn_file_module (shared)
 authn_core_module (shared)
 authz_host_module (shared)
 authz_groupfile_module (shared)
 authz_user_module (shared)
 authz_core_module (shared)
 access_compat_module (shared)
 auth_basic_module (shared)
 reqtimeout_module (shared)
 filter_module (shared)
 mime_module (shared)
 log_config_module (shared)
 env_module (shared)
 headers_module (shared)
 setenvif_module (shared)
 version_module (shared)
 proxy_module (shared)
 proxy_connect_module (shared)
 proxy_ftp_module (shared)
 proxy_http_module (shared)
 proxy_fcgi_module (shared)
 proxy_scgi_module (shared)
 proxy_wstunnel_module (shared)
 proxy_ajp_module (shared)
 proxy_balancer_module (shared)
 proxy_express_module (shared)
 slotmem_shm_module (shared)
 lbmethod_byrequests_module (shared)
 lbmethod_bytraffic_module (shared)
 lbmethod_bybusyness_module (shared)
 unixd_module (shared)
 status_module (shared)
 autoindex_module (shared)
 vhost_alias_module (shared)
 negotiation_module (shared)
 dir_module (shared)
 alias_module (shared)
 rewrite_module (shared)
 php5_module (shared)

I have moved the application folder into OS X webserver and commented out the vhost include statement to ensure that if there is an issue with my vhost it should show up. However, there is a 404 response when drilling down to /user.

What am I overlooking? thx, sam

It may be that your Apache vhost and/or .htaccess need updating.

Yosemite uses Apache 2.4, which replaces some access control statements used in 2.2 and prior.

'Allow from all' becomes 'Require all granted'

'Deny from all' becomes 'Require all denied'

See htaccess protections do not work on Apache 2.4 without mod_access_compat for the ongoing Drupal 7 core discussion. Upgrading to 2.4 from 2.2 gives some guidance on upgrading configurations.


How can nested subdirectories and symbolic links be used without conflict with a multi-site Drupal installation? My question is basically a reflection of the question found here (which unfortunately does not have a clear answer): http://groups.drupal.org/node/20604

Please note that this is not a question about multi-site setup, but it is rather a question about a complicated edge-case; please read through before jumping to suggestions. Also, take a look at the link above if you need more info.

Note also multi-site works generally fine, just not this case.

Some truths:

I am using symbolic links (on RHEL5 to be exact)
I am using Drupal 6.20
I am using Apache
I am using subdirectories (NOT subdomains, switching to subdomains is not an acceptable answer)
My Drupal site directories are nested two levels deep (e.g. /campus/bus, /campus/news)
The Drupal sites all use the same code base in the /campus directory
The Drupal sites all use different (their own) databases

In my case, there are dozens of sites, but the first conflict I noticed was as follows. There are two sites at urls such as the below structure:

drupal.drupalsite.com/campus/bus

drupal.drupalsite.com/campus/news

In the sites/[foldername] the respective folders are:

drupal.drupalsite.com.campus.bus

drupal.drupalsite.com.campus.news

The campus folder in the web root contains the Drupal install, and also the symbolic links, so in /var/www/campus there are e.g., news -> ./, bus -> ./.

On the 'bus' subsite, attempting to go to https://drupalsite.com/campus/bus/news makes Drupal confused. It seems to drop everything in the request after the last directory. e.g., drupalsite.com/campus/bus/news will instead resolve to drupalsite.com/campus/bus and drupalsite.com/campus/bus/news/headlines will return a 404 not found.

For another data point, I put a var_dump on $dir in the conf_path() function to see how many directories were being looked at for each request. For a non-conflicting URL, such as bus/undergraduate-programs I got the following:

drupal.drupalsite.com.campus.bus

However for a conflicting URL such as bus/news/headlines I get

drupal.drupalsite.com.campus.bus.news
drupalsite.com.campus.bus.news
com.campus.bus.news
drupal.drupalsite.com.campus.bus

There is a patch which could allow the multi-site setup to be done via sites.php instead of via the method of using symbolic links, however it would involve hacking core, and thus I am not willing to entertain it, though for reference it is here: http://drupal.org/node/231298#comment-3769752

To note, I also tried most of the suggestions in the original groups.drupal.org. thread as well as numerous hacks in .htaccess and my httpd.conf file, all to no avail.  Please comment if you need further information to answer the question.

Are you using just one rewrite? I have this exact setup, and I take care of it with a separate rewrite for each sub-directory. If you just use the default index.php rewrite, the path gets rewritten back to the default, like drupal.drupalsite.com/index.php?q=/campus/news which is where the 404 comes from. I also use aliases in the server level config instead of symbolic links. It makes things cleaner. (Alias /campus/bus /var/www/html/whatever)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /campus/bus/
RewriteRule ^(.)$ /campus/bus/?q=$1  [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /campus/news/
RewriteRule ^(.)$ /campus/news/?q=$1  [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /
RewriteRule ^(.*)$ ?q=$1  [L,QSA]


Determine available Entities entity_metadata_wrapper value() methods I'm struggling to determine which entity_metadata_wrapper methods are available for a given field.  For instance:

<?php
  $fields = entity_metadata_wrapper('node', $nid);
  $body = $fields->body->value->value();
  $title = $fields->title->value();
  $type = $fields->type->value();
?>

$body has a different method, where you have to do a ->value->value() for it to work right.

In my situation I'm trying to get the type of the node in Human readable form: "Custom Type" vs. "custom_type".  I'm wondering if there is some kind of value() method that returns the human readable version.  print_r($fields) avails me not.

Edit: To get the Human readable node type I ended up just using node_type_load.  It seems like there should be a more efficient way of doing this using the Entity API, but I can't figure it out.

i think the wrapper doesnt provide the type label, at least i havent found it.
One way to find the label :

$info = entity_get_info($fields->type());
echo $info['label'];

To learn more about available fields, try $fields->getPropertyInfo().

The diference of the body field is in the fact it is formatted, so the "first" value() function returns the object which allows you to retreive other metadata about the field. The difference can be spotted in the result of the aforementioned getPropertyInfo. While a "plain text" field is set to a callback function "entity_metadata_field_property_get", which returns the value immiediately, the body will have something like "entity_metadata_field_verbatim_get" which returns the whole array of the field.

according to the docs, you can also use value() on the wrapper itself and that will allow you to see what there is (so print_r($fields->value()); or dpm() the same will help :)


How to use security review module I have installed the security review module and enabled it but where to see the security flaws? There is not next page that I am being redirected to, tried google but not much help.

IF it is Drupal 7

Navigate to Administer >> Reports >> Security Review to run the checklist.


how to drupal_set_title for add node form D7 (form alter doesnt work) drupal_set_title doesn't work in my case. well... it worked some time ago (i don't remember when it stopped working) but after installing couple (4-6) of modules it stopped working. where else i can override page-title? it really bugs when you see 'Create Add new order' instead of 'Order form'... so i can live with that but it BUGS me every time i go to that page....

function driver_mailer_form_alter(&$form, &$form_state, $form_id) {
global $user;
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'order') {
drupal_set_title(t('Order form'));
}

one more thing, if i do code like this

function driver_mailer_form_alter(&$form, &$form_state, $form_id) {
global $user;
drupal_set_title(t('Order form'));
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'order') {
}

it works but it changes page-titles to all my pages  (((

and if its possible i really don't want work with .tpl files (i don't know how to yet), but if thats the only way in my case please provide sort of short tutorial.

THANKS to everyone for help!!!!!

I did try to weight my module... made a file 'driver_mailer.install' and used this code:

<?php
/**
* Implements hook_install().
*/
function driver_mailer_install() {
db_update('system')
->fields(array('weight' => 100))
->condition('name', 'driver_mailer')
->execute();
}
?>

then i turned off my module, flush my caches, and turned my module back...
nothing changed... not working.))))

finally...

in general code below works great...

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'yourcontenttype') {
drupal_set_title(t('my title'));
}
}

BUT sometimes other modules do altering the form and title AFTER your module... that was my case :(
it took me couple days to find the solution...
solution:

function yourmodulename_preprocess_page(&$variables) {
if (!empty($variables['page']['content']['system_main']['#form_id']) && $variables['page']['content']['system_main']['#form_id'] == 'yourcontenttype_node_form'){
drupal_set_title(t('my title'));
}
}

to find out your form's id use this in form_alter

drupal_set_message(print_r($form_id, true));

I hope someone will find it useful...


Where are list_text conversions stored? I have a field in a content type that is a list_text with a key/value pair where the key is stored in the database and the value is the text visible in the drop down menu.

I imported a large amount of data.  When I look at the data in a view or view a node, the key shows up.  However, after I edit the node, whether I've made changes or not, the value starts appearing in the view and in the node.  I would like this to be the case for every node, but can't possibly go though and manually edit each node.

Can anyone tell me where in the database the info that tells Drupal to use the translate the key to its value is stored?

The Field CRUD API could be a better approach instead of handmade DB calls.

If you must: Field creats two DB tables for every field they are called field_data_field_fieldname and field_revision_fieldname. The contents depends on the field type.


How to override logic of specific drush command? I'm aware of validate/pre/post COMMAND hooks and I would like to replace the logic of the existing drush command on specific condition using policy commandfile with something else, e.g.

/**
 * Implementation of drush_hook_COMMAND_validate().
 *
 * Validate feature revert of specific module.
 */
function drush_policy_features_revert_validate() {
  if (strpos($args[1], 'rules') !== FALSE) {
    drush_invoke_process('@self', 'rules-revert-all');
    drush_print('Rules reverted in custom way!');
    return drush_set_error('POLICY_DENY', dt('Rules features already reverted.'));
  }
}

However the problem is when I return TRUE - the command which I want to override is called after than, on the other hand when I'm returning FALSE, the drush will fail with non-zero exit code which could cause some other issues (like breaking the deployment).

Is there any better way of overriding the logic of existing drush command without described side-effects? Secondly validation hook doesn't sound right to implement that kind of logic.

Actually returning just FALSE without drush_set_error should work fine without error and the original command isn't executed, e.g.

/**
 * Validate feature revert of specific module.
 *
 * Implementation of drush_hook_COMMAND_validate().
 *
 */
function drush_policy_features_revert_validate() {
  $args = drush_get_arguments();
  if (strpos($args[1], 'rules') !== FALSE) {
    drush_log(dt('Reverting rules...'), 'ok');
    drush_invoke_process('@self', 'rules-revert-all');
    drush_log(dt('Reverting of rules finished.'), 'ok');
    // drush_postflight(); // Set context as completed, but this is not needed.
    return FALSE;
  }
}


How to display all the terms of a vocabulary with a list of the items associated to the term below in a view? In a view in D8, I want to achive something like :

term 1
-item 1
-item2
term 2
-item 3
-item 4
term 3
- item 5
- item 6

Is it possible ? If yes, how ?

It sounds like you are looking for a glossary view.  There are many tutorials on how to do this, ex: https://www.ostraining.com/blog/drupal/glossary/

... after rereading, you may actually be looking to create a view of all terms in that is grouped by parent id. There are different ways to do this. Take a look at:

Grouping Taxonomy terms by their parents
https://www.konordo.com/blog/show-taxonomy-terms-grouped-taxonomy-parent

These talk about D7, but the same should work in D8


D7: Import localized menu programatically I'm constructing a site that has 6 localized versions (English, German, Russian etc.). So the site is supposed to have a localized navigation menu with a common structure across the languages.

I've decided that importing menu items though several Drupal API calls would be the quickest way to create the menu structure I need. So I've learned how to save menu links with menu_link_save() function and they even get their language field set correctly... but those imported items in different languages mix with each other and get displayed all togeher :-(

When I open and save some imported menu item through Drupal administrative interface it starts behaving properly and gets displayed only when the site is in it's language. Also the 'options' database field for this item becomes populated with some additional data compared to other imported items.

So my question is: what i18n API or some other function should i call to save menu items with all needed options? Maybe there is a better way to painlessly import menus?

Thanks in advance!

You dont need to play directly with i18n. All you need is the correct configuration.
It also has a difference between translated and localized items. Translated items may point to different pages and may have different description (besides other customization). Localized item is the same item with just a different title on the menu for each language.

I think you want a translated item. Here is the recipe with some comments:

 <?php
 $menu_item = array(
    'link_title' => 'The menu link title',
    'menu_name'  => 'machine-name-of-the-menu', // It uses '-', not '_'
    'customized' => 1, // Must be 1 in order to not dispaly the link in any language
    'link_path'  => 'node/' . $node->nid, // menu_link_save() does not like aliases. Then 'nid' is used
    'language'  => 'en', // language is required in order to make the item translatable
  );
  $mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
  $ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it
  print_r($ml); // Use print_r() only if you are testing on the block "Execute PHP"

I had a hard time to figure out the need of 'customized' and also the path alias issue.


How do I get a user profile's picture from entity_metadata_wrapper()? I am using entity_metadata_wrapper() for getting values from the user profile.

This is my code:

$user_wrapper = entity_metadata_wrapper('user', $uid);
$user_name = $user_wrapper->name->value();

How do I get the user picture field from $user_wrapper?

You can get the information about user picture indirectly as follows:

$user_picture = $user_wrapper->value()->picture;

I said indirectly, since the picture object itself is not an entity wrapper anymore, so you cannot chain it further using entity_metadata_wrapper functions. However, it should have all the information you need about the user picture, like the fid, filename, uri, filemime, filesize, metadata, and any other fields that could be attached to a file, for instance using File Entity module.


Help with subdomains My hosting provider has problems. I put Drupal on a sub-domain of my site. When I try logging in or clicking a link it comes to a Internal server error. But if I navigate to the actual directory it works fine. What should I do?

Examples:

Works: sld.tld/subdomainroot/Y

Fails subdomain.sld.tld/Y

If sld.tld/subdomainroot/Y works, that suggests that you have set $base_url in your settings.php to include subdomainroot.  If that's the case, subdomain.sld.tld/Y certainly won't work because drupal will be using the above.  Now, if this is the case, and you change the above to subdomain.sld.tld, you still may have issues with cookies being set to the old domain until they are cleared.


Implement hook_block_configure on theme Is it possible to implement a hook_block_configure inside a theme? I would like to have a configuration that is related to my theme in each block but don't want to implement this in a module because I'd generate a dependency from the theme to the module.

Unfortunately no, I must use a module for that, only because of module_invoke use to call the hook.

Also, I was thinking that you could just add your functions on template.php, but this file is only included in the theme function, that doesn't allow you add some stuff, expect throw theme override.


custom wrapper to a form api field In form api, #prefix and suffix are not working for '#type' => 'managed_file'. Below is my code, is there any other way to wrap this?

    $form['cvFile'] = array(
    //'#title' => t('Upload your CV'),

    '#type' => 'managed_file',
    //'#description' => t('The uploaded file will be processed.'),
    '#default_value' => variable_get('cvFile', ''),

    '#upload_validators' => array(
        'file_validate_extensions' => array('pdf doc docx'),
    '#prefix' => '',
    '#suffix' => ''
    ),

    '#upload_location' => 'public://cv/',
    '#process' => array('gng_job_my_cv_element_process'),

    );

The way you are using #prefix and #suffix is wrong. It should not be a part of #upload_validators array.

    $form['cvFile'] = array(
    //'#title' => t('Upload your CV'),

    '#type' => 'managed_file',
    //'#description' => t('The uploaded file will be processed.'),
    '#default_value' => variable_get('cvFile', ''),

    '#upload_validators' => array(
        'file_validate_extensions' => array('pdf doc docx'),
    ),

    '#prefix' => '',
    '#suffix' => '',
    '#upload_location' => 'public://cv/',
    '#process' => array('gng_job_my_cv_element_process'),

    );

Check the form API for this : https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#prefix
https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#suffix