Drupal Commerce: discount for line items based on user's values? I need to have different discount rates for every customer.

I added a textfield in the user profile, where I store a Json object with all the discounts (there is a little GUI to manipulate it), so, for example, I can have this situation:

{
    'product_B': 20,
    'product_A': 15,
    'product_C': 0
}

This means that this customer will have a fixed discount for all commerce_products of type A, 15 on type B and 0 on type C.

I got stuck in the Rules configuration: I created a rule for the Subtract an amount from the unit price event; In the condition, i just check that the user and the line item match few pre-requisites, and it works, but I cant get the line_item details in the action:

// My action
global $user;
$ul = user_load($user->uid);
if(isset($ul->field_discounts))
{
  $user_discounts = field_get_items('user', $ul, 'field_discounts');
  /*
   * Here i have to get few info of the current commerce_product/commerce_line_item
   * in order to calculate the correct $item_discount
   * */
  $discount = ((int)$item_discount * $value) / 100;
  return $discount;
}
return 0;

So the question is: inside that PHP block, how to get the current line item?

I don't think the line item will be exposed to the PHP block, and I doubt there'll be anything in scope to get a reference back to it.

You might need to create your own Rules action. It's pretty simple, and you can copy most of what you need from commerce_line_item_unit_price_subtract(), which does have access to the line item entity.

hook_rules_action_info() would be a good place to start.


Custom save message for site information form Folks,
I need to alter the site information form. I used api_form_system_site_information_settings_alter hook to do so. After submitting I need to print a custom message. I used one submission handler, but the data not saved. My .module file is given below.

use Drupal\Core\Form\FormStateInterface;

function api_key_form_system_site_information_settings_alter(&$form,
 FormStateInterface $form_state, $form_id) {
 if($form_id != 'system_site_information_settings') {
    return;
}
$site_api = \Drupal::config('api_key.settings')->get('siteapikey');

$form['api_settings'] = array(
    '#type' => 'details',
    '#title' =>t('Site API settings'),
    '#open' => true
);

$form['api_settings']['siteapikey'] = [
    '#type' => 'textfield',
    '#title' => t('API Key'),
    '#default_value' => $site_api,
    '#description' => t('Enter the API key for making the site
        protected on API calls'),
    '#maxlength' => 32,
    '#required' => true,
    '#placeholder'=> t('No API key yet')
];

$value = !empty($site_api)? t('Update Configuration'): t('Save Configuration');
$form['api_settings']['actions']['#type'] = 'actions';
$form['api_settings']['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => $value,
    '#button_type' => 'primary',
];
$form['actions']['submit']['#submit'][] = 'api_key_form_submit';
return $form;
 }

function api_key_form_submit(array $form, FormStateInterface $form_state) {

$site_api = \Drupal::config('api_key.settings')->get('siteapikey');
//Reads the new value form the form instance.
$new_value = $form_state->getValue('siteapikey');
//Changes the success message based on the condtions.
if(!empty($site_api)) {
        //Sets update message.
    $message = t('Site API key is changed from @old_value to
        @new_value', [
            '@old_value'=> $site_api,
            '@new_value'=> $new_value
        ]);
} else {
        //Sets success message.
    $message = t('@new_value is set as site API key.',
        ['@new_value'=>$new_value]);
}

//Prints the message.
drupal_set_message($message,$type='status', $repeat=true);
}

It seems you have success with displaying the message but not with saving the value? For this you need to load the editable version of the config, set the value and save:

function api_key_form_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('api_key.settings');
  $config->set('siteapikey', $form_state->getValue('siteapikey'));
  $config->save();
}

By the way it's also a good idea to get the value from the editable version because the config might be overridden and you want to fill the form with the original value:

$site_api = \Drupal::service('config.factory')->getEditable('api_key.settings')->get('siteapikey');


Webform submissions to be seen on Drupalgap I am making a DrupalGap application to view Webform submission.

I have made a view in Drupal as a table to list the submissions, now I want to see that table in DrupalGap.

How do I do that?

Use a DrupalGap Views Render Array. With it you will:

Create the Views JSON page display in Views with contextual filter(s)
Create a page in the app to display the view
Use the Views Render Array to send up the contextual filter(s)
Build the render function to render each row of the table


Installing and Running Drupal in Subfolder - Beginner I am trying to do a redesign on a drupal site. I added a subfolder via an ftp client (example.com/devsite) and manually uploaded the extracted drupal7 files. One would think that going to example.com/devsite or example.com/devsite/install.php would be the next step in accessing the subfolder files, but im only getting 404/page not found error messages when i navigate to this URL.

I'm new to drupal and feel like this should be an easy fix...but dang is it frustrating. HELP!

I have read "How to get Drupal 7 installed in a sub-folder / sub-directory properly?" already - i'm having a difficult time deciphering what steps to take from this post. I need the original site example.com to be live, but example.com/devsite to be viewable as well.

I have read "How to get Drupal 7 installed in a sub-folder / sub-directory properly?" already - i'm having a difficult time deciphering what steps to take from this post.

Your problem is not a Drupal problem. It is a file permissions problem. It is probably caused by you using ftp to create the sub-direactory to hold Drupal.

  but im only getting 404/page not found error messages when i navigate to this URL.

This means that the the directory you've created with ftp, and/or the files you've uploaded in that directory is not readable by the webserver user.

If you have access to the command line interface (CLI), you may need to use chown to make sure the Drupal directory and files are owned by the webserver user, or at least use chmod to make sure they're readable by the webserver user.

However, since you use ftp, I assume that you have not CLI access to your installation? In that case, you need to contact customer support at your hosting provider to learn what tools exist to change the read permissions of files and directories to be readable by the webserver user.

  this post lost me at " I already modified the .htaccess in the parent drupal installation to ignore the sub-folder and i also set the $base_url in the sub-directory drupal installation."

That is just noise in the question.  You need to read the upvoted answer to that question for the solution.

In fact, you should ignore all the stuff about modifying .htaccess in the duplicate issue.  I am no idea why the person who wrote it believes this is relevant. Each Drupal installation has its own .htaccess in its own directory, and the one that comes with Drupal is fine provided you do a clean install. The simple fact is that there is nothing special about installing Drupal in a subfolder.  You need to get the directory and file permissions correct tho' - and using ftp to set things up may have caused the permissions to be wrong.


Embed view block with JSON data output How can I embed the output of a view in another page, as a JSON Data Document, without stopping the page processing ?

I have a view with format set to JSON data document and am attempting to embed the block output in a node with views_embed_view('nec_map_data','block').

This embeds the block but with Views API mode unchecked page processing is stopped at the JSON and the page doesn't render.

If I enable Views API Mode then the block output is wrapped in a div.

I would like the JSON output from the view to be assigned to a javascript variable in the node. How can I achieve this ?

You can do that by adding this function ( a customized version of the original views_json_get in the view_datasource module ) in your template or custom module

/**
 * Gets JSON data from a View rendered in the JSON data document style.
 *
 * This is useful for when working with a JSON view in code.
 *
 * @param $name
 *   The name of the view.
 * @param $display_id
 *   The display of the view to use.
 * @param $args
 *   The arguments to pass to the view.
 * @param $raw
 *   If TRUE, the JSON data is returned as a string.  Otherwise, an object
 *   representation is returned.
 * @return
 *   The JSON data in the form of an object or a string or NULL otherwise.
 */
function views_json_noheader_get($name, $display_id = 'default', $args = array(), $raw = FALSE) {
  $view = views_get_view($name);
  if (!is_object($view)) {
    return NULL;
  }

   $view->display[$display_id]->display_options['style_options']['using_views_api_mode'] = 1;

  $preview = $view->preview($display_id, $args);
  $start_pos = strpos($preview, '{');
  $finish_pos = strrpos($preview, '}');
  $length = $finish_pos - $start_pos + 1;
  $json = trim(substr($preview, $start_pos, $length));

  if ($raw) {
    return $json;
  }

  return json_decode($json);
}

and  get the result of your view  by typing in your function:

$json = views_json_noheader_get('yourviewname', 'yourview json display id', null, true);


Reducing number of results in pager As the image shows, the "Last >>" page button is not well adjusted, so i want to remove one item from this pager but can't figure out where can i find it to edit. I don't think it's configurable in apachsolr? Can anybody help me with this?

This can be done by using theme_pager in TEMPLATE.PHP (add it to your theme folder) . the code will be :

function theme_pager($variables) {
  if(arg(0) == "search" && arg(1) == "site") {
    $variables['quantity'] = 8;
  }
}


Alphabetical sorting of terms (not using a view) I'm using the templates to display my terms rather than views but I'd like to change the order that the items are sorted. Currently it appears to be sorted by date. I would like to sort them alphabetically. Is this something I can do in the temeplate.php or within anywhere else?

The easiest way indeed is using views.

If you really don't like to do so, you could create a custom module, implement hook_menu_alter() to alter the page callback of the taxonomy page:

/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] => 'MYMODULE_my_taxonomy_page';
  }
}

Then write your own version of the taxonomy module's function taxonomy_term_page($term) (using the above example, you would call it MYMODULE_my_taxonomy_page).

Within this function you can alter the call of taxonomy_select_nodes and add a fourth parameter, specifying the desired sort order:

$order = array('t.title' => 'ASC')

Note that this is working only, if you did not use a field replacement for the title property (e.g. using the title module). Then you would have to write an own version of the taxonomy_select_nodes function as well.


Programmatically created node gets created three times, produces error I'm creating one of my first Drupal modules which should create a node (type= page) when you activate the module, and then add some javascript to site.

But when I activate the module, it creates three nodes with the desired node-title, and drupal produces an error:

Notice: Undefined index: module i FieldInfo->prepareInstanceWidget() (linje 591 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).
Notice: Undefined index: module i FieldInfo->prepareInstanceDisplay() (linje 626 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).
Notice: Undefined index: module i FieldInfo->prepareInstanceDisplay() (linje 626 af /var/www/SITENAME/public_html/modules/field/field.info.class.inc).

I am creating the node in the .module file like this:

$node = new stdClass();
$node->type = "page";
$node->title = "Page title";
$node->language = LANGUAGE_NONE;
$node->path = array('alias' => 'some-path');
node_object_prepare($node);
$node->uid = 1;
// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = '';
$node->body[$node->language][0]['format'] = 'full_html';
$node = node_submit($node);
node_save($node);

The above code is based on this article

If i were to use the above path for the node, i would get three pages created with the following paths (i have pathauto installed):

/some-path
/some-path
/page-title.html

All of the pages have the "Page title" title set, and if i edit them they all have the 'This is a body text' body content.

Any help would be appreciated.

Have you installed the drupal for a specific language. If yes than please take care of the language on the time of node creation. e.g. for engisg code is en.

Also please make sure that the function you are calling is attached to only 1 menu. It should not be called by several other source on that module. So, please check HOOK_install, HOOK_menu, HOOK_init wherever you add code for the same.


Access image alt attribute in field template I have copied the field.html.twig Template to field--node--field-image--article.html.twig, to specialize the template for my needs.
In this case the template would be called for content type article and field type image. (This content type uses the Responsive Image module.)
As default, with the image field, you must define an alt-value for the image.
But the alt-value is processed in the template image.html.twig.
Is it possible, to access the alt-value in the field--node--field-image--article.html.twig (the copy of field.html.twig), which calls the image.html.twig via the responsive-image templates.
I want to display the alt text in a div near the image.
I also have tried to access it in hook_preprocess_field(), but all I have for now is the following code.
function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_image') {
    foreach ($variables['element']['#items'] as $item_key => $item) {
      // code to write
    }
  }
}

With twig a preprocess function won't be necessary to get at this data (yay). Unfortunately we still have some weird "drupalisms" to deal with due to the render API. At any rate, here's how you get to it:

{{ item.content['#item'].alt }}

And here's the issue on d.o accounting for the drupalism (linked directly to comment with the above solution and explanation): https://www.drupal.org/node/2160611#comment-9358305


Preventing other sites from embedding Drupal page How do I prevent other sites from embedding a page from my Drupal site using an iframe? Ideally, I'd like the parent window to redirect to my website if this happens, or alternatively redirect the iframe to an error page.

Any modules/hacks/code/tips?

Thanks

The technique that you want to employ is called framebusting (or framekilling).

The Frameprevention does this.  However, I typically do this manually, as I want it to happen as soon as possible, or I need to do it a certain way to pass an automated test.

Typically, I will edit html.tpl.php to add a no-js class onto the <html> tag, then then add this code bit directly after the opening <head>:

<head<?php print $rdf->profile; ?>>
  <script>
    // http://www.456bereastreet.com/archive/201209/tell_css_that_javascript_is_available_asap/
    document.documentElement.className = document.documentElement.className.replace(/(\s|^)no-js(\s|$)/, '$1js$2');
  </script>
  <?php // bypass render array so this is guaranteed to be very first thing ?>
  <style>html.js { display:none }</style>
  <script>
    if (self == top) {
      document.documentElement.style.display = 'block';
    } else {
      top.location = self.location;
    }
  </script>

This does force users to have Javascript enabled in their browsers, which is a common problem with framebusting.  I cannot find the exact reference for the technique above, but I think it came from OWASP.

You can also implement X-Frame-Options:

function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['mytheme_x_frame_options'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'X-Frame-Options',
      'content' => 'DENY',
    ),
  );

  $head_elements['mytheme_x_frame_options']['#attached']['drupal_add_http_header'][] =
    array('X-Frame-Options', $head_elements['mytheme_x_frame_options']['#attributes']['content']);
}

Keep in mind that you may need additional logic to account for legitimate <iframe> elements in your site.  Some ctools modals come to mind, as well as some WYSIWYG situations.


How to find and remove a cached image? I have an image with url like:

http://example.com/index.php?q=sites/default/files/imagecache/node-gallery-display/123.JPG

I want to remove this image but don't know where it stored in database.

Whenever I remove 123.JPG from the path, it is re-generated on the next GET request.
I removed all nodes with that title from the node table but it had no effect. So I'm have no idea how to find and remove all trace of it from the database. Appreciate your help about it.

Try this:

find -name   "123.JPG" -exec rm {} \;


Looping through an array using Migrate Plus I'm trying to loop through an array (called "Attributes") in a JSON migration source, but I can't figure out how to do it. Here's a shortened sample of my data source:

[
  {
    "Id": "ST00000002",
    "Title": "Fast & Furious 9",
    "Attributes": [
      "0000000013",
      "0000000015"
    ]
  }
]

My ultimate goal is to check certain checkbox/boolean fields based on those attribute values, but I can't figure out how to handle each of the attributes individually.

Things I have tried so far:

Using single_value and multiple_values
Using the custom Deepen process plugin (as seen on this issue)
Using sub_process
Using the static_map plugin (to do something like this:

map:
    '0000000015': 1
default_value: 0

Using skip_on_value with not_equals: true
Using countless combinations of the above functions

I feel like this can't possibly be as difficult as I'm making it, so I hope someone can help me out. Thank you so much.

Thank you so much. I got it to work by creating a custom process plugin using "in_array", as suggested. If anyone's interested, here's the plugin I created:

namespace Drupal\migrate_veezi\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateException;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;

/**
 * Check if value exists in array
 *
 * @MigrateProcessPlugin(
 *   id = "in_array"
 * )
 *
 * To check if value is in array, use the following:
 *
 * @code
 * field_text:
 *   plugin: in_array
 *   source: array
 *   search: 'string'
 * @endcode
 *
 */

class InArray extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {

    $search = $this->configuration['search'];

    if ($search) {
      if (is_array($value) || $value instanceof \Traversable) {
        return in_array($search, $value);
      }
      else {
        throw new MigrateException(sprintf('%s is not traversable', var_export($value, TRUE)));
      }
    }
    else {
      throw new MigrateException(sprintf('search value is not set'));
    }
  }

}

And then I used it like this:

field_closed_caption:
    -
      plugin: single_value
      source: attributes
    -
      plugin: in_array
      search: '0000000007'


Interactive filter options for views I have setup a view with contextual filters; it works great.

Now I just need to setup a few drop downs to allow users to filter on criteria. Does the Views module support this in Drupal 7?

Should I just build a quick module using the form API, set the module to block level, and show the block above the listings?

What's the best practice here?

You can allow your users to filter the view data by "exposing" your filters. See screenshot:


How can I sort a product display view by product popularity I'd like to sort a view of Commerce product displays by their popularity (not too bothered by the specifics of how this is calculated). I found a comment by Ryan Szrama that implies it could be possible with vanilla Views:

  The gist of it is going to require a View of Orders joined to Line Items via the "Commerce Line Items relationship" joined to the Products via the "Referenced product" relationship. You can filter by Order State to only see purchased products and then count the occurrence of each Product ID to get the most referenced products. The hardest part will be establishing a relationship from the Product ID to the product display, but I believe you can use the reverse relationship from the product ID to a node referencing it so long as you only have a single product display per product.

Unfortunately even if my Views-fu was good enough to do that, I'd like for this to be just one possible sort (ie you can sort by price, title, or popularity) so I'd like to avoid using a View of orders. Is there an existing Views sort handler for this floating around at all, or perhaps another clever way to achieve it?

Commerce Product Popularity provides a Radioactivity field for popularity.


Access to core comment preprocess variables in a custom comment layout twig template? In Drupal 8 I have a custom comment type and when I use the default core comment.html.twig to render the comments then variables like 'new_indicator_timestamp' and 'parent' get rendered as expected. But if I switch to using a custom layout (via layout_plugin and display suite) and copy across the relevant twig template code for those core comment preprocess variables into my own custom layout then they don't work.

What do I need to do to ensure that the comment.module template_preprocess_comment() variables are available to my custom comment layout?

Probably the twig changed, layout modules usually bring their own templates. You have to check which templates are used. To find this out use twig debug:

https://www.drupal.org/node/1903374

After you found the right twig you have to use the corresponding preprocess hook, which you find in the comments of the twig template.


Sort an entity query by a term reference field's term weight? I've created an entity query to get an array of nodes based on a specific content type,see below:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'article');
$query->propertyCondition('status', 1, '=');
$result = $query->execute();
$nodes = node_load_multiple(array_keys($result['node']));

The node content type article being queried has a Term Reference field (list of tags). Each taxonomy term is sorted via the admin/structure/taxonomy/tags administration screen.

I have the requirement to have the nodes sorted by term weight. For example the nodes that reference the highest weighted taxonomy term will be at the top.

Is there a way to add a relationship to the taxonomy table using EntityQuery, or is there another way to do this?

Since the weight is kept in a different table than the one that stores the data related to your node, I'm afraid this is impossible using EntityFieldQuery. You'll have to do some custom coding after the query.

By the way, to use data from the reference field (field_data_your_reference) you could use a fieldCondition or fieldOrderBy.


Published checkbox only available for administrator Only the administrator can publish a node of content type Report. It is not using content moderation or groups though other content types are. All permissions are set for the "site admin" to create/edit own/others of this type. The only buttons available are "Save" and "Preview" and the published checkbox doesn't show for non-administrator users. Save sets as "Draft" even though it's not using content moderation.

You can use the following module.

Override Node Options

The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form. It also allows selected field sets to be set as collapsed and / or collapsible.


In D7, Where can you go to get a list of Access Arguments to be used with user_access()? Where can I find a list of Access Arguments to be used with user_access() ? I went to the permissions page and I'm not sure what I can copy and paste from there to be used as an argument for user_access(). So far I only know two: 'access dashboard' and 'access content'

I want to find out how can we get a list of these arguments.

You can get a list of arguments for the site by running this in the terminal:

drush sqlq "select distinct(permission) from role_permission \G"

Make sure you clear cache after making permission adjustments. As my changes weren't showing.


Process Array contents I've done a database query which returns the results in the following array:

Array ( [0] => stdClass Object ( [field_latitude_value] => 25.2000000000 ) [1] => stdClass Object ( [field_latitude_value] => 51.9456801568 ) [2] => stdClass Object ( [field_latitude_value] => 51.9471747475 ) [3] => stdClass Object ( [field_latitude_value] => 51.9471218425 ) )

How do I process this information so I get just the values instead of the added keys? I.e a list of said values.

I'm currently using the following code, which gives me a recoverable fatal error:

<?php

$query = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchAll();

print_r($query);
foreach($query as $value){
    echo $value;
};?>

Instead of fetchAll(), try fetchCol(), like this:

$latitude_values = db_query("SELECT field_latitude_value FROM {field_data_field_latitude}")->fetchCol();


How can an address database be converted to an account profile? I imported an address database into Drupal as a content type and I want to convert into an account profile, with users having the ability to make changes it, and use some of the fields in it to link to other content. Are there some modules which can help accomplish that?

At the very least, after creating a Drupal account for each entry of the database, I should be able to link the user account to a particular record of that content type, or import some of the records fields into the profile.

If you want to keep current content type, add Reference field to your user and reference your type via reference field.

If you don't want to keep current content type, it is better to import the data directly into user fields.


How to prevent adding of duplicate item to Drupal Queue? I am using Drupal Queue (Class DrupalQueue) to store items (a simple objects).

How can I check if there is already the same object in the queue before adding a new one ?

You cannot find the previously entered values in the queue, since the DrupalQueueInterface interface doesn't expose a method to retrieve a previously added value. You cannot even rely on the fact the value is added in a database table, since that is an implementation detail that can change with the class actually implementing the queue, which can be easily changed from a module.

That is the reason why modules like the Aggregator module take their data from their own database table, where they record the last time they added those values in the queue. (See the comment that says Add timestamp to avoid queueing item more than once.)

  $result = db_query('SELECT * FROM {aggregator_feed} WHERE queued = 0 AND checked + refresh < :time AND refresh <> :never', array(
    ':time' => REQUEST_TIME,
    ':never' => AGGREGATOR_CLEAR_NEVER
  ));
  $queue = DrupalQueue::get('aggregator_feeds');
  foreach ($result as $feed) {
    if ($queue->createItem($feed)) {
      // Add timestamp to avoid queueing item more than once.
      db_update('aggregator_feed')
        ->fields(array('queued' => REQUEST_TIME))
        ->condition('fid', $feed->fid)
        ->execute();
    }
  }

  // Remove queued timestamp after 6 hours assuming the update has failed.
  db_update('aggregator_feed')
    ->fields(array('queued' => 0))
    ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
    ->execute();

You could implement a queue class that checks the value has been already inserted, and use that as default queue class, but a module cannot rely on such implementation details.


How to enable tag moderation using rules? I would like to create a rule where if a user adds a tag(taxonomy) which is not allowed (e.g. 'Sexy') the content which contains that tag is sent to be moderated to the site admin for approval before being published.
I am currently stuck on the data selector part as I do not know what to put there!

I think this module Content Moderation is help to create rules

  Some selected group should first review those changes (based one a    specific revision marked for "approval). In the meantime others
  should be able to edit and create new revisions (which are not part
  of this approval process)
  Later some group can approve that revision and make it the new    live-version
  Every state change (review, approval..) should get logged in a    history. You always want to know, who reviewed / approved what, when
  and what revisions
  You want to have a different workflow, like some other states between    review and approve and live. You want to define your own
  workflow.
  You want to create ToDo list for you reviwer / approval teams


Rule to complete checkout for all orders How can I create a rule to process checkout for all orders. Te be more specific: I'm creating a shop in which the whole checkout is based on a cronjob. So customers add their products to the shopping cart and every week at friday a cronjob is processed to process all shopping carts and create a order for them. Payment is not necessary, and users can not manually complete orders.

I've tried to create this in rules, but their is only the option to "Complete checkout for an order" not all orders.

There is no default Commerce rules action that selects all orders. You're going to have to build your own action, or find a contrib module that provides it for you, that selects such a list of commerce orders to act upon.


How to use views taxonomy contextual filters with menu tabs? I have a CT (let's call it Article) with a Status taxonomy field (let's say with values Open, Closed and Cancelled) and I want a view of Articles with menu tabs for each status value. And I would like to have it work with contextual filters on Status term name.

The URLs of the tabs should be like articles/open, articles/closed etc but the last argument should act also as the contextual filter value. I cannot make it work since drupal takes articles/open as part of the url and I should type articles/open/open to have it use the argument.

Is it possible to be implemented with contextual filters somehow? I would like to avoid hidden filter criteria with taxonomy term value preselected, as I want to track it with features and I do not want the id of the preselected taxonomy term tracked.

I managed to resolve the above problem with the following configuration:

I created the contextual filter on taxonomy term field and in the filter settings section When the filter value is NOT in the URL I selected Provide default value and Raw value from URL with Path Component 2 and the option Use path alias checked.

In the filter settings section When the filter value IS in the URL or a default is provided I selected the appropriate vocabulary and for Filter value type Term name converted to term ID.


Update entity on cart page programmatically Drupal Commerce I need to rewrite default view - commerce_cart_form, because of my design of /cart page. So, I've created file views-view--commerce-cart-form.tpl.php and try to repeat something like on original /cart page were. I can print all needed information about line items in cart, but I don't know how to create "Update" button, to change quantity which I typed in textfield with quantity of line item. That's why I want to get help with this.

I use Drupal Commerce 7.x-1.9

Many thanks in advance!

Assuming that you want to display the full view result and add some extra content to your cart, put the following lines in a file named views-view--commerce-cart-form.tpl.php :

if($view->current_display == 'default'){//OR your display
  //dsm($view);
  print $rows;
  print '
MY CUSTOM CONTENT
';
}

Check views-view.tpl.php doc to see available variables.

Otherwise, have a look at Commerce Cart View Override :

  This module provides the ability to override the default cart page
  view for Drupal Commerce.


How can I change the published state of a node before it is saved with hook_entity_presave()? I tried adding this in entity_presave $entity->setPublished(0);  but the node still gets saved as published.  How can I make it be set to draft?

I have tested with hook_entity_presave() and setPublished(0) and setPublished(FALSE) both worked.  So the issue is somewhere else.

If you have workbench moderation installed, you may need to set it to one of your moderation states that set it to unpublished.

See admin/structure/workbench-moderation/states

$entity->set('moderation_state', 'draft');

or

$entity->set('moderation_state', 'unpublished');

or perhaps a custom moderation state.


Apache solr is not accessible by my server but accessible by my localhost I have a solr installed in my server(centos 6.5).and everything works fine and my conf files exist where they should be. I try to connect to solr by help of search_api_solr module in drupal. Everything works fine on my localhost and one other host I try my website on,but when I try to connect to this solr using a website on the same server as the solr I'm get error

  The Solr server could not be reached

where should I start looking for something that went wrong?

problem was caused by selinux on my server.

by disabling selinux and rebooting centOs I could connect to my solr apache.

I found the answer here


How do I create a page (with a url) that displays only views blocks I have been using views to create all of my pages.  I am wondering if there is a way to set up a page (with url) that is initially blank.  I want to use context to place view blocks on this page based on user roles.  If a context is not matched, then the url should act as though the page does not exist (would I need a rule for this?)  How can I build this?

One way of solving your issue is by installing the following modules:

Empty Page

  The Empty Page module is a simple empty page solution. It provides an interface that assists in managing "empty" menu callbacks, mostly used for pages that only consist of blocks.

Path Access

  The Path Access module gives site administrators an additional layer
  of access control to all pages of a Drupal site.

Chain Menu Access API - required by Path Access module

  Chain Menu Access API allows your module to chain its own menu access
  callback functions into other modules' menu router entries.

After installing all the above modules, try to implement the following steps:

Add new empty page from admin/structure/empty-page/add.
locate blocks you need to display on the created page using Context with Path condition and Blocks reaction.
Now from Access Path settings admin/config/people/pathaccess specify who should access the created page and who should not per user role.

I hope this will help you.


Use a form instead of content type in maestro drupal module I am working on maestro module of Drupal 7, the module uses content type to add the form fields ,but instead of content type i want to use simple form which i have created using php , can anyone please help me , it is very urgent.
Thanks a lot in advance

for those who are  still searching the answer for this question

We can use webform instead of content type with maestro, for that we need maestro_webform_task module, the module will integrates
both web form and maestro and provides the list of already created web forms in web form task->edit->select web form to use

maestro_webform_task


How to find which templates are affecting a display? spending hours dealing with form_alter , finally realized that a tpl.php file is overriding the output !!!

now the question is

  what are the ways to understand which template files(or functions) are affecting a display so they can be customized ?

First, you can easily debug everything with Devel module. Another trick that I use to inspect what tpl is generating a particular element is by adding $conf['theme_debug'] = TRUE; in settings.php. After adding that refresh your page (or clear your cache first) then use inspect element. The tpl should be visible now in the HTML source. See the screenshot below.

Here is a blog that describe on how to theme a field.

Hoe that helps.


What's the best way to create a booking form? I need to create a booking form for an event.
This form will contain normal text field plus one drop down list with the number of tickets.
There will be a prefilled field with the price of the single ticket that user can modify.
After the field with the price of the single ticket there will be an other field with the total price of the tickets and when they select the number of the tickets automatically the total price will be updated and stored in the database after the form is submitted.
After the submit I need to send an email, I can use mime-mail but let me know if I need to change method due the live field of the prices.

There is not online payment expected.

Let me know if everything is clear.

If you're new to Drupal, I would first try the webform module.  This is a very popular, well tested module that often gets security fixes which less commonly used modules may not get.

It has all the basic functions you need for creating the options for the form and can easily be configured to send an e-mail upon submission.  It will also leave a record of all submitted data in the Drupal database.

To be honest, off the top of my head I'm not sure if webform can do the computation you request or not.  However, for that there is the computed field module, which will allow you to write a simple function in PHP to compute the value.  Alternately, you could use the rules module's "on node save" event with the action "compute data value" to calculate the total price.

There are a number of other approaches as well but these are commonly used Drupal modules with fairly good documentation and thus are, I think, a good place to start.


How can I track statistics on how often a hook/error message is triggered? I am using the Privatemsg module in Drupal 7.  I have a hook in a custom module that is triggered when users write a message that is too short.  I set this up using the instructions here.

Basically, it looks like this:

function mymodule_privatemsg_message_validate($message) {
  $uid = $vars['message']->author->uid;

  //if root or help user, message should always go through regardless of length
  if ($uid !== '1') {
    if ($uid !== '3') {

      if (empty($message->thread_id) && strlen($message->body) < 200 ) {
    form_set_error('[body][value]', t('My custom message.'));
      }
    }
  }
}

I recently noticed there are not so many messages being sent on my site.  I would like to know if it is because they are being blocked by this hook.  How can I track how many times it is triggered (and even better if I can know which logged-in users are getting the error message)?

I don't think you'll get 'statistics' as such without some coding yourself, I've never seen a module that does that sort of thing (but hey it's Drupal so there probably is one somewhere).

Failing that I think your best bet would be to use the the watchdog() function, combined with enabling the dblog module on your site. You can use it like so:

if (empty($message->thread_id) && strlen($message->body) < 200 ) {
  form_set_error('[body][value]', t('My custom message.'));

  global $user;
  watchdog('mymodule', 'My custom message for user @username', array('@username' => $user->name));
}

Every time that if statement is entered you'll get a message on the 'Recent log messages' page, where you can even filter by entries for your own module, giving you a basic idea of what's happening, when, and for whom.


Preprocess function per content type I have a couple of content types which I need to preprocess in different ways. So template.php in my theme foo currently looks like:

function foo_preprocess_node(&$variables) {
    if ('news' ==$variables['type']) _preprocess_news($variables);
    if ('event'==$variables['type']) _preprocess_event($variables);
    if ('alert'==$variables['type']) _preprocess_alert($variables);
    ...
}

function _preprocess_news(&$variables) {
    ...
}

function _preprocess_event(&$variables) {
    ...
}

function _preprocess_alert(&$variables) {
    ...
}

I'd like to be able to specify a Drupal specific preprocess function which would hook on the content type's machine name. I tried using foo_preprocess_news but it is never called.

Is there a better way?

The zen subtheme accomplishes this by adding this to its theme_preprocess_node function:

function foo_preprocess_node(&$variables, $hook) {
  ...
    // Optionally, run node-type-specific preprocess functions, like
  // foo_preprocess_node_page() or foo_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $variables['node']->type;
  if (function_exists($function)) {
    $function($variables, $hook);
  }
  ...
}

If you have a content type called 'news', then you would be able to create a function called foo_preprocess_node_news in your template.php file.


How to add "rel=nofollow" to ALL external links? How to add "rel=nofollow" attribute to ALL external links....in Drupal 7?

So far I can find only with different filters and what not....

Before I was working with Joomla - I had a single plugin which was once set up - and wrapped ALL, completely all external links, wherever they would be - in Menus, articles, modules, social buttons, advertisements, etc....

I just cannot understand why would I need some Filter - the only Filtering option should be - it is an External link...

If I would know all external URL some scripts or users may add to my site - it would be great. But my experience shows - external URLs are almost always added secretly without me being aware of it; but it still should have "rel=nofollow"..

Have you tried this module : Noindex External Links

Module let's you take full control of external links indexing. Pages could also pass HTML-validation.

  Features

  Two methods of indexing control:

  Wrap links with NOINDEX tag. NOINDEX tag is used to deny indexing part of page. Only Yandex and Rambler considers this tag but Google
  and others doesn't. There is also an attribute NOINDEX in meta-tag
  Robots.
  Add attribute rel="nofollow" to links. This link's attribute has no effect on indexing. Only Google really do not follow this links but
  others do. Attribute is used to say to search engine that links no
  longer constitute a "vote" in the PageRank system.


Calendar popup field get a default value. How to avoid this? I have all necessary module to add "Calendar popup" fields to my nodes.

When creating a new node this field is populated with the current date. Since this field is not mandatory I need it empty by default.

I can´t figure out how to accomplish this.  Please help.

I upload a capture

Edit the date field in your Content Type.  There should be a MORE SETTINGS AND VALUES accordion that drops down to reveal more options including DEFAULT VALUES.  Set the default value to No Default Value.  You probably have it set to Now.


There are no entities matching. BaseFieldDefinition entity reference error for taxonomy My Code looks like this:
$fields['color'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Color'))
  ->setDescription(t('The color of the fruit.'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['Color' => 'Color']])
  ->setDisplayOptions('view', [
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
    'weight' => -3,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

I have a vocabulary with the name : 'Color'
I have 3 terms in it : 'Red', 'Yellow', 'Green'
The error I'm getting is this :

I'm trying to figure out what went wrong.

Change the Color to color in ['target_bundles' => ['Color' => 'Color']]) if you create a vocabulary caller Color the machine name will be color Not Color So try with:

$fields['color'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Color'))
      ->setDescription(t('The color of the fruit.'))
      ->setSetting('target_type', 'taxonomy_term')
      ->setSetting('handler', 'default:taxonomy_term')
      // Target is color not Color.
      ->setSetting('handler_settings', ['target_bundles' => ['color' => 'Color']])
      ->setDisplayOptions('view', [
        'label'  => 'above',
        'type'   => 'author',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type'     => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator'    => 'CONTAINS',
          'size'              => 60,
          'autocomplete_type' => 'tags',
          'placeholder'       => '',
        ],
        'weight'   => -3,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);


How to change view's field (Custom-Text field specifically) value based on other field value using hook_view_pre_render? I have created a taxonomy-term view.
I have added two fields in a view: term-id and custom-text field.

I want to check if term-id has children and depending upon the result, I want to set markup inside custom-text field.

I am able to get term-id in hook_views_pre_render with following code, but I am not able to set the value of custom-text field

function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
 if ($view->id() == 'test_view' && $view->current_display == 'block_2') {
    foreach($view->result as $value){
        $tid = $value->_entity->get('tid')->value;
        kint($tid);

        //trying to set value for custom text field, with foll. line of code
        //'nothing' is the field-name you get for any custom-text field
        $value->_entity->set('nothing', '
This is my custom mark-up
');
    }
 }
}

I referred the code from these following 2 sources, but they are not dealing with custom-text field:

How to change views field value using a hook
https://api.drupal.org/comment/62573#comment-62573

Or should I use template_preprocess_views_view_fields(), if yes then how can I get term-id value to check if it has children terms.

Any help will be appreciated.

You can't set a value for "nothing" aka "Global: Custom text" in hook_views_pre_render() because _entity is the entity object. The entity (Taxonomy Term in your case, and Node in my test case) does not contain this field.

Therefore, you need to use template_preprocess_views_view_field

function THENAME_preprocess_views_view_field(&$vars) {
  if(isset($vars['view']) && ($vars['view']->id() == 'test_view') && ($vars['view']->current_display == 'block_2')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      if ($vars['field']->field == 'nothing') {
        $tid = $vars['row']->_entity->get('tid')->value; // get tid
        if ($vars['field']->field == 'nothing') {
          $vars['output'] = [
            '#markup' => "
This is my custom mark-up with term id: $tid
",
          ];
        }
      }
    }
  }
}


Display suggested search result on search page if search result is empty There are any way or module to display search result from suggested keyword on search page if search result is empty. just like google search, But result should come from my Apache solr system.

The Search API Spellcheck module might be a starting point. It interfaces with the Search API Solr module.

Hope it helps,


how to inject JQuery into a D7 page I have a Drupal 7 view page where I want to change the behaviour of the submit button by using the jQuery code below. How do I do this in Drupal 7?

$('#reset-button').click(function() {
  $('#views-exposed-form').each(function() {
    this.reset();
  });
  $('#submit-button').click();

  return false;
});

You can add your code in a JS file say somescript.js and save it in your theme folder. In the theme.info file add the following line

scripts[] = somescript.js

This will add somescript.js to all pages by default. If you want it for a particular page add a conditional check and use drupal_add_js(PATH_TO_JS)
For more info check out Managing JavaScript in Drupal 7


Strict warning: Only variables should be passed by reference I am getting this error on this line in my code. I'm guessing I need to break this line down a bit. Any comments would be great.

$promobox_id = reset(array_keys($result['fieldable_panels_pane']));

That's not a Drupal error. It's a PHP error. You're getting it because the reset function expects an array to be passed by reference. You are passing it the return value of the array_keys function, which does not return its result by reference.

If you want to break down your code to avoid this error, try something like this:

$array_keys = array_keys($result['fieldable_panels_pane']);
$promobox_id = reset($array_keys);

Also, consider seeing this page for more information: http://www.php.net/manual/en/language.references.pass.php


How to grant user User Points after publishing content, while content's default is unpublished? I'd like to grant users User Points when their added content of the content type 'Content', which is unpublished by default, is published. I tried this with the Rules module:
- Event: After saving new content
- Elements:
  * Content is of type: Content
  * Content is published
- Actions: Grant points to a user

So, when a user adds 'Content' content, they don't get any User Points and their content is unpublished. My idea was that they'd be granted the points after I - as moderator - had published their content. But apparently, they don't get points after I've done that with the rule I set up. What did I do wrong and how can I solve this?

I solved my problem by doing this:

Create flag and give flag name as Publish node and grant points to user
Add new rule with event A node has been flagged, under "Publish node and grant points to user"
For actions publish this node and grant points to user use this data selector: flagged-node:author

Special thanks to oneng on Stackoverflow!


What can cause duplicated XML sitemap links? I have a site where I have XML Sitemap installed.  I was using node-based sitemaps, and everything was working fine.  I also enabled the menu sub-module, and now I see duplicate links for all of my content:

What can cause this?

Please visit the feature request about "Remove duplicate links when using both menu and node sitemap". It has a patch which works fine.


Accessing field inside a block I have created a block to display flash content. All it needs a a variable to be assigned dynamically from the content to flashVar. I created a field called myfile path in the custom content type. Which is just a text pointing to the path of file. I also created a block and below is the code inside the block.

<?php
$myFilePath = field_get_items('node', $node, 'field_myfilepath');
?>

Floorplan Basic

                To view this content you need Adobe flash player (v11+) plug-in installed on your browser

Get Adobe Flash player

I am getting this error

EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7663 of C:\...\www\includes\common.inc).

Can any on tell me how to get the value of the field in this block? I am totally new to drupal.

I guess $node is not defined. You should know when a node page is shown. Then get the node id using arg(1). Load the node object and then use.


How do I enable the Views Contact Form module? I cannot install the Views Contact Form module because it depends from the Email module, which is said to be missing, in the module page. The Email module is not a Drupal 8 core module.

How do I install that module?

The Views Contact Form module doesn't actually works for Drupal 8, since it puts its class files in [module directory]/lib/Drupal/views_contact_form (PSR0), when Drupal 8 now requires them to be in [module directory]/src (PSR4), inside the module directory. Looking at the code, I notice the module has not been updated to work with the official releases of Drupal 8.0, nor 8.1.

For this reason, not even removing the dependency on the Email Field module from
the views_contact_form.info.yml file would work. Otherwise, I would have suggested to change the views_contact_form.info.yml file as follows.

name: Views Contact Form
description: Views Contact Form
core: 8.x
type: module
dependencies:
 - views

To add more details about the dependecies, the Views Contact Form module declares its dependency from the Email Field module, which is only for Drupal 7. In the project page of the latter module, it's clearly stated:

  The basic email field type is in core now: #1668332: Add an E-mail field type into core, making this contrib module obsolete. Specific formatters (like the contact form) can live in separate contrib modules.

It seems the Views Contact Form module implements one of those formatters, so it would just require the email field already present in core. Unfortunately, the module has not been updated to work with the latest releases of Drupal 8.


Entity create access based on a custom field Is there a way to allow/prevent users to create a new entity based on an entity field? Because the checkCreateAccess() / hook_entity_create_access() function is not receiving the actual entity as a parameter, just the bundle.

Is is ok to do a check on 'hook_entity_presave()' and throw an exception there?

Use the rules module instead? https://www.drupal.org/project/rules

Before saving entity of type X
Entity has field Y
Entity field Y is Z
Allow, else deny


How do I print custom html in nodes of a certain type using template.php? I want to print some custom html inside nodes of a certain type.
I could use node.tpl.php, but i'd prefer a template.php solution.

THX in advance.

If you want to provide a new variable to your node template file you should implement hook_preprocess_node() in your theme and pass it from there:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['extra_html'] = my_function_to_build_html_string();
  }
}

Then in your node.tpl.php file you can output that HTML wherever you want like so:

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

If you just want to add some HTML into the normal content of the node, you would do it like this:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'node_type') {
    $vars['content']['extra_html'] = array(
      '#markup' => my_function_to_build_html_string(),
      '#weight' => -10 // Control the display order of this element
    );
  }
}

In either case you'll need to clear Drupal's caches once you've implemented this hook so the theme registry picks it up.


Insert or Update value in table mysql? I just trying to save or insert data into a mysql from inside a custom module.

The table is 'my_table'.

I use this to insert:

  db_insert('my_table')->fields(array(
    'name' => 'Andy',
    'last_name' => 'Moore',

  ))->execute();

and this to update:

  db_update('my_table')
  ->fields(array(
    'name' => 'John'
  ))
  ->condition('last_name', 'Moore')
  ->execute();

So far so good, but now I need to update or insert a value:

If 'name=George' exist then update its 'last_name=Niels'. Otherwise if  'name=George' doesn't exist then create insert it with this values 'name=George' and 'last_name=Niels'

You can use db_merge() function. Here is the example.

db_merge('my_table')
  ->insertFields(array(
    'name' => 'George',
    'last_name' => 'Niels',
  ))
  ->updateFields(array(
    'last_name' => 'Niels',
  ))
  ->key(array('name' => 'George'))
  ->execute();

If there is no key ("name") with value "George", "name" and "last_name" values are inserted to the database table. If there is a record with key value "George", only the field "last_name" is updated with the specified value.


How to invoke autodialog module close method in autodialog.js file using ajax_command_invoke I have form that loads in modal using autodialog module and I have two buttons inside the form the close and save button. What I am trying to achieve is to just close the modal when the close button is clicked. I can do this using jQuery but what I wanted to do is use ajax_command_invoke to invoke autodialog close to close the modal. so far this what I have done, but I can't make it work maybe I am doing it wrong.

function example_autodialog_close_form_submit($form, &$form_state) {
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save':
      // Insert data in database.
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

  Using jQuery, this one work but what I wanted is use
  ajax_command_invoke to invoke auto dialog close.

$('#autodialog-close').click(function() {
  $('.autodialog-content').dialog('close');
});

Some code snippet in autodialog module autodialog.js file.

  Drupal.ajax.prototype.commands.autodialog = function (ajax, response, status) {
    var options = {
      title: response.title,
      width: 500,
      modal: true,
      closeText: Drupal.t('Close'),
      close: function () {
        $(this).dialog('destroy').remove();
      }
    };
    $.extend(options, response.options);

    // Close previous dialog
    if (options.closeprev) {
      $('.autodialog-content').dialog('close');
    }

    // Create dialog content
    var $dialogContent = $('' + response.content + '').appendTo('body');

    // Open dialog. Not $dialog.dialog() because it causes problems with inline scripts for jQuery 1.4.
    $('#' + response.dialog_id).dialog(options);

    // Remove focus from first tabbable element
    $dialogContent.closest('.ui-dialog').focus();

    // Close dialog when clicked outside
    $('.ui-widget-overlay:last').click(function (event) {
      if ($(event.target).hasClass('ui-widget-overlay')) {
        $dialogContent.dialog('close');
      }
    });

    Drupal.attachBehaviors($dialogContent);
  }

Finally I made it work.

Instead of using asaf module (This module is used to AJAX-ify form submissions) - not aware of this one, just notice it appending its own ajax class. thought that autodialog already made the submit button ajaxified. In combo with autodialog I make my form api submit button ajaxified.

here's my working code

Form submit buttons.

  $form['closed'] = array(
    '#type' => 'submit',
    '#value' => 'Closed',
    '#attributes' => array('class' => array('btn btn-block btn-default btn-sm')),
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Changes',
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

Ajax callback

function ajax_example_submit($form, &$form_state) {
  $commands = array();
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save Changes':
      drupal_set_message('Saved Changes');
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}


How get a programmatically menu fields into template? i add to my main menu an image field programmatically for build a megaMenu :

/**
 * Implements hook_entity_base_field_info().
 */
function hook_entity_base_field_info(EntityTypeInterface $entity_type) {

    $fields = [];

    if ($entity_type->id() == 'menu_link_content') {

        $year = date('Y');
        $month = date('m');

        $fields['image'] = BaseFieldDefinition::create('image')
            ->setLabel(t('Image'))
            ->setDescription(t('Image field'))
            ->setSettings([
                'file_directory' => 'imagesMenu'. '/' . $year . '/' . $month,
                'alt_field_required' => FALSE,
                'file_extensions' => 'png jpg jpeg',
            ])
            ->setDisplayOptions('view', array(
                'label' => 'hidden',
                'type' => 'default',
                'weight' => 0,
            ))
            ->setDisplayOptions('form', array(
                'label' => 'hidden',
                'type' => 'image_image',
                'weight' => 0,
            ))
            ->setDisplayConfigurable('form', TRUE)
            ->setDisplayConfigurable('view', TRUE);
    }

    return $fields;
}

After a drush update-entity, i can see the field on my form and i can add the image.

Now i try to get this field into twig.

When i use kint with keys this is the result :

  menu--main.html.twig

I cannot see my field image.

Any idea how can i get my field in tempalte ? hook_preprocess for the menu ?

This is how i get my custom image field from menu into twig

function hook_preprocess_menu(&$variables, $hook) {

    if($variables['theme_hook_original'] == 'menu__main'){

            $items = $variables['items'];
            foreach ($items as $key => $item) {

                if(count($item['below'])>0)
                {
                    foreach($item['below'] as $id=>$array)
                    {
                        $entity = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('uuid'=>$array['original_link']->getDerivativeId()));

                        foreach($entity as $idMenu)
                        {

                            if($idMenu->get('image')->entity != null) {

                                $image = file_create_url($idMenu->get('image')->entity->getFileUri());

                                $items[$key]['below'][$id]['imageUrl'] = $image;

                            }
                        }

                    }

                }

            }

        $variables['items']=$items;

    }

}

I just work on my item menu and add 'imageUrl' into my array.
I first load my entity by properties with the UUID for access to my menu item fields.

This method is only for my sub menu ( inside my mega menu, i want just add an image by item in submenu )

  that why i check count(item['below']>0)

For now i can't find better way.


i have prepared form api, now how to insert form values when i click submit button by using db_insert I have prepared a form using Drupal form API. Now how can I insert the form values when I click the submit button by using db_insert()?

$form['totp'] = array(
    '#title' => t('Title of the Programme'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#maxlength' => 250,
    '#size' => 50,
);

$form['pd'] = array(
    '#type' => 'radios',
    '#title' => t('Programme Day'),
    '#required' => TRUE,
    '#options' => array(
        0 => 'One Day Programme',
        1 => 'Two or More Day Programmes'
    ),
);

The above values to be stored in MySQL table?

You would need to add a custom form submit handler.

$form['#submit'][] = 'mymodule_custom_form_submit';

Then, in the function, use $form_state['values'];

function mymodule_custom_form_submit($form, $form_state){
    db_insert('yourtable')
        ->fields(array(
            'totp' => $form_state['values']['totp'],
            'pd' => $form_state['values']['pd']
          ))
        ->execute();
}


Change Default Value of XML sitemap enable/disable flag Is there a way to change the default value of a node's XML sitemap enable/disable flag for the XML sitemap module?

The default is disabled.  I have a large old site that I want to have completely site-mapped by the module. The documentation I can find says I need to edit every node to enable -- there has to be an easier way.

Barring that, is there a Drush command available for it?

You seem to be asking 2 things.

The default inclusion status for nodes is set on the node type's edit page (admin/structure/types/manage/MYTYPE). The XMLSiteMap settings are stored as xmlsitemap_settings_node_MYTYPE in   keyed array (status key) if you'd rather drush vset the setting.

As for bulk inclusion, the xmlsitemap table stores all items index for inclusion/exclusion in your site map. A drush sqlq command can bulk update these settings.

#Set all XMLSiteMap node entries as included
drush sqlq 'UPDATE xmlsitemap SET `status` = 1 WHERE `type` = "node"'
drush xmlsitemap-rebuild


How to invoke a post drush command? I am using Drush 9 and Drupal 8. When I execute drush site:install I find that it also modifies the permission of the web/site/default directory to r-xr-x--x, which troubles me delete that directory later. I want that directory to be 740 in my case. So two methods came to my mind. One is to run a custom shell script as post drush si or to override the default dush si command. I tried to go through some blogs but I couldn't understand them. Please explain stepwise.

How can I invoke a custom shell script to drush site:install which will be run just after that command is executed.

How can I override the default site:install command?

Note: I am using Drupal composer project. So I have a drush folder outside the webroot but I don't know if I can edit some files in that directory and write my custom commands.

See the example file PolicyCommands.php in the Druhs examples directory. Create a directory named "Commands" in your site's "drush" directory, and put your command file there. Its name must end with "Commands.php" or "Hooks.php".

Create a hook similar to one of the ones shown in the example file. You'll want @hook post-command site:install.


Show products based on the location (country) of the visiting user I need to display products based on the country of the visiting user, the countries have the same language (Spanish), but different systems of currency, I installed the module smart ip to identify the country of the visiting user and the countries module for creating the product can select the country or countries where the product will be available, my goal now is to make filter in the view to show only the products available in the country of the visiting user.

According to the countries module page:

  Views Integration

  The 2.x branch supports View operations. The views filter is supported via 'select list' in the following way:

  Create a Relationship (under 'Advanced') to 'Field: Country (field-country)' ('Country' being the field label, 'field_country' the field name).

  The field is shown twice in the list

  Field: Country

  Field: Country (field-country)

  The first one is not working. This broken relationship has been removed in the latest dev version.

  Add a Field/Filter/Sort of type 'Countries: xyz' with the new relationship.

Also, you might consider Nick's answer for hiding the product "Add to cart" based on country.


How to preload a css/js library programmatically after module installation? is there api for changing *.library.yml file? i would like to develop a module where i cached internally html,css,js statically for pages.
1) in a admin setting page i can add a bundle with 1 html page + css/js files.
2) for each bundle i have different path
3) Normally in drupal8 i can define a file *.library.yml where i can set css/js but in this case is not defined statically when i install the module, but is changed every time in admin section i add a bundle.

Is there drupal API for loading programmatically the register where there are saved libraries and where i can change and save again the configuration? it is not possible do you have other suggestions?

Drupal allows modules to add dynamic library definitions by implementing hook_library_info_build(). Drupal core doesn't implement this hook, except in a test module.

function common_test_library_info_build() {
  $libraries = [];
  if (\Drupal::state()->get('common_test.library_info_build_test')) {
    $libraries['dynamic_library'] = [
      'version' => '1.0',
      'css' => [
        'base' => [
          'common_test.css' => [],
        ],
      ],
    ];
  }
  return $libraries;
}

If you instead need to alter the library definitions given from another module, hook_library_info_alter() is the correct hook to use.

function locale_library_info_alter(array &$libraries, $module) {
  if ($module === 'core' && isset($libraries['jquery.ui.datepicker'])) {
    $libraries['jquery.ui.datepicker']['dependencies'][] = 'locale/drupal.locale.datepicker';
    $libraries['jquery.ui.datepicker']['drupalSettings']['jquery']['ui']['datepicker'] = [
      'isRTL' => NULL,
      'firstDay' => NULL,
    ];
  }

  // When the locale module is enabled, we update the core/drupal library to
  // have a dependency on the locale/translations library, which provides
  // window.drupalTranslations, containing the translations for all strings in
  // JavaScript assets in the current language.
  // @see locale_js_alter()
  if ($module === 'core' && isset($libraries['drupal'])) {
    $libraries['drupal']['dependencies'][] = 'locale/translations';
  }
}


What modules do I need to implement web services? We have planned to create a bank loan application in Drupal. The Application does not have any own users records, but it completely depends on external service provider.

For example, when we log in to the application, the username and password should hit the service provider, and fetch the result from the provider; the login information should be validated into the application.

How do I implement the web service in Drupal? What type of modules do I need to use?

I need to be able to do CRUD operations using web services.

I've used the soapclient module in D6 for my cause with a SOAP server. It works by making SOAP calls and keeps things really simple. One method to instantiate the SOAP object and another to make the call. It has a good test page where you could enter the webservice end point, the mode like XML RPC etc. and other options such as the service method and service parameters and test the response which is quite good as you can test the service without any actual code. If you plan on implementing webservice with SOAP it is a nice module.


Apache Solr 4.6.0 installation and compatibility with Drupal7 I'm having difficulties installing Apache Solr. The latest version that I downloaded was 4.6.0.  But all Drupal documentation and tutorials (see http://www.youtube.com/watch?v=ori-VvvH1Aw) are talking about 3.5.0.  While 3.5.0 is nowhere to be found on internet, 4.6.0 has a totally different directory structure, and there is no documentation on how to install this latest version on a server or on a local WAMP.  There is no mentioning of which Apache Solr versions are most recommended to work with Drupal?  Any help?

You aren't alone I had to scour the internet and read several articles before I truly understand all of this. I tried about three different methods until I finally got it right!

If you are using Debian/Ubuntu (with Tomcat7) it's even easier then most outline. I preferred this over Lullabot since when you install it through Ubuntu it's actually a service and less fiddling :)

Install Java

apt-get install java7-jdk

Install Tomcat

apt-get install tomcat7 tomcat7-admin

Once this is done you can get to http://localhost:8080 and see that's it is all running properly.

Note: It's recommended to push the port to another one since 8080 is pretty common. If you want to do that use this code for that!

sudo sed -i s/8080/8983/g /var/lib/tomcat7/conf/server.xml

Configure Tomcat

You will want to actually create a users account for Tomcat so that other people have to log into the admin (it keeps it safer).

nano /var/lib/tomcat7/conf/tomcat-users.xml
Then add these xml arguments between the <tomcat-users> tags

<role rolename="manager-gui"/>
 <role rolename="admin-gui"/>
 <user username="!!somename!!" password="!!somepassword!!" roles="manager-gui,admin-gui"/>
Now you can restart tomcat again and view the admin page at  http://localhost:8983/manager/html

service tomcat7 restart

Install Solr

Download the latest ApacheSolr here (When I wrote this I got it working with 4.7)
Extract the files into a directory

Copy Solr library files

Next we want to add the library files to Tomcat library directory. Note: You can also use symlinks if you prefer, but for the purpose of understand where everything goes I chose to place it directly in the directories

cp ~/solr-4.x.x/example/lib/ext/* /usr/share/tomcat7/lib/

It may be a good idea to also copy the java libraries from solr/dist/solrrj-lib/*

cp ~/solr-4.x.x/dist/solrj-lib/* /usr/local/tomcat7/lib/

Copy Solr WAR app file

cp ~/solr-4.x.x/dist/solr-4.x.x.war /var/lib/tomcat7/webapps/solr.war

Setup Drupal ApacheSolr core

We first need to copy over the sample configuration files from ApacheSolr.

mkdir -p /var/lib/tomcat7/solr
cp -r ~/solr-4.x.x/example/solr/collection1/conf /var/lib/tomcat7/solr/
Next grab the latest version of the apachesolr module https://drupal.org/project/apachesolr and unzip it

tar xvf apachesolr-*.tar.gz
Syncronize the apachesolr configuration files (for Drupal) with your solr configuration

rsync -av apachesolr/solr-conf/solr-4.x/ /var/lib/tomcat7/solr/conf/

Note: I found an error in which ApacheSolr refused to start due to duplicate errors. I reported that here so you might want to look at the solution here as at the time of writing this I could not get it running without that!

Create a core definition file to tell Apache Solr which cores are available.

nano /var/lib/tomcat7/solr/solr.xml
Paste the following code inside that file

<?xml version="1.0" encoding="UTF-8" ?>
 <solr persistent="false">
   <cores adminPath="/admin/cores">
     <core name="!!yourcorename!!" instanceDir="!!yourcoredir!!" />
    </cores>
  </solr>

Create Drupal core directory

This will create a new core in your system with that name. If you wish to add more you simply can repeat this step as well as the one above.

mkdir /var/lib/tomcat7/solr/!!yourcoredir!!
cp -r /var/lib/tomcat7/solr/conf /var/lib/tomcat7/solr/!!yourcoredir!!/

Let's Make It Live

Your at the last stretch!! Let's put tomcat7 to sleep

service tomcat7 stop
Now change the permissions on the tomcat directory

chown -R tomcat7:tomcat7 /var/lib/tomcat7
Start it back up

service tomcat7 start

It's Live

You should be able to go to http://localhost:8983/solr and see a new core instance available! Now you can go ahead and configure drupal to point to that.

Note: Your new core is located at http://localhost:8983/solr/!!yourcorename!! to be used in the Drupal ApacheSolr module.

Credit and props goes out to Pacoup


Override user login form template I'm trying to customize my user login page in my custom theme using the template file page--user--login.html.twig, but am having issues accessing the different form elements. All aspects of the form are located in page.content, but I'd like to edit the content that's being outputted.
For a simple example, the base theme has Username and Password stacked vertically, where I'd like to adjust this to use bootstrap so that they are stacked horizontally on large screen and vertically on mobile.
In Drupal 7, we had a form element in the template file that allowed me to render certain form elements separately, like:

  <?php print drupal_render($form['name']); ?>

  <?php print drupal_render($form['pass']); ?>

Is there an equivalent for Drupal 8?
I attempted to create a template file for the form (form--user-login.html.twig and form--user-login-form.html.twig) to see if I could alter the form template itself instead of the page the form exists on, but didn't have any luck with that.
I'd prefer to override the current login theme instead of creating a whole new page and form and have to add all the necessary configurations so that a user lands on the correct login page, but have yet to find any way to do so, thanks in advance.

if you overrided correctly element will contain all items in form--user-login.html.twig,

    <form{{ attributes }}>

hello world

            {{ element.messages }}
            {{ element.name }} {# username element #}
            {{ element.pass }} {# password element #}

                <input id="show_password" class="show_password" type="checkbox" />
                Show password
                Forgot Password?

            {{ element.form_build_id }} {# required #}
            {{ element.form_id }} {# required #}

                {{ element.actions.submit }}

    </form>

if the template is not valid, you should try to add it.
function Yourtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {

  if ($hook == 'form' & !empty($variables['element']['#id'])) {
    $suggestions[] = 'form__' . str_replace('-', '_', $variables['element']['#id']);
  }
}

then create form--user-login-form.html.twig in your theme.
do not forget to clear the cache.


Using views to find list of users nearby using location in arguments I am using drupal 6.X
I am creating an api through views and views datasource module
in which i will add the latitude and longitude of the location in the end of the url as we define the arguments in the view so that i can get the list of users in the order of the nearest first.

I think you are telling about the proximity search and you want to display the user/nodes with in a particular distance based on the location of a single user/node.

You can select the "location" in the filter and there you can see the distance/proximity option


Drupal and node.js configuration I have a problem with Nodejs and Rules action with node.js modules

First, I have installed node.js on my server following the README.txt instructions and then configured the node.config.js file as the sample file and had no problem connecting Drupal with node.js. But after creating a rule of new nodes, I checked messages like this in the debugger:

Started http server.
   info  - socket.io started
publishMessageToContentChannel: message { uniqid: '520d016b52adc',
  markup: '
\n

\n

\n
\n      TEST TITLE
\n
value of body action message
\n
\n',
  callback: 'nodejsAction',
  messageAuthorUid: '1',
  channel: 'rules_nodejs_role_2',
  clientSocketId: '' }
publishMessageToContentChannel: message { uniqid: '520d016b52adc',
  markup: '
\n

\n

\n
\n      TEST TITLE
\n
value of body action message
\n
\n',
  callback: 'nodejsAction',
  messageAuthorUid: '1',
  channel: 'rules_nodejs_user_3',
  clientSocketId: '' }
publishMessageToContentChannel: The channel "rules_nodejs_user_3" doesn't exist.
publishMessageToContentChannel: message { channel: 'watchdog_dblog',
  commands:
   [ { command: 'insert',
       method: 'before',
       selector: '#admin-dblog tr:eq(1)',
       data: '
	content	08/15/2013 - 12:27
          page: added node 18.	admin	view
',
       settings: null } ],
  callback: 'nodejsWatchdog',
  clientSocketId: '' }
publishMessageToContentChannel: The channel "watchdog_dblog" doesn't exist.
setContentToken: message { token: 'Xx0RmC36fXFTnyH_goIX21fP-2iDJMhTk_u-iWBpcM4',
  channel: 'rules_nodejs_user_1',
  notifyOnDisconnect: false }
setContentToken Xx0RmC36fXFTnyH_goIX21fP-2iDJMhTk_u-iWBpcM4 for channel rules_nodejs_user_1
setContentToken: message { token: 'u3EbOVHjEdIiL6mlGbN8p4T5CifL2Gt-tZc2jfqfbCE',
  channel: 'rules_nodejs_role_2',
  notifyOnDisconnect: false }
setContentToken u3EbOVHjEdIiL6mlGbN8p4T5CifL2Gt-tZc2jfqfbCE for channel rules_nodejs_role_2
setContentToken: message { token: '9WLPPJWOr7XlMXLYbhhiuBvMwN4Bd4o9_6exS-_cspU',
  channel: 'rules_nodejs_role_3',
  notifyOnDisconnect: false }
setContentToken 9WLPPJWOr7XlMXLYbhhiuBvMwN4Bd4o9_6exS-_cspU for channel rules_nodejs_role_3

However, I couldn't get the notifications on my browser and I don't know if I'm missing some extra configuration for it.

noddejs module is hard to configure and make it work as it is under development and not stable yet (I tried personally)

take a look at tha sandbox project it may help nodejs-chat-d7


Unwanted data show after add password-comfirm In my form I would like to add comfirm password field, the pic below show is before adding comfirm field, there is no data in waiter name field, after adding comfirm-password field there are data in waiter name field and password field, where do they come from. Anyone could please to help me to solve this problem.

function waiter_form($form, &$form_state= NULL) {

$form['waiter_name'] = array(
'#type' => 'textfield',
'#title' => t('Waiter Name'),
'#maxlength' => 70,
'#description' => t("You Need To Add Waiter Name. "),
'#required' => 'true'
);

$form['pass_fields'] = array(
  '#type' => 'password_confirm',
  '#description' => t('Enter the same password in both fields'),
);

$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);

return $form;
}

Screen shot of before adding confirm password field

Screen shot of after adding comfirm password field

Your browser autocomplete functionality is responsible for this.

If it's undesirable something like this should fix it:

$form['waiter_name'] = array(
  '#type' => 'textfield',
  '#title' => t('Waiter Name'),
  '#maxlength' => 70,
  '#description' => t("You Need To Add Waiter Name. "),
  '#required' => 'true',
  '#attributes' => array('autocomplete' => 'off'),
);

I would expect just adding it to the name field is enough, the browser shouldn't try to fill the password if it doesn't perceive a username.


DateTime field value is automatically adjusted for the timezone set in Drupal I have a DateTime field in a content type. I set the value as 00:00:00 for the H:m:s. My timezone is set to Europe/Bucharest. Whenever I get the field the value changes to 21:00:00.

Obviously Drupal is adjusting to fit my timezone. I assume, I'm not sure.

I don't want any sort of adjustments to be made. I want the time I've entered.

How can I get the non-adjusted time or disable Drupal adjusting the time?

I am not sure if you can disable it completely, but by changing the site's default timezone to the same timezone as your server, and preventing users from setting their own timezone you should be good.

Both can be configured on /admin/config/regional/settings


Serialization of 'Closure' is not allowed I am getting the following error on .../checkout/ID/order_information page after submitting payment details for Review.

  Exception: Serialization of 'Closure' is not allowed in serialize() (line 14 of core/lib/Drupal/Component/Serialization/PhpSerialize.php).

I have tried to catch the exception with a try/catch block, but it  always gives that fatal error, if I unchecked My billing information is the same as my shipping information checkbox in the Payment information form.

I am using my custom payment method module for payment. Where should I look in the code to find what is causing the fatal error?

__construct() method :-

public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, PaymentTypeManager $payment_type_manager, PaymentMethodTypeManager $payment_method_type_manager, TimeInterface $time) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $payment_type_manager, $payment_method_type_manager, $time);

  if ($this->getMode() === 'test') {
    $url = "url given here";
  }
  else {
    $url = "url given here";
  }

  try {
    $this->soapClient = new SoapClient($url);
  }
  catch (SoapFault $e) {
    throw new PaymentGatewayException($e->getMessage());
  }
}

I believe this comes from loading a connection in the SOAP client, and storing it in memory with $this->soapClient. The problem is that the soap client cannot be serialized. Serialization is the process of turning something into a string, generally so it can be stored in a databse or a file or something, to be retrieved later. The SOAP connection is not something that can be stored, which is why you are facing the issue.

You could potentially store the SOAP client in the construct method, then make the connection using the client when you actually need it. I'm guessing that the client, without a connection, can probably be serialized. I may be wrong though, and you may need to call the soap client dynamically every time you need it.


How to add extra arguments/parameters to ajax callback function? I am using drupal 7. I need to add extra arguments to my ajax callback function. I have five fieldsets in my form, and in all of them same there are same elements, just their IDs are different. For example; group-1, group-2... I need to include that 1,2,3.. part in the callback function as arguments. Otherwise, it will be too complicated to build a logic to predict which fieldset element need to change.

For example, is such a an implementation possible?

function mymodule_form($form, $form_state) {
    $group = 1;

    // Some form elements...

    $form['button'] = array(
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'my_callback_function',
            'wrapper' => 'my_target_area',
            'arguments' => array($group1, ...) // Is such a thing possible or another way?
        ),
    );
}

function my_callback_function($args, $form, $form_state) {
    $arguments = $args;
    return $form['my_target_area'];
}

This question as already been asked here. But I those answers don't fit my needs mentioned above. Thank you.

Drupal doesn't have a mechanism to do that, no. As mentioned in the post you linked to, there's no need to pass that data to Javascript and then back to PHP though - just keep it in the form:

function mymodule_form($form, $form_state) {
  $form['button'] = array(
    '#type' => 'button',
    '#ajax' => array(
      'callback' => 'my_callback_function',
      'wrapper' => 'my_target_area',
    ),
  );

  $form['#foo'] = array($group1, ...);

}

function my_callback_function($form, $form_state) {
  $arguments = $form['#foo'];
  return $form['my_target_area'];
}


How to add a checkbox in checkout form to optionally add 5$ to the product price as a donation? I have a Drupal site using the Drupal Commerce module.

I want to add a checkbox to the checkout form, some thing like this

    = Donate by 5$

If it is checked, then "5$" will added to the selected product price.

Any suggestions?

Have a look at the Commerce Donate module. From its project page:

  This module provides a donation line item type along with a donation product and product display. This is partially based on Randy Fay's excellent screencast at http://commerceguys.com/blog/using-custom-line-items-provide-donation-fe...

  It uses the Select or Other module to provide the donation amount form field. If you need to modify the default donation option values, the install the Commerce Customizable Products module in order to modify the line item type form settings.

  In addition to being able to create a donation product, this module also provides a donation checkout pane, allowing customers to add a donation to their order as part of the checkout process.

Especially the last paragraph seems pretty close to what you're looking for.


Best Way to share content across a UK and USA website I am creating a website that will have a US and UK section and we are going to separate the two via the addresses ....com/uk and ....com/us.

Some of the content will be the same and some of it will differ.  The menu structure will also differ.

The site is relatively small and about half of the content will be shared between the two and half of it will be unique.

We have had had a look at the language/internationalisation modules and they seem a little bit overkill for our needs.

It seems that the best way to achieve this for the shared content is to have a "Shared Page" content type that is never seen, but then a View that accepts a contextual filter in the url (the title) which displays the body of the node at both uk/title and us/title.

However I read somewhere that it is not a good idea to use views to display only a single node and that they should be used only for lists etc.

Is this the case?  If so what method should I use if I want to display a single node at two locations?

We have successfully done this with a multi site installation and the domain module.


Set value for custom field I created a custom field but I don't know how to set a value.
I can read values with

$entity->get('field_myfield')->getValue()[0]['data']

The field consists of several elements: value, data, api_key

I'm loading the entity and would like to set the values of the field programatically, I tried:

$entity->set('field_myfield', ['data' => 'some data'], 'value' => 'some value');

This doesn't work.

You don't need to worry as the entity API should take care of the specific structure and just set it via:

$entity->set('field_myfield', 'some value');
$entity->save();


Edit user profile form I have found many articles about showing sections of the user profile edit page based on $user->roles but none that deal with other custom fields.

For example,

global $user;
if (in_array('administrator', $user->roles)) {

}
else {
  drupal_add_css(drupal_get_path('theme', 'my_theme') . '/css/normal-user.css');
  //Disable admin-only fields
  $fields = array('field_employee_types');
  foreach ($fields as $field) {
    $form[$field]['#disabled'] = TRUE;
  }
}

BUT what I am needing to do is check a custom user profile field (which happens to be a taxonomy term array) and if the user has a certain term,  then do something such as show fields.  Can someone lead me in the right direction?  I am doing all of this in a custom module to alter profile form.

thanks!

So I somewhat got the info to print on the user profile page

[field_affiliation] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [tid] => 28
                        [taxonomy_term] => stdClass Object
                            (
                                ...
                            )
                    )
            )
    )

(upon writing back and forth, the solution to this problem is listed underneath Edit 2)

not sure where exactly you are stuck. are you asking how to check which taxonomy term they have assigned in a field, or how to show/hide fields?

if you already have access to the taxonomy term id and you need to further check the content of the taxonomy term, you can assign that id to a variable like$tid, and then do something like this:

$myfield_term = entity_load('taxonomy_term',array($tid))[$tid];

I find myself doing this a bunch of times, because of the way I use taxonomy terms.
this gives you an object with all the content of the taxonomy term.
if you wanna fetch information out of it, keep in mind that php uses a different approach for objects than for arrays.
so if you need the title value, instead of doing $myfield_term['title'], you need to do $myfield_term->title

EDIT 1:

can you please show us what the structure of the array looks like?
this can be done in various ways. drupal has its own technique of printing arrays (I believe it's caled devel or something), but I still prefer the good old native php way via print_r.

how I'd do it:

assign the array to a value, e.g. $user_apartments
then in the next line add print_r($user_apartments);
switch back to your browser, right click > view page source (may vary depending on your browser, this would be Chrome)

somewhere at the beginning or further down the code (depending on the file that executed the print_r command) should be a printed list of an array, that may look something like this:

Array
(
[0] => 4
[2] => 11
[3] => 28
[4] => ...
)

but it may as well be more complicated than this, if for example it not only lists the term IDs but all the content of the terms as well.

now just grab it and past a part of it here please (if it is a huge list, no need to post the repetitive part)

the way the print_r command works is it takes the object that you feed into it and displays the content in a more human-readable manner, giving you an insight of its structure, whether something is an object, an array, what else it contains etc.

so depending on what this array looks like, we will need to use a different approach on checking the array for your specific ID, this is why I am asking for an insight of the array we want to check.

EDIT 2:

so upon looking at the structure of the array, this is how you check for your term ID:
the array that we need to look at is ...['field_affiliation']['und']. you can (optionally) assign it to a variable, e.g. $field_affiliation, and then do something like this:

$hasDepartment28 = false;
foreach( $field_affiliation as $thisTerm ) {
    if( $thisTerm['tid'] == 28 ) {
        $hasDepartment28 = true;
        break;
    }
}

then, where- and whenever needed, you can simply check by doing

if( $hasDepartment28 ) {
    // do..
}

and here is how it works:

$hasDepartment28: we declare a boolean, and we say by default the department with the term id 28 is not listed
using foreach, we loop through every entry that is listed in the taxonomy term array we named $field_affiliation and every time we assign current entry to the variable name $term
now, as we could see in the structure of the array, what we want to look for is the 'tid' key of every entry
we compare it with the ID you mentioned in the comment below, and if we have a match, we set $hasDepartment28 to TRUE
and via break; we stop the current foreach. since we found what we were looking for, there is no need to loop through any other entry in the array that may come after it
if we found no entry at all where the tid equals 28, the boolean we set earlier will still equal FALSE

let me know if it worked!

keep in mind all the variable names are arbitrary and you should use whatever describes the variable best.

one last thing I'd add is if you were delete and re-create that term entry, you'd have to update this code and check for a different Term ID. perhaps a more readable and future-proof approach would be to check inside the foreach loop for something like:

if( $thisTerm['taxonomy_term']->name == 'Apartment A' ) { ... }

but this in return only works if the [taxonomy_term] gets loaded into your array for every entry. chances are only the first entry has all the term content, but based on the array you submitted I cannot tell you if this is the case. if you wanna stick to this approach though, this is exactly where drupal's entity_load function becomes super useful!


How to use EntityFieldQuery with a simple text field? I have a content type called foo and it has a textfield called field_bar. I have one that has a value set to baz.

I'd like to use the EntityFieldQuery object to find all foos that have field_bar with the baz value.

$nodeQuery = new EntityFieldQuery();
  $nodeQuery->entityCondition('entity_type', 'node', '=')
    ->entityCondition('bundle', 'foo')
    ->fieldCondition('field_bar', 'value', '12345', '=');

The problem is that I get no results or error back. If I remove the fieldCondition, I get all foos including the one I am looking for.

As the documentation is vague and only for experts, I googled a lot, but can't find any reason for my query not returning my node.

I also tried with

->fieldCondition('field_bar', 'value', array('12345'), '=');

to see if that matters, but its the same. I dd-ed the $nodeQuery but can't see the executed SQL.

Is there anything special with textfields?

From the canonical reference on EFQs,

  ->fieldCondition($field, $column = NULL, $value = NULL, $operator =
  NULL, $delta_group = NULL, $language_group = NULL)

  These conditions are specific to a field implementation.

  Looking at the body field in the article node type, a field condition
  would look like this:
  ->fieldCondition('body', 'value', 'A', 'STARTS_WITH')

  field name. Though the field table in the database is named 'field_data_body', the actual field name is 'body'. This is in the
  field_config_instance table.
  column. This is the column in the database that should be matched, with field name prefix removed. For body field, the database columns
  are: body_value, body_summary, body_format, and language. 'value',
  'summary', 'format', and 'language' are the actual arguments you would
  use. Likewise an image field would use 'fid', 'alt', and 'title' as
  column names; an entity reference field would use 'target_id' and
  'target_type' as column names.

So, your syntax is correct, assuming your field name is correct (you want the machiine name), and your column is correct.  Text and Longtext fields both use "value".  You can verify this by looking at the database itself.

If your field name is field_bar, there will be a table called field_data_field_foo.  Look at the columns.  You should see one called field_bar_value.